USE [Timecheck]
GO
/****** Object:  UserDefinedFunction [dbo].[ConvertHoursToMinites]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
--select dbo.ConvertMinsToHours(100)
-- =============================================
CREATE FUNCTION [dbo].[ConvertHoursToMinites](@Hours time)
returns int	
Begin
		RETURN (select LTRIM(DATEDIFF(MINUTE, 0, @Hours)))
	
END

GO
/****** Object:  UserDefinedFunction [dbo].[ConvertMinsToHours]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
--select dbo.ConvertMinsToHours(100)
-- =============================================
CREATE FUNCTION [dbo].[ConvertMinsToHours]
(
	@Mins int
)
RETURNS varchar(10)
AS
BEGIN
	Declare @Converted varchar(10)
	SELECT	@Converted=CASE WHEN @Mins!=0 THEN
			CASE	WHEN LEN(@Mins/60)=1 THEN '0'+(CONVERT(VARCHAR(10),CONVERT(INT,(@Mins/60))))
					ELSE (CONVERT(VARCHAR(10),CONVERT(INT,(@Mins/60))))
			END 
			+':'+
			CASE	WHEN LEN(@Mins%60)=1 then '0'+CONVERT(varchar(10),convert(int,(@Mins%60)))
					ELSE CONVERT(VARCHAR(10),CONVERT(INT,(@Mins%60)))
			END
			else '00:00'
		END
		
	RETURN @Converted
END
GO
/****** Object:  UserDefinedFunction [dbo].[CSVToTable]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE(id int not null)
AS
BEGIN    
	SET @InStr = REPLACE(@InStr + ',', ',,', ',')
	DECLARE @SP INT
	DECLARE @VALUE VARCHAR(1000)
	WHILE PATINDEX('%,%', @INSTR ) <> 0 
	BEGIN
	   SELECT  @SP = PATINDEX('%,%',@INSTR)
	   SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
	   SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
	   INSERT INTO @TempTab(id) VALUES (@VALUE)
	END
	RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[DateOnly]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  function [dbo].[DateOnly](@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
begin
    return dateadd(dd,0, datediff(dd,0,@DateTime))
end
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_CheckCurrentDayIsWeeklyOff]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- select * from dbo.Fn_CheckCurrentDayIsWeeklyOff(1,'20220709')
-- =============================================
CREATE FUNCTION [dbo].[Fn_CheckCurrentDayIsWeeklyOff]
(	
	-- Add the parameters for the function here
	@COMPANYID bigint
)
RETURNS @TempWeeklyOff TABLE(WeekOffDay varchar(10))
AS
Begin
	INSERT INTO @TempWeeklyOff
	SELECT 'Monday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and mon=1		UNION ALL
	SELECT 'Tuesday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and tues=1	UNION ALL
	SELECT 'Wednesday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and wed=1	UNION ALL
	SELECT 'Thursday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and thurs=1	UNION ALL
	SELECT 'Friday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and fri=1		UNION ALL
	SELECT 'Saturday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and satur=1	UNION ALL
	SELECT 'Sunday' from TA_Tbl_ShiftSettings where CompanyId=@COMPANYID and sun=1
	RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_ConvertDateAndTimeFromString]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- select dbo.Fn_ConvertDateAndTimeFromString('20210430170059')
-- =============================================
CREATE FUNCTION [dbo].[Fn_ConvertDateAndTimeFromString]
(
	-- Add the parameters for the function here
	@passingValue varchar(20)
)
RETURNS datetime
AS
BEGIN
	Declare @Number varchar(20)
	set @Number=@passingvalue
	declare @ShiftDate datetime
	set @ShiftDate=SUBSTRING(@number,1,8)
	Declare @First int
	declare @Second int
	declare @Third int
	set @First=substring(@number,9,2)
	set @Second=SUBSTRING(@number,11,2)
	set @Third=SUBSTRING(@number,13,2)


	-- Return the result of the function
	RETURN convert(datetime, @ShiftDate + CONVERT(datetime, right('00'+convert(varchar(20),@First),2)+':'+convert(varchar(20),@Second)+':'+right('00'+convert(varchar(20),@Third),2)))

END
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_GetWholeLevelName]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Fn_GetWholeLevelName]
(
	@empLevelID bigint
)
RETURNS varchar(500)
AS
BEGIN
	declare @fullLevelName varchar(max)
	;WITH ChildLevelDetails as
	(
		SELECT id,parentid,name FROM ta_tbl_leveldetails ld where id=@empLevelID
		union all
		select LD.id,LD.parentid,LD.name from ChildLevelDetails CD
		inner join ta_tbl_leveldetails LD on CD.parentid=ld.id
		
	)
	select @fullLevelName=coalesce(@fullLevelName+' / ','')+name from ChildLevelDetails order by parentId
	-- Return the result of the function
	RETURN @fullLevelName  
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_KeepNumInt]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select dbo.[fn_KeepNumInt]('Man12kadn454')
CREATE function [dbo].[fn_KeepNumInt]
(
	@mixedNumStr varchar(15)
) 
returns int as
begin
	BEGIN 
		WHILE PATINDEX('%[^0-9]%',@mixedNumStr)> 0 
		SET @mixedNumStr = REPLACE(@mixedNumStr,SUBSTRING(@mixedNumStr,PATINDEX('%[^0-9]%',@mixedNumStr),1),'') 
	END 
	return CAST(@mixedNumStr as int)
end
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_ReplaceCharacter]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Fn_ReplaceCharacter]
(
	@expression varchar(max),
	@replaceChar char(1)
)
RETURNS varchar(20)
AS
BEGIN
	Declare @newChar varchar(20)
	select @newChar=replace(@expression,'&amp;',@replaceChar)
	RETURN @newChar 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_RoundoffHours]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Fn_RoundoffHours]
(
	@INSWIPECARDNO VARCHAR(50),
	@INDATE DATETIME,
	@ClockTime Datetime,
	@flag char(1)
)
RETURNS datetime
AS
BEGIN	
	--set @ShiftStartime='08:00 am'
	Declare @mins int
	Declare @returnValue datetime	
	set @mins=DATEPART(minute,@ClockTime)	
	if(@flag='I')
	begin
		declare @ShiftStartime varchar(20)
		Declare @ShiftID int
		select @shiftid=shift_id from ta_tbl_processeddata where employee_code_id=@INSWIPECARDNO and date=@inDate
		select @ShiftStartime=shift_starttime  from ta_tbl_shift where shift_id=@shiftid
		select @returnValue= case when @ClockTime<cast(convert(varchar(11),@ClockTime) as datetime)+' '+ @ShiftStartime then cast(convert(varchar(11),@ClockTime) as datetime)+' '+ @ShiftStartime
		else 
			case	when @mins<=44 then 
						convert(datetime,dateadd(minute, 0-@mins,@ClockTime))
					else 
						convert(datetime,dateadd(minute, 60-@mins,@ClockTime))
			end
		end
	end
	else if(@flag='O')
	begin
			select @returnValue= case	when @mins<=44 then 
						convert(datetime,dateadd(minute, 0-@mins,@ClockTime))
					else 
						convert(datetime,dateadd(minute, 60-@mins,@ClockTime))
			end
	end

	-- Return the result of the function
	RETURN @returnValue

END
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_TA_ConvertTimeZoneDT]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================

-- Select UTC_CLKDate,UTC_CLKTime From [dbo].[Fn_TA_ConvertTimeZoneDT] ('2024-01-24','11:20 AM','BB006')

CREATE FUNCTION [dbo].[Fn_TA_ConvertTimeZoneDT]
(	
	-- Add the parameters for the function here
	@CLKDateTime Date='2024-01-24 00:00:00.000',
	@CLKTime nvarchar(20)='11:20 AM',
	@CLKCardNo nvarchar(120)='BB006'
)
RETURNS @TimezoneDT TABLE (UTC_CLKDate DaTeTime,UTC_CLKTime nvarchar(30))
AS
Begin
	
	Declare @EmployeeAutoID int

	Declare @ConcatUTCTime nvarchar(max)

	DECLARE @ConvertedDate NVARCHAR(50);
	DECLARE @ConvertedTime NVARCHAR(50);

	Select  @EmployeeAutoID=isnull(Employee_Id,0) From TA_Tbl_Employee where SwipeCardNo=@CLKCardNo
	
	if(@EmployeeAutoID!=0)
	begin
		declare @offsetHours INT
		declare @offsetMinutes INT
		DECLARE @ConvertTimezoneformat nvarchar(max)
	
		Select @offsetHours=HoursToBeAdded,@offsetMinutes=MinToBeAdded
		from TA_Tbl_EmployeeLevel
		Inner Join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id =TA_Tbl_EmployeeLevel.LevelId
		Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
		Inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id =  TA_Tbl_EmployeeLevel.EmployeeId
		Where TA_Tbl_Employee.Employee_Id =@EmployeeAutoID
	 

		--SET @ConcatUTCTime = CONVERT(NVARCHAR(100), @CLKDateTime, 23) + ' ' + CONVERT(NVARCHAR(8), CONVERT(TIME, @CLKTime, 102));

		-- Concatenate and format
		DECLARE @combinedStr NVARCHAR(30) = CONCAT(@CLKDateTime, ' ', @CLKTime);

		-- Convert to datetime and format the result in the desired format
		DECLARE @utcDateTime NVARCHAR(30) = CONVERT(NVARCHAR(30), CONVERT(DATETIME, @combinedStr, 0), 127);

		-- Display the result
		 	
		SELECT @ConvertTimezoneformat=(DATEADD(MINUTE, @offsetMinutes, DATEADD(HOUR, @offsetHours, @utcDateTime))) 
		DECLARE @TimezoneDTFomat NVARCHAR(30) = CONVERT(NVARCHAR(30), CONVERT(DATETIME, @ConvertTimezoneformat, 100), 120);

		SET @ConvertedDate = CONVERT(DATE, @TimezoneDTFomat)
		SET @ConvertedTime = FORMAT(CONVERT(DATETIME, @TimezoneDTFomat), 'hh:mm tt');


		insert into @TimezoneDT values(@ConvertedDate,@ConvertedTime)

	End
	Else
	begin
		insert into @TimezoneDT values(@CLKDateTime,@CLKTime)
			
	End

	Return 

End
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_CountNumberOfWorkingDays]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <Create Date,,>    
-- Description: <Description,,>    
-- fn_TA_CountNumberOfWorkingDays 44    
-- =============================================    
CREATE function [dbo].[fn_TA_CountNumberOfWorkingDays]    
(
--@MonthClosureID int
@FromDate   nvarchar(20),    
@ToDate   nvarchar(20)    
)  
  RETURNS int   
AS    
BEGIN    
 declare @days as int    
-- declare @FromDate as nvarchar(20)    
-- declare @ToDate as nvarchar(20)    
-- Count number of days in a month    
 --select @FromDate = MonthClosure_StartDate ,@ToDate= MonthClosure_EndDate, @days=datediff(d,MonthClosure_StartDate,MonthClosure_EndDate)+1    
 --from ta_tbl_monthclosure where monthClosure_id=@MonthClosureID    
--End of count number of days in a month    
set @days=datediff(d,@FromDate,@ToDate)+1  
  declare @Mon as int    
  declare @year as int    
  declare @IsHoliday as int    
  set @IsHoliday=0      
  declare @CurDate as nvarchar(25)    
  Declare @Count as int    
  set @Count = 0    
  declare @StartDay as int    
  set @StartDay=1    
  declare @TotHoliday as int    
  set @TotHoliday = 0    
  declare @iFlag as int    
  set @iFlag = 0    
  while @startDay<=@days    
  Begin    
-- 1 = sunday      
   if (datepart(dw,dateadd(d,@iFlag,@FromDate))=1)    
   Begin    
    set @count = @count + 1    
   End     
   set @StartDay= @StartDay + 1    
   set @iFlag= @iFlag+1    
  End    
 Declare @Holiday as int    
 set @Holiday = (select isnull(sum (datediff(day,holiday_fromDate,dateadd(day,1,holiday_toDate))),0)  from ta_tbl_holiday where holiday_type='G'  and     
  (((@FromDate between holiday_fromDate and holiday_toDate)or    
  @ToDate between holiday_fromDate and holiday_toDate))     
  or (holiday_fromDate between @FromDate and @ToDate or (holiday_toDate between @FromDate and @ToDate))    
  )    
 --select @days - @count - @Holiday  as TotWorkingDays    
 return  @days - @count - @Holiday  
END    
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetEmployeeWorkingHours]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <Create Date,,>    
-- Description: <Description,,>    
-- fn_TA_CountNumberOfWorkingDays 44    
-- =============================================    
CREATE function [dbo].[fn_TA_GetEmployeeWorkingHours]    
(
@EmployeeID int
)  
RETURNS numeric(9,2)   
AS    
BEGIN    
	declare @WorkHours numeric(9,2)    
	select @WorkHours= round(catmas.MonToSat_WorkHrs/6,1) from TA_Tbl_EmployeeCategory cat 
	inner join TA_Tbl_Employee emp on emp.Employee_Id = cat.EmployeeId 
	inner join TA_Tbl_Category catmas on catmas.CategoryId=cat.CategoryId 
	where SwipeCardNo =@EmployeeID
return @WorkHours
END    
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_ReportingTo]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from fn_TA_GetMappedEmployees_ReportingTo (2)
CREATE FUNCTION [dbo].[fn_TA_GetMappedEmployees_ReportingTo] 
(
	@Employee_Id INT
)
RETURNS @tblReportingEmployees TABLE 
(
	reportingEmpID INT NULL
)
AS
BEGIN
	INSERT INTO @tblReportingEmployees VALUES(@Employee_Id)
	INSERT INTO @tblReportingEmployees SELECT Employee_ID FROM TA_Tbl_Employee WHERE Reporting_To = @Employee_Id AND Isdeleted=0
	RETURN 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_SancAuthority]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from fn_TA_GetMappedEmployees (27)
CREATE FUNCTION [dbo].[fn_TA_GetMappedEmployees_SancAuthority] 
(
	@Employee_Id int
)
RETURNS @tblReportingEmployees TABLE 
(
	reportingEmpID int null
)
AS
BEGIN
	INSERT INTO @tblReportingEmployees VALUES(@Employee_Id)
	INSERT INTO @tblReportingEmployees SELECT Employee_ID FROM TA_Tbl_Employee WHERE Leave_Sanc_Authority = @Employee_Id AND Isdeleted=0
	RETURN 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetParentChild]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--	Author	   :	<Author,,Name>
--	Create date:	<Create Date,,>
--	Description:	<Description,,>
--	Modified by:	Manikandan.R
--	Modified on:	31-May-2019 11:19
-- =============================================
--select * from dbo.[fn_TA_GetParentChild]('superadmin',4)order by ParentChildId
CREATE FUNCTION [dbo].[fn_TA_GetParentChild] 
(
	@UserGroupName varchar(max), 
	@parent_id int
)
RETURNS @TA_Tbl_ReturnParentChild TABLE (ParentChildId int null)
AS
BEGIN
	DECLARE @UserGroupId INT
	SELECT @UserGroupId=GroupId FROM TA_Tbl_UserGroup WHERE groupName=@UserGroupName and IsDeleted=0 	
	IF(@parent_id<>0)
	BEGIN
		;WITH ChildLevelDetails as
		(
			SELECT LR.LevelId as selectedParent_Child FROM TA_Tbl_LevelRights LR
			INNER JOIN Ta_Tbl_levelDetails LD on LR.LevelId=LD.id
			WHERE GroupId=@UserGroupId and LD.isDeleted=0 and LD.id=@parent_id
			UNION ALL
			SELECT LR.LevelId from TA_Tbl_LevelRights LR
			INNER JOIN Ta_Tbl_levelDetails LD on LR.LevelId=LD.id
			INNER JOIN ChildLevelDetails CL ON CL.selectedParent_Child = ld.parentId
			WHERE GroupId=@UserGroupId and LD.isDeleted=0
		)
		INSERT INTO @TA_Tbl_ReturnParentChild
		SELECT selectedParent_Child FROM ChildLevelDetails order by selectedParent_Child
	END
	ELSE
	BEGIN
		INSERT INTO @TA_Tbl_ReturnParentChild
		SELECT LevelId FROM TA_Tbl_LevelRights WHERE GroupId=@UserGroupId
	END
	RETURN 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_TA_GetBranchName]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
-- Select dbo.Fun_TA_GetBranchName(2)

CREATE FUNCTION [dbo].[Fun_TA_GetBranchName]
(
	-- Add the parameters for the function here
	@levelId int
)
RETURNS varchar(50)
AS
BEGIN
	-- Declare the return variable here
	Declare @BranchName varchar(50)

	--select @BranchName
	-- Add the T-SQL statements to compute the return value here

	set @BranchName=(Select Name From Ta_Tbl_levelDetails where id=@levelId)

	-- Return the result of the function
	RETURN @BranchName
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_TA_GetDateFormat]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
/*
Select [Fun_TA_GetDateFormat] 
*/
-- =============================================
CREATE FUNCTION [dbo].[Fun_TA_GetDateFormat]()
RETURNS Varchar(3)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- Return the result of the function
	RETURN @dateFormat
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_TA_GetLevelForEmployeeTransfer]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Fun_TA_GetLevelForEmployeeTransfer]
(
	@Date Date,
	@EmployeeID int 
)
RETURNS int
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ResultVar int

	-- Add the T-SQL statements to compute the return value here
	--Declare @Date Datetime , @EmployeeID int 

Select @ResultVar= NwLevelID from TA_Tbl_EmployeeTransferModule where @Date between EmployeeTrans_fr_Date and isnull(EmployeeTrans_To_Date,
getdate())
 and EmployeeId = @EmployeeID
	-- Return the result of the function
	RETURN @ResultVar

END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_AbsentDate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 26-July-2010
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_AbsentDate] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @Absent as varchar(8000)
--set @Absent=''
 SELECT @Absent = ISNULL(@Absent + ', ', '') + 
 case when  FNAttendanceCode='Absent' and ANAttendanceCode='Absent' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+'(FS)')
      when  FNAttendanceCode='Absent' and ANAttendanceCode <> 'Absent' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+'(F)')
      when FNAttendanceCode <> 'Absent' and ANAttendanceCode='Absent' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+'(S)')
      else ''
      end
 FROM TA_Tbl_ProcessedData pd
inner join ta_tbl_employee emp on emp.SwipeCardNo=pd.Employee_Code_Id
where emp.Employee_Code_Id = @empId 
and Date between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@ToDat as nvarchar(50)) , 102)
and (FNAttendanceCode='Absent' or ANAttendanceCode='Absent')
and emp.Report_Exclude=0
return isnull(@Absent,'')
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpCategory]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpCategory] 
(
	@todat datetime,@Employee_Code_Id varchar(50), @employeeCategory int
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	CategoryId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + ' And SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
--		End
--	if not(@EmployeeId='' or @EmployeeId='0')  
--		begin  
--			set @sqlCommon = @sqlCommon + ' and (Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
--		end 
if (@Employee_Code_Id<>'')
		if(@employeeCategory<>0 and @employeeCategory!='')
		BEGIN	
		INSERT @Emptest
		select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100)) and ECategory.CategoryId=@employeeCategory
		End
		else
		BEGIN	
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))
		End	
else 
	Begin
	if(@employeeCategory<>0 and @employeeCategory!='')
		BEGIN	
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and ECategory.CategoryId=@employeeCategory
		End
		else 
		Begin
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
	end 
	End
RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpDesignation]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpDesignation] 
(
	@todat datetime,@Employee_Code_Id varchar(50),@DesignationId varchar(50)
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	DesignationId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + ' And SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
--		End
--	if not(@EmployeeId='' or @EmployeeId='0')  
--		begin  
--			set @sqlCommon = @sqlCommon + ' and (Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
--		end 
if (@Employee_Code_Id<>'')
if(@DesignationId<>0 and @DesignationId!='')
		BEGIN	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100)) and ED.DesignationId=@DesignationId
		End
		else
	begin	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	
	End
else 
if(@DesignationId<>0 and @DesignationId!='')
		BEGIN	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	    and ED.DesignationId=@DesignationId
		End
		else
	Begin
		INSERT @Emptest
		select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null		
	end 
RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpLevel]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization

-- Select * From [dbo].[Func_TA_EmpLevel] ('20221220','1003')
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpLevel] 
(
	@todat datetime,@Employee_Code_Id varchar(50)
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	LevelId int,
	EffectiveDate datetime,
	Employee_Code_Id varchar(50),
	SwipeCard varchar(50)
)
AS
BEGIN
if (@Employee_Code_Id<>'')
	begin	
		INSERT @Emptest
		select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	
	End
else 
BEGIN
		INSERT @Emptest
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	END
RETURN
END


GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpType]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpType] 
(
	@todat datetime,@Employee_Code_Id varchar(50),@employeeType int
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	TypeId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + ' And SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
--		End
--	if not(@EmployeeId='' or @EmployeeId='0')  
--		begin  
--			set @sqlCommon = @sqlCommon + ' and (Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
--		end 
if (@Employee_Code_Id<>'')
		if(@employeeType<>0 and @employeeType!='')
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	and EType.TypeId=@employeeType
		End
		else
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))
		End	
else 
	Begin
	if(@employeeType<>0 and @employeeType!='')
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and EType.TypeId=@employeeType
		End
		else 
		Begin
		INSERT @Emptest
	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null	
	end 
	End
RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetDateTimeFormat]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-11-2016
-- Description:	GetDate And Time Format
-- Select * from [Func_TA_GetDateTimeFormat]()
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GetDateTimeFormat]()
RETURNS 
@DatetimeFormat TABLE 
(
	DateFormat int,
	TimeFormat nvarchar(50)
)
AS
BEGIN
	DECLARE @dateFormat as INT
	DECLARE @date as nVARCHAR(25)			
	DECLARE @TimeFormat as nvarchar(25)
	SELECT @TimeFormat=TimeFormat,@date = DateFormat FROM TA_Tbl_DateandTimeFormat
	IF(@date='dd/MM/yyyy')
	BEGIN
		SET @dateFormat = 103
	END
	ELSE IF(@date='MM/dd/yyyy')
	BEGIN
		SET @dateFormat = 101
	END
	ELSE
	BEGIN
		SET @dateFormat = 106
	END	
	insert into @DatetimeFormat values (@dateFormat,@TimeFormat)
	RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetOrganizationNamedetails]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 23-dec-2020
-- Description:	Get Name of the selected sites
-- select dbo.[Func_TA_GetOrganizationNamedetails](61)
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GetOrganizationNamedetails]
(
	-- Add the parameters for the function here
	@id int
)
RETURNS nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ResultVar nvarchar(Max)=''
	declare @Start int=1, @loop int=1
	-- Add the T-SQL statements to compute the return value here
	while(@Start<=@loop)
		begin
			if exists(select * from Ta_Tbl_levelDetails where id=@id and parentId=0)
				begin
					set @ResultVar= '<p><b>' +(select levelName from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) + SPACE(15) + '</b>' + Space(14) + ' : ' + (select name from Ta_Tbl_levelDetails where id=@id) + case when @ResultVar='' then ' <br></p>' else  '<br></p>'  end + @ResultVar
					set @loop=@loop-1
				end
			else
				begin
					if exists(select name from Ta_Tbl_levelDetails where id=@id)
					begin
						set @ResultVar= '<p><b>' + (select levelName from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) + SPACE(15) + '</b>' + Space(14) + ' : ' + (select name from Ta_Tbl_levelDetails where id=@id)  + case when @ResultVar='' then '</p>' else '<br></p>' end + @ResultVar
						select @id=parentId from Ta_Tbl_levelDetails where id=@id
						set @loop=@loop+1
					end
					else
					begin
						set @loop=@loop-1	
					end
				end
			set @Start=@Start+1
		end
	RETURN @ResultVar
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetParentIds]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Select  [dbo].[Func_TA_GetParentIds](7)
CREATE function [dbo].[Func_TA_GetParentIds]
(
@LevelId as varchar(500)
)
returns varchar(500)
as
begin
	declare @ParentLevelId as varchar(250)
	declare @LevelIdFinal as varchar(250)
	declare @Pos as int
	declare @Id as int
	declare @TableCount as int
	declare @OrgninId as int;
	set @LevelId=@LevelId;
	declare @TempLevelId table 
	(
	SlNo int identity(1,1) not null,
	LevelId int
	)
	insert into @TempLevelId
	select Value from dbo.Split(@LevelId,',')
	set @TableCount=(select COUNT(*) from @TempLevelId)
	set @Pos=1;
	while (@Pos<=@TableCount)
	begin
		set @Id=(select LevelId from @TempLevelId where SlNo=@Pos)
		while (@Id>0)
		begin
			set @ParentLevelId=(select isnull(parentId,0) from Ta_Tbl_levelDetails where id in (@Id));
			set @OrgninId=@Id;
			set @Id=@ParentLevelId;		
		end
		set @LevelIdFinal= COALESCE(@LevelIdFinal + ',', '')+cast(@OrgninId as varchar(100));
		set @Pos=@Pos+1;
	end
	RETURN @LevelIdFinal
end
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetRemarks]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GetRemarks]
(
	@EmployeeID varchar(25),
	@StartDate datetime,
	@EndDate datetime,
	@Type varchar(100) -- Absent, Sick, Annual
	--@Day as varchar(3) -- 1.0 - full day , 0.5 - half day
)
RETURNS varchar(8000)
AS
BEGIN
	DECLARE @Remarks VARCHAR(8000)
	DECLARE @Remarks1 VARCHAR(8000)
	if (@Type='Absent')
		Begin
			SELECT @Remarks = ISNULL(@Remarks + ', ', '') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where attendance = @type and employee_code_id= @EmployeeID and totaldays='1.0'
			and (date >= @StartDate and date <= @EndDate)
			order by date
			SELECT @Remarks1 = ISNULL(@Remarks + ', ', '') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where attendance = @type and employee_code_id= @EmployeeID and totaldays='0.5'
			and (date >= @StartDate and date <= @EndDate)
			order by date
		End
	Else
		Begin
			SELECT @Remarks = ISNULL(@Remarks + ', ', '') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where LeaveCode = @type and employee_code_id= @EmployeeID and totaldays='1.0'
			and (date >= @StartDate and date <= @EndDate)
			order by date
			SELECT @Remarks1 = ISNULL(@Remarks + ', ', '') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where LeaveCode = @type and employee_code_id= @EmployeeID and totaldays='0.5'
			and (date >= @StartDate and date <= @EndDate)
			order by date
		End
	set @Remarks1 = ' And ' + @Remarks1	+ ' is 0.5 day'
	return @Remarks +  ' ' + isnull(@Remarks1,'')
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Description,,>
-- select * from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](2,'03/01/2017 06:00 PM',1,'03/01/2017')
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]
(	
	@CompanyId int,
	@InPunchTime varchar(30),
	@Selectby int,
	@Date datetime
)
RETURNS @Final TABLE(NearShift varchar(max),Differences int,ShiftID int,Shift_StartTime varchar(20),Orderby int)
AS
BEGIN	
	DECLARE @TimeFormat as nvarchar(10)
    SELECT @TimeFormat=TimeFormat FROM TA_Tbl_DateandTimeFormat
	INSERT INTO @Final
	 select *,RANK()over(order by diff) from 
	   (
			select Shift_ShortName +': '+
			case   when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex(':',Shift_StartTime)))=1 then '0'+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,@Date+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,@Date+Shift_StartTime,@InPunchTime)
				  else datediff(minute,@Date+Shift_StartTime,@InPunchTime) end as diff,Shift_Id,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!='No Shift' and shift_shortName!='NOS' 
		   union all
		   select Shift_ShortName +': '+
			case   when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex(':',Shift_StartTime)))=1 then '0'+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)
				  else datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime) end as diff,Shift_Id,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!='No Shift' and shift_shortName!='NOS' 
	   )as a order by RANK()over(order by diff),Shift_StartTime
	RETURN
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:           <R.Manikandan>
-- Create date: <04-11-2016>
-- Description:      <Get the closed shift details>
-- select dbo.[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](2,'03/01/2017 06:00 pM',1,'03/01/2017')
-- select * from ta_tbl_leveldetails
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]
(
       -- Add the parameters for the function here
       @CompanyId int,
       @InPunchTime varchar(30),
       @Selectby int,
	   @Date datetime
)
RETURNS varchar(max)
AS
BEGIN
       -- Declare the return variable here
       DECLARE @Final TABLE(NearShift varchar(max),Differences int,Shift_StartTime varchar(20),Orderby int)
       DECLARE @TimeFormat as nvarchar(10)
       SELECT @TimeFormat=TimeFormat FROM TA_Tbl_DateandTimeFormat
       -- Add the T-SQL statements to compute the return value here
       Insert into @Final
       select *,RANK()over(order by diff) from 
	   (
			select Shift_ShortName +': '+
			case   when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex(':',Shift_StartTime)))=1 then '0'+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,@Date+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,@Date+Shift_StartTime,@InPunchTime)
				  else datediff(minute,@Date+Shift_StartTime,@InPunchTime) end as diff,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!='No Shift' and shift_shortName!='NOS' 
		   union all
		   select Shift_ShortName +': '+
			case   when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex(':',Shift_StartTime)))=1 then '0'+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)
				  else datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime) end as diff,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!='No Shift' and shift_shortName!='NOS' 
	   )as a
       Declare @FinalData varchar(max)
       select @FinalData=coalesce(@FinalData+';','')+ NearShift from @Final where orderby=@Selectby order by Orderby,Shift_StartTime
       -- Return the result of the function
       RETURN (@FinalData)
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_LeaveDate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_LeaveDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @LeaveDate VARCHAR(8000)
 -- + ' (' + cast(NumberOfDays as varchar(5)) + ') '
 SELECT @LeaveDate = ISNULL(@LeaveDate + ', ', '') + 
 case when  leave_fromdate=leave_todate then replace(convert(varchar(20),leave_fromdate,106)+'('+ cast(NumberOfDays as varchar(5))+')',' ','-')
      else  replace(convert(varchar(20),leave_fromdate,106),' ','-') + ' - ' +  replace(convert(varchar(20),leave_todate,106)+'('+ cast(NumberOfDays as varchar(5))+')',' ','-')
      end
 FROM TA_Tbl_LeaveApplication
 where Employee_id = @EmpId and isdeleted=0 and Status='Approved' and (((CONVERT(DATETIME, cast(@fromDat as nvarchar(50))  , 102) between Leave_FromDate and Leave_ToDate) or (CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102) between Leave_FromDate and Leave_ToDate) )
 or (Leave_FromDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102)) or (Leave_ToDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50)) , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)))
 return isnull(@LeaveDate,'')
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_LoadSpace]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 23-dec-2020
-- Description:	Get Name of the selected sites
-- select dbo.[Func_TA_GetOrganizationNamedetails](61)

-- Select [dbo].[Func_TA_LoadSpace](2)
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_LoadSpace]
(
	-- Add the parameters for the function here
	@UserID nvarchar(20),
	@id bigint,
	@tableName nvarchar(200)
)
RETURNS nvarchar(MAX)
AS
BEGIN
	-- Declare the return variable here
	-- Declare the return variable here
	DECLARE @ResultVar nvarchar(Max)='EmployeeId,',@ResultVar1 nvarchar(Max)=''''+cast(@UserID as nvarchar(20))+''','
	declare @Start int=1, @loop int=1
	-- Add the T-SQL statements to compute the return value here
	while(@Start<=@loop)
		begin
			--Set @ResultVar='insert into @Emptest('
			if exists(select * from Ta_Tbl_levelDetails where id=@id and parentId=0)
				begin
					Set @ResultVar = @ResultVar + 'Level'+ cast((select levelID from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) as varchar(10)) +'Name' + ', '+ 'Level'+ cast((select levelID from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) as varchar(10)) +'Details,'
					Set @ResultVar1 = @ResultVar1 + '''' + (select levelName from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) + ''', '''+ (select name from Ta_Tbl_levelDetails where id=@id) + ''',' 
					set @loop=@loop-1
				end
			else
				begin
					if exists(select name from Ta_Tbl_levelDetails where id=@id)
					begin
						Set @ResultVar = @ResultVar + 'Level'+ cast((select levelID from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) as varchar(10)) +'Name' + ', '+ 'Level'+ cast((select levelID from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) as varchar(10)) +'Details,'
						Set @ResultVar1 = @ResultVar1 + '''' + (select levelName from TA_Tbl_Level L where L.levelID=(select levelId from Ta_Tbl_levelDetails where id=@id)) + ''', '''+ (select name from Ta_Tbl_levelDetails where id=@id) + ''',' 
						select @id=parentId from Ta_Tbl_levelDetails where id=@id
						set @loop=@loop+1
					end
					else
					begin
						set @loop=@loop-1	
					end
				end
			set @Start=@Start+1
		end
	set @ResultVar='insert into '+ @tableName +'(' + left(@ResultVar, len(@ResultVar)-1) +') values (' + left(@ResultVar1, len(@ResultVar1)-1) +')'
	RETURN @ResultVar
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_MusterRoll_OD_Notation]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	19-02-2014
-- Description	:	Muster Roll On Duty Notation
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_MusterRoll_OD_Notation] 
(
	@Date DATETIME,
	@AttendanceCode NVARCHAR(50),
	@EmployeeCodeId NVARCHAR(15),
	@AttendType NVARCHAR(2),
	@ShiftId INT,
	@ReplaceText NVARCHAR(50)
)
RETURNS NVARCHAR(15)
AS
BEGIN	
	DECLARE @RecCount INT
	DECLARE @OnDutyText NVARCHAR(15), @ShiftStartTime NVARCHAR(20), @Shift_SecondHalf_Starttime NVARCHAR(20), @ShiftEndtime NVARCHAR(20)
	IF(@ShiftId = -1)
		SELECT @ShiftId = PD.Shift_Id FROM TA_Tbl_ProcessedData PD WHERE PD.[Date] = DATEADD(D, -1, @Date) AND PD.Employee_Code_Id = @EmployeeCodeId
	IF(@ShiftId = -1)
		SELECT @ShiftId = PD.Shift_Id FROM TA_Tbl_ProcessedData PD WHERE PD.[Date] = DATEADD(D, -2, @Date) AND PD.Employee_Code_Id = @EmployeeCodeId
	IF(EXISTS (SELECT S.Shift_EndTime FROM TA_Tbl_Shift S WHERE S.Shift_Id = @ShiftId))
		SELECT @ShiftStartTime = S.Shift_StartTime, @Shift_SecondHalf_Starttime = S.Shift_SecondHalf_StartTime, @ShiftEndtime = S.Shift_EndTime FROM TA_Tbl_Shift S WHERE S.Shift_Id = @ShiftId
	SET @OnDutyText = @ReplaceText
	IF((CHARINDEX('PM', @ShiftStartTime) > 0) AND (CHARINDEX('AM', @ShiftEndtime) > 0))
	BEGIN
		IF(CHARINDEX('AM', @Shift_SecondHalf_Starttime)>0)
		BEGIN
			IF(@AttendType = 'FN')
			BEGIN
				SELECT @RecCount = COUNT(MTE.IsOnDuty) FROM TA_Tbl_ManualTimeEntry MTE
				WHERE MTE.ManualTimeEntry_InDate = @Date
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
									or
									cast(ManualTimeEntry_OutTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
						end
					else
						begin
							set @RecCount=
							(
								select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
								where ManualTimeEntry_OutDate = case when ((CHARINDEX('PM',ManualTimeEntry_InTime)>0) and (CHARINDEX('AM',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
									or
									cast(ManualTimeEntry_OutTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
							)
						end
				End
			else if(CHARINDEX('PM',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType='FN')
						begin
							set @RecCount=
							(
								select count(IsOnDuty) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date			
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < cast(@Shift_SecondHalf_Starttime as datetime)
									or
									case when CHARINDEX('AM',ManualTimeEntry_OutTime)>0 then
														dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime)) else cast(ManualTimeEntry_OutTime as datetime) end < cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
							)
						end
			else
				begin
						set @RecCount=
						(
							select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate = case when ((CHARINDEX('PM',ManualTimeEntry_InTime)>0) and (CHARINDEX('AM',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
							and 
							(
								cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								or
								case when CHARINDEX('AM',ManualTimeEntry_OutTime)>0 then
								(dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime))) else (cast(ManualTimeEntry_OutTime as datetime)) end  > cast(@Shift_SecondHalf_Starttime as datetime)
							)
							and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
						)
				end
		End
End
else
Begin
	if(@AttendType='FN')
	begin
		set @RecCount=(select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_InDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) < @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) < @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status='Approved'
		)
	end
	else
	begin
		set @RecCount=(select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_OutDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) > @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) > @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status='Approved'
		)
	end
End
if(@RecCount>0)
begin
	if(@AttendanceCode='Present' or @AttendanceCode='Weekly Off' or @AttendanceCode='Holiday')
	begin
		set @OnDutyText='OD'
	End
end
RETURN @OnDutyText
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_OnDuty]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 17-02-2014
-- Description:	Modified for weekly off records
-- =============================================
----select [dbo].[Func_TA_OnDuty]('2015/10/03','Present',100,'FN','09:00 AM','01:30 PM','06:00 PM',1,4,'04:30')
CREATE FUNCTION [dbo].[Func_TA_OnDuty] 
(
	@Date as datetime,
	@AttendanceCode as varchar(50),
	@EmployeeCodeId as nvarchar(15),
	@AttendType as varchar(2),
	@ShiftStartTime varchar(20),
	@Shift_SecondHalf_Starttime varchar(20),
	@ShiftEndtime varchar(20),
	@isFlexible int,
	@Shiftid int,
	@TotWrkHrs varchar(10)
)
RETURNS varchar(15)
AS
BEGIN	
	declare @recCount as int
	declare @OnDutyText as varchar(15)
	set @OnDutyText=''
	if((charindex('PM',@ShiftStartTime) > 0) and (charindex('AM',@ShiftEndtime) > 0))
		Begin
			if(charindex('AM',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType='FN')
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
									or
									cast(ManualTimeEntry_OutTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
							)
						end
					else
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry 
								where ManualTimeEntry_OutDate = case when ((charindex('PM',ManualTimeEntry_InTime)>0) and (charindex('AM',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
									or
									cast(ManualTimeEntry_OutTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
							)
						end
				End
			else if(charindex('PM',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType='FN')
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date			
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < cast(@Shift_SecondHalf_Starttime as datetime)
									or
									case when charindex('AM',ManualTimeEntry_OutTime)>0 then
														dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime)) else cast(ManualTimeEntry_OutTime as datetime) end < cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
							)
						end
			else
				begin
						set @recCount=
						(
							select count(*) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate = case when ((charindex('PM',ManualTimeEntry_InTime)>0) and (charindex('AM',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
							and 
							(
								cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								or
								case when charindex('AM',ManualTimeEntry_OutTime)>0 then
								(dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime))) else (cast(ManualTimeEntry_OutTime as datetime)) end  > cast(@Shift_SecondHalf_Starttime as datetime)
							)
							and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status='Approved'
						)
				end
		End
End
else
Begin
	if(@AttendType='FN')
	begin
		set @recCount=(select count(*) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_InDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) < @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) < @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status='Approved'
		)
	end
	else
	begin
		set @recCount=(select count(*) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_OutDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) > @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) > @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status='Approved'
		)
	end
End
		if(@isFlexible=1)
			begin
				Declare @Count int
				select @count=count(*) from TA_Tbl_ManualTimeEntry 
				where ManualTimeEntry_OutDate = @Date and IsOnDuty=1
				and ManualTimeEntry_Employee_Id=@EmployeeCodeId
				and IsDeleted=0 and ManualTimeEntry_Status='Approved'
				if @count=0
					begin						
						if(substring(@ShiftStartTime,7,8)='PM' and substring(@ShiftEndtime,7,8)='AM')
						begin
							select @count=count(*) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate =dateadd(d,1, @Date)and IsOnDuty=1
							and ManualTimeEntry_Employee_Id=@EmployeeCodeId
							and IsDeleted=0 and ManualTimeEntry_Status='Approved'
						end
					end
				if(@Count>0)
				begin
					Declare @FHTotHrs varchar(20)
					Declare @SHTotHrs varchar(20)
					select @FHTotHrs= Shift_FirstHalfWorkingHours,@SHTotHrs=Shift_SecondHalfWorkingHours from TA_Tbl_Shift where Shift_Id=@Shiftid and Isdeleted=0
					if(@AttendType='FN')
					begin
						if(@TotWrkHrs<>'00:00' and convert(datetime,@TotWrkHrs)>=convert(datetime,@FHTotHrs))
							begin
								set @recCount=1
							end
					end
					if(@AttendType='AN')
					begin
						if(@TotWrkHrs<>'00:00' and CONVERT(datetime,@TotWrkHrs)>=convert(datetime,@SHTotHrs))
							begin
								set @recCount=1
							end
					end
				end
			end
if(@recCount>0)
begin
	if(@AttendanceCode='Present' or @AttendanceCode='Weekly Off' or @AttendanceCode='Holiday')
	begin
		set @OnDutyText=' (On Duty) '
	End
end
RETURN @OnDutyText
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PendingLeaveDate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_PendingLeaveDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @LeaveDate VARCHAR(8000)
 -- + ' (' + cast(NumberOfDays as varchar(5)) + ') '
 SELECT @LeaveDate = ISNULL(@LeaveDate + ', ', '') + 
 case when  leave_fromdate=leave_todate then replace(convert(varchar(20),leave_fromdate,106)+'('+ cast(NumberOfDays as varchar(5))+')',' ','-')
      else  replace(convert(varchar(20),leave_fromdate,106),' ','-') + ' - ' +  replace(convert(varchar(20),leave_todate,106)+'('+ cast(NumberOfDays as varchar(5))+')',' ','-')
      end
 FROM TA_Tbl_LeaveApplication
 where Employee_id = @EmpId and isdeleted=0 and Status!='Approved' and  Status!='Rejected' and (((CONVERT(DATETIME, cast(@fromDat as nvarchar(50))  , 102) between Leave_FromDate and Leave_ToDate) or (CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102) between Leave_FromDate and Leave_ToDate) )
 or (Leave_FromDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102)) or (Leave_ToDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50)) , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)))
 if(@LeaveDate!='')
 begin
 set @LeaveDate= 'Pending Leaves : ' + isnull(@LeaveDate,'')
 end
 return isnull(@LeaveDate,'')
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PermissionDate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_PermissionDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @PerDate VARCHAR(8000)
SELECT @PerDate = ISNULL(@PerDate + ', ', '') + replace(convert(varchar(20),Permission_Date,106)+'('+ISNULL(Permission_Hours,CONVERT(varchar(6), DATEDIFF(second,Permission_FromTime, Permission_ToTime)/3600) + ':' + RIGHT('0' + CONVERT(varchar(2), (DATEDIFF(second, Permission_FromTime, Permission_ToTime) % 3600) / 60), 2) )+')',' ','-')   FROM Ta_tbl_Permission
where 
(TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, @fromDat, 102) and TA_Tbl_Permission.Permission_Date <= CONVERT(DATETIME, @ToDat, 102))
and 
TA_Tbl_Permission.Employee_id = @empId 
and permission_status='Approved'
and IsDeleted=0
--select @PerDate as PermissionDate
return @PerDate
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_ProfessionalTaxCalculate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================

-- select [dbo].[Func_TA_ProfessionalTaxCalculate]('1002',133,3000)
CREATE FUNCTION [dbo].[Func_TA_ProfessionalTaxCalculate]
(
	-- Add the parameters for the function here
	@EmployeeID nvarchar(20),
	@TaxPolicy int,
	@BasicSalary bigint
)
RETURNS bigint
AS
BEGIN
	-- Declare the return variable here
	Declare @ProfessionalTaxAmount bigint
	Declare @Slabcount int
	Declare @result int

	-- Add the T-SQL statements to compute the return value here
	Declare @ProfessionalTax table (Employee_Code varchar(20),SlabName varchar(20),Prof_FromRange bigint,Prof_ToRange bigint,Prof_Amount bigint,isFlag bit,basicSalary bigint)

	If(@BasicSalary=0)
	Begin
		Set @ProfessionalTaxAmount=0
	End

	Else
	Begin

		Insert into @ProfessionalTax
		Select AE.Employee_Code_Id,Ps.Prof_SlabName,PS.Prof_RangeFrom,PS.Prof_RangeTO,TRY_Convert(bigint,PS.Prof_Amount),PS.IsPercentage,AE.Basic_Salary
		From TA_tbl_Employee AE inner Join Ta_Tbl_ProfSlab PS on PS.Tax_PolicyId=AE.Tax_Policy
		Where  @BasicSalary between PS.Prof_RangeFrom and Ps.Prof_RangeTO or ps.Prof_RangeTO<@BasicSalary


		Select @Slabcount=Count(*) From Ta_Tbl_ProfSlab  ps inner Join TA_tbl_Employee ae on ae.Tax_Policy=Ps.Tax_PolicyId
		Where ae.Employee_Code_Id=@EmployeeId

		update @ProfessionalTax set @ProfessionalTaxAmount= Prof_Amount= Case when isFlag=1 then 
		Case when Prof_FromRange=(Select Top 1 Prof_RangeFrom From Ta_Tbl_ProfSlab order by Prof_SlabName desc) then Prof_FromRange*Prof_Amount/100 else  Prof_ToRange*Prof_Amount/100 End
		Else
		 Prof_Amount End
		 From @ProfessionalTax where Employee_Code=@EmployeeID
	End

	-- Return the result of the function

	RETURN @ProfessionalTaxAmount

END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_ProperCase]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create function [dbo].[Func_TA_ProperCase](@Text as varchar(8000))
returns varchar(8000)
as
begin
   declare @Reset bit;
   declare @Ret varchar(8000);
   declare @i int;
   declare @c char(1);
   select @Reset = 1, @i=1, @Ret = '';
   while (@i <= len(@Text))
   	select @c= substring(@Text,@i,1),
               @Ret = @Ret + case when @Reset=1 then UPPER(@c) else LOWER(@c) end,
               @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
               @i = @i +1
   return @Ret
end
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectInReaderId]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_SelectInReaderId] 
(
	@SwipeCardNo as varchar(20),
	@InOrOut char(4)
)
RETURNS varchar(50)
AS
BEGIN
	declare @DeviceID as varchar(50)
    if(@inOrOut='In')
		begin
			set @DeviceID=(select Top 1 cd.Clk_InDeviceId from Ta_tbl_clockdetails cd 
			inner join TA_Tbl_Terminal ter on ter.Terminal_ReaderID=cd.Clk_InDeviceId
			where Clk_EmpId=@SwipeCardNo )
			if(@DeviceID='' or @DeviceID is null)
				Begin
					select Top 1 @DeviceID=Terminal_Id from TA_Tbl_PunchTypes where PunchType='In' or PunchType='Shift In' or PunchType='Break In' or PunchType='Lunch In' or PunchType='In Duty' or PunchType='Official In'
				End
		end
	else
		begin
			set @DeviceID=(select Top 1 cd.Clk_InDeviceId from Ta_tbl_clockdetails cd 
			inner join TA_Tbl_Terminal ter on ter.Terminal_ReaderID=cd.Clk_InDeviceId
			where Clk_EmpId=@SwipeCardNo)
			if(@DeviceID='' or @DeviceID is null)
				Begin
					select Top 1 @DeviceID=Terminal_Id from TA_Tbl_PunchTypes where PunchType='Out' or PunchType='Shift Out' or PunchType='Break Out' or PunchType='Lunch Out' or PunchType='Out Duty' or PunchType='Official Out'
				End	
		end	
	return @DeviceID
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectMatchingDevice]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_SelectMatchingDevice]
(
	@ReaderID as varchar(25),  
	@Para as varchar(25)  
)
RETURNS varchar(50)
AS
BEGIN
	declare @OutDeviceID as varchar(50)
	declare @DeviceID as int  
	 set @DeviceID = (Select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@ReaderID)  
	 if @Para='In'  
	 Begin  
	  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type='Out'  
		set @OutDeviceID = ( Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type='In' ) 
	 End  
	 if @Para='Out'  
	 Begin  
	  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type='In'  
	  set @OutDeviceID = ( Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type='Out'  )
	 End  
	return @OutDeviceID
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_TaxCalculate]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- Select dbo.Func_TA_TaxCalculate (1003,115,116)
-- Select * From TA_tbl_Employee Where Employee_Code_Id ='1002'
-- select [dbo].[Func_TA_TaxCalculate]('E015',133,8837)
-- =============================================

CREATE FUNCTION [dbo].[Func_TA_TaxCalculate]
(
	-- Add the parameters for the function here
	@EmployeeID nvarchar(20),
	@TaxPolicy int,
	@BasicSalary bigint
)
RETURNS bigint
AS
BEGIN
	-- Declare the return variable here
	Declare @CTCAmount bigint
	Declare @TotalTdsAmount bigint
	Declare @cess int
	-- Add the T-SQL statements to compute the return value here
    Declare @TdsTable Table (ID int Identity(1,1),Employee_Code varchar(100),Tds_PolicyID int,FromRange bigint,ToRange bigint,tdsPercentage float,tds_Cess float,TdsDecutionSlabAmount bigint,TdsPercAmount bigint,CTCAmount bigint)

	if(@BasicSalary=0)
	Begin

		Set @TotalTdsAmount=0
	End
	Else
	Begin

		Insert into @TdsTable (Employee_Code,Tds_PolicyID,FromRange,ToRange,tdsPercentage,tds_Cess,TdsDecutionSlabAmount,TdsPercAmount,CTCAmount)
		Select emp.Employee_Code_Id,emp.Tax_Policy,TS.Tds_RangeFrom,TS.Tds_RangeTo,TS.Tds_Percentage,TS.Tds_CessPercentage,
		TS.Tds_RangeTo-Ts.Tds_RangeFrom, ((TS.Tds_RangeTo-Ts.Tds_RangeFrom) * Tds_Percentage/100),null
		From TA_Tbl_Employee emp inner Join TA_Tbl_TDSSlab TS on TS.Tax_PolicyId= emp.Tax_Policy where emp.Employee_Code_Id=@EmployeeID 
	
		Select @CTCAmount=Emp_Ctc From TA_Tbl_Employee where Employee_Code_Id=@EmployeeID 

		--Update @TdsTable set @tdsAmount=CTCAmount=Case when FromRange=0 then (@tdsAmount-ToRange) Else (Case when @tdsAmount<FromRange then @tdsAmount Else (@tdsAmount-FromRange)  End)End From @TdsTable 

		Update @TdsTable set @CTCAmount=CTCAmount=Case when FromRange=0 then (@CTCAmount-ToRange) Else (@CTCAmount-FromRange) End From @TdsTable 

		Update @TdsTable set TdsDecutionSlabAmount= Case when FromRange=0 then 0 Else (Case when CTCAmount>0 then (FromRange*tdsPercentage)/100 Else ((Select Min(CTCAmount) From @TdsTable where CTCAmount>0)*tdsPercentage/100) End) End From @TdsTable 
	
		Select @CTCAmount=Emp_Ctc From TA_Tbl_Employee where Employee_Code_Id=@EmployeeID

		select @cess=Tds_CessPercentage From TA_Tbl_TDSSlab where Tds_RangeFrom<=@CTCAmount and Tds_RangeTo>=@CTCAmount

		set @TotalTdsAmount=IsNull(@TotalTdsAmount,0)

		Set @TotalTdsAmount=(Select Sum(Case when @CTCAmount>FromRange then @TotalTdsAmount + TdsDecutionSlabAmount +(TdsDecutionSlabAmount * @cess/100) else 0 End) From @TdsTable where CTCAmount!=0)


		
	End


	RETURN @TotalTdsAmount/12

	-- Return the result of the function

END
GO
/****** Object:  UserDefinedFunction [dbo].[GetUTCTimeZoneDateTime]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
--Select dbo.GetUTCTimeZoneDateTime(11) as Time
CREATE FUNCTION [dbo].[GetUTCTimeZoneDateTime] (@EmployeeID int)

RETURNS DATETIME
AS
BEGIN

	declare @offsetHours INT
	declare @offsetMinutes INT
	 DECLARE @utcTime DATETIME
	if(@EmployeeID=1)
	begin

	--set @offsetHours=5
	--set @offsetMinutes=30
	Set @utcTime=GETDATE()

	end 
	else
	begin

	Select @offsetHours=HoursToBeAdded,@offsetMinutes=MinToBeAdded 
	from TA_Tbl_EmployeeLevel
	Inner Join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id =TA_Tbl_EmployeeLevel.LevelId
	Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
	Inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id =  TA_Tbl_EmployeeLevel.EmployeeId
	Where TA_Tbl_Employee.Employee_Id =@EmployeeID
	 
    SET @utcTime = DATEADD(MINUTE,Convert(int,@offsetMinutes),DateADD(Hour,Convert(int, @offsetHours), GETUTCDATE()))

	end 

    RETURN @utcTime 
END

--Select * from TA_Tbl_Employee where Employee_Code_Id = 'bb001'
--Select dbo.GetUTCTimeZoneDateTime(11)
--Select [dbo].[GetUTCTimeZoneDateTime](13)
--Print @offsetHours
--print @offsetMinutes
GO
/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[Split](
 @String nvarchar (max),
 @Delimiter nvarchar (10)
 )
returns @ValueTable table (Id int identity, [Value] nvarchar(4000))
begin
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @CommaCheck nvarchar(1)
 --Initialize
 set @NextString = ''
 set @CommaCheck = right(@String,1) 
 --Check for trailing Comma, if not exists, INSERT
 --if (@CommaCheck <> @Delimiter )
 set @String = @String + @Delimiter
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0)  
 begin
  set @NextString = substring(@String,1,@Pos - 1)
  insert into @ValueTable ( [Value]) Values (@NextString)
  set @String = substring(@String,@pos +1,len(@String))
  set @NextPos = @Pos
  set @pos  = charindex(@Delimiter,@String)
 end
 return
end
GO
/****** Object:  UserDefinedFunction [dbo].[SplitupEmployeeCode]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan.
-- Create date: 08-09-2014
-- Description:	To split up the comma separated values
-- select * from SplitupEmployeeCode('787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,')
-- =============================================
create FUNCTION [dbo].[SplitupEmployeeCode]
(	
	-- Add the parameters for the function here
	@EmployeeCodeID as varchar(max)
)
RETURNS @EmployeeID table (EmployeeID varchar(150))
AS
begin
	--To remove Duplicate Values if occured
	declare @S varchar(max)
	declare @T varchar(max)
	declare @W varchar(max)
	set @S = @EmployeeCodeID
	set @T = ','
	while len(@S) > 0
		begin
			set @W = left(@S, charindex(',', @S+',')-1)+','
			if charindex(','+@W, @T) = 0
				set @T = @T + @W
				set @S = stuff(@S, 1, charindex(',', @S+','), '')
		end
	set @EmployeeCodeID = substring(@T, 2, len(@T)-2)
	----
	Declare @RowCountEmployeeID int
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '')
	begin
		if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = ',')
		begin
			set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
		end
			insert into @EmployeeID
			select value from dbo.split(@EmployeeCodeID,',')
			select @RowCountEmployeeID=COUNT(EmployeeID) from @EmployeeID
	end
RETURN 
end
GO
/****** Object:  UserDefinedFunction [dbo].[SplitUpEmployeeName]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[SplitUpEmployeeName]
(
	@String nvarchar (max),
	@Delimiter nvarchar (10)
 )
returns @ValueTable table (Id int identity, [Value] nvarchar(4000))
begin
	--To remove Duplicate Values if occured
	declare @S varchar(max)
	declare @T varchar(max)
	declare @W varchar(max)
	set @S = @String
	set @T = ','
	while len(@S) > 0
		begin
			set @W = left(@S, charindex(',', @S+',')-1)+','
			if charindex(','+@W, @T) = 0
				set @T = @T + @W
				set @S = stuff(@S, 1, charindex(',', @S+','), '')
		end
	set @String = substring(@T, 2, len(@T)-2)
	----
	declare @NextString nvarchar(4000)
	declare @Pos int
	declare @NextPos int
	declare @CommaCheck nvarchar(1)
	--Initialize
	set @NextString = ''
	set @CommaCheck = right(@String,1)
	--Check for trailing Comma, if not exists, INSERT
	--if (@CommaCheck <> @Delimiter )
	set @String = @String + @Delimiter
	--Get position of first Comma
	set @Pos = charindex(@Delimiter,@String)
	set @NextPos = 1
	--Loop while there is still a comma in the String of levels
	while (@pos <>  0)  
		begin
			set @NextString = substring(@String,1,@Pos - 1)			
			insert into @ValueTable ( [Value]) 
			select Employee_Code_Id from ta_tbl_employee where employee_FirstName+' '+ Employee_LastName=@NextString
			and isdeleted=0
			set @String = substring(@String,@pos +1,len(@String))
			set @NextPos = @Pos
			set @pos  = charindex(@Delimiter,@String)
		end
	return
end
GO
/****** Object:  UserDefinedFunction [dbo].[TimeOnly]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create function [dbo].[TimeOnly](@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
returns datetime
as
    begin
    return @DateTime - dbo.DateOnly(@DateTime)
    end
GO
/****** Object:  UserDefinedFunction [dbo].[udf_CompleteWeekRange]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Function [dbo].[udf_CompleteWeekRange] (
    @StartDate Datetime
   ,@EndDate Datetime
   ,@DayNumber1 int
   )
-- CompleteWeekRange(StartDate,EndDate,DayNumber1,DayNumber2) 
--             1=Sun,2=Mon,3=Tue,4=Wed,5=Thu,6=Fri,7=Sat
Returns Int
As Begin 
   Declare @nCnt Money
   Set @nCnt=0
   While @StartDate <= @EndDate
   Begin
      Set @nCnt=@nCnt 
            + case when datepart(dw,@StartDate)=@DayNumber1
                                 then 1 else 0 end
      Set @StartDate=@StartDate+1
   End
   Return Floor(@nCnt)
End
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance_INOUTDetails]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails](
	[EntranceInOut_Id] [int] IDENTITY(1,1) NOT NULL,
	[Entrance_Id] [int] NOT NULL,
	[Reader_Id] [int] NOT NULL,
	[Type] [nvarchar](10) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Terminal]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Terminal](
	[Terminal_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_ReaderID] [nvarchar](20) NULL,
	[Terminal_Name] [nvarchar](50) NOT NULL,
	[Terminal_Description] [nvarchar](250) NOT NULL,
	[TerminalDatatype_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_ID] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Terminal] PRIMARY KEY CLUSTERED 
(
	[Terminal_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ClockDetails]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ClockDetails](
	[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_CompId] [nvarchar](10) NULL,
	[Clk_EmpId] [nvarchar](20) NULL,
	[Clk_InDeviceId] [nvarchar](20) NULL,
	[Clk_InDate] [datetime] NULL,
	[Clk_InTime] [datetime] NULL,
	[Clk_InPunchType] [nvarchar](25) NULL,
	[Clk_OutDeviceId] [nvarchar](20) NULL,
	[Clk_OutDate] [datetime] NULL,
	[Clk_OutTime] [datetime] NULL,
	[Clk_OutPunchType] [nvarchar](25) NULL,
	[Clk_Process] [nvarchar](1) NULL,
	[Clk_Remarks] [nvarchar](255) NULL,
	[Clk_User] [nvarchar](20) NULL,
	[Clk_Date] [datetime] NULL,
	[Clk_Status] [nvarchar](1) NULL,
	[IsVoid] [bit] NULL,
	[PunchType_Remarks] [varchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_ClockDetails] PRIMARY KEY CLUSTERED 
(
	[Clk_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches_Test]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_BreakInPunches_Test]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], (CD.Clk_InDate + CD.Clk_InTime) [DateTime], CD.Clk_InPunchType [PunchType],ROW_NUMBER() OVER(PARTITION BY Clk_EmpId, CAST(Clk_Date AS DATETIME) ORDER BY (CD.Clk_InDate + CD.Clk_InTime) ASC) Id
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = 'N') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE 'Break In') AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + '12:00 PM') AND (CD.Clk_InDate + '02:00 PM') 
 AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + '09:00 PM') AND (CD.Clk_InDate + '10:00 PM')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, (CD.Clk_InDate + CD.Clk_InTime)
ORDER BY CD.Clk_EmpId, CD.Clk_Date
GO
/****** Object:  View [dbo].[TA_VW_LunchInPunches]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_LunchInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], CD.Clk_InPunchType [PunchType]
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = 'N') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE 'Lunch In')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
GO
/****** Object:  View [dbo].[TA_VW_ShiftInPunches]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_ShiftInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], 'Shift In' PunchType
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = 'N') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE 'In')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeEntrance]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeEntrance](
	[Unique_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Code_Id] [varchar](50) NULL,
	[Device_Id] [varchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches_Test]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_FirstInPunches_Test]
AS
--Get All Employee Appropriate Device First In Data After Shift In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime],  'Work Place In' PunchType, 'Shift FIn' [FirstInPunch], NULL Id FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_ShiftInPunches IP ON IP.EmployeeCodeId = CD.Clk_EmpId AND IP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= IP.[DateTime]
WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Break In
SELECT [EmployeeCodeId],[DeviceId], [Date], [DateTime], PunchType, [FirstInPunch], ROW_NUMBER() OVER(PARTITION BY [EmployeeCodeId], CAST([Date] AS DATETIME) ORDER BY [DateTime] ASC) Id FROM (
	SELECT DISTINCT
		CD.Clk_EmpId [EmployeeCodeId], 
		CD.Clk_InDeviceId [DeviceId],
		CD.Clk_Date [Date],
		--(SELECT TOP 1(TCD.Clk_InDate + TCD.Clk_InTime) FROM TA_Tbl_ClockDetails TCD WHERE TCD.Clk_Process = 'N' AND TCD.Clk_InPunchType LIKE 'In' AND TCD.Clk_EmpId = CD.Clk_EmpId AND (TCD.Clk_InDate + TCD.Clk_InTime) >= BP.[DateTime]) [DateTime],
		(CD.Clk_InDate + CD.Clk_InTime)[DateTime],
		'Work Place In' PunchType,
		'Break FIn' [FirstInPunch]
	FROM TA_Tbl_ClockDetails CD
	RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
	RIGHT OUTER JOIN TA_VW_BreakInPunches_Test BP ON BP.EmployeeCodeId = CD.Clk_EmpId AND BP.[Date] = CD.Clk_Date --AND (Clk_InDate + Clk_InTime) >= BP.[DateTime]
	WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
	GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id, (CD.Clk_InDate + CD.Clk_InTime), BP.[DateTime]
) Tbl
UNION ALL
--Get All Employee Appropriate Device First In Data After Lunch In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], 'Work Place In' PunchType, 'Lunch FIn' [FirstInPunch], NULL Id FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_LunchInPunches LP ON LP.EmployeeCodeId = CD.Clk_EmpId AND LP.[Date] = CD.Clk_Date AND (CD.Clk_InDate + CD.Clk_InTime) >= LP.[DateTime]
WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_BreakInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], CD.Clk_InPunchType [PunchType]
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = 'N') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE 'Break In') AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + '12:00 PM') AND (CD.Clk_InDate + '02:00 PM') 
 AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + '09:00 PM') AND (CD.Clk_InDate + '10:00 PM')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_FirstInPunches]
AS
--Get All Employee Appropriate Device First In Data After Shift In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime],  'Work Place In' PunchType, 'Shift FIn' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_ShiftInPunches IP ON IP.EmployeeCodeId = CD.Clk_EmpId AND IP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= IP.[DateTime]
WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Break In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], 'Work Place In' PunchType, 'Break FIn' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_BreakInPunches BP ON BP.EmployeeCodeId = CD.Clk_EmpId AND BP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= BP.[DateTime]
WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Lunch In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], 'Work Place In' PunchType, 'Lunch FIn' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_LunchInPunches LP ON LP.EmployeeCodeId = CD.Clk_EmpId AND LP.[Date] = CD.Clk_Date AND (CD.Clk_InDate + CD.Clk_InTime) >= LP.[DateTime]
WHERE CD.Clk_Process = 'N' AND CD.Clk_InPunchType LIKE 'In'
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference_Test]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_FirstInPunchDifference_Test]
AS
	SELECT SIP.EmployeeCodeId, SIP.[Date], ST.Terminal_Description EntranceName, SIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), SIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName, 
        FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) PunchDifference,
		ISNULL(DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM dbo.TA_VW_ShiftInPunches SIP
		LEFT OUTER JOIN dbo.TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = SIP.EmployeeCodeId AND FIP.[Date] = SIP.[Date] AND FIP.FirstInPunch = 'Shift FIn'
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal ST ON ST.Terminal_ReaderID = SIP.DeviceId
	WHERE (ISNULL(SIP.EmployeeCodeId, N'') <> '') --AND (ISNULL(FT.Terminal_Description, '') <> '')
	UNION ALL
	SELECT LIP.EmployeeCodeId, LIP.[Date], LT.Terminal_Description [EntranceName], LIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), LIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) [PunchDifference],
		ISNULL(DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_LunchInPunches LIP
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = LIP.EmployeeCodeId AND FIP.[Date] = LIP.[Date] AND FIP.FirstInPunch = 'Lunch FIn'
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal LT ON LT.Terminal_ReaderID = LIP.DeviceId
	WHERE ISNULL(LIP.EmployeeCodeId, '') <> '' --AND (ISNULL(FT.Terminal_Description, '') <> '')
	UNION ALL
	SELECT DISTINCT BIP.EmployeeCodeId, BIP.[Date], BT.Terminal_Description [EntranceName], BIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), BIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) [PunchDifference],
		ISNULL(DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_BreakInPunches_Test  BIP 
		LEFT OUTER JOIN TA_VW_FirstInPunches_Test FIP ON FIP.EmployeeCodeId = BIP.EmployeeCodeId AND FIP.[Date] = BIP.[Date] AND FIP.FirstInPunch = 'Break FIn' AND FIP.Id = BIP.Id
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal BT ON BT.Terminal_ReaderID = BIP.DeviceId
	WHERE ISNULL(BIP.EmployeeCodeId, '') <> '' --AND (ISNULL(FT.Terminal_Description, '') <> '')
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_FirstInPunchDifference]
AS
	SELECT SIP.EmployeeCodeId, SIP.[Date], ST.Terminal_Description EntranceName, SIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), SIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName, 
        FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) PunchDifference,
		ISNULL(DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM dbo.TA_VW_ShiftInPunches SIP
		LEFT OUTER JOIN dbo.TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = SIP.EmployeeCodeId AND FIP.[Date] = SIP.[Date] AND FIP.FirstInPunch = 'Shift FIn'
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal ST ON ST.Terminal_ReaderID = SIP.DeviceId
	WHERE (ISNULL(SIP.EmployeeCodeId, N'') <> '') --AND (ISNULL(FT.Terminal_Description, '') <> '')
	UNION ALL
	SELECT LIP.EmployeeCodeId, LIP.[Date], LT.Terminal_Description [EntranceName], LIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), LIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) [PunchDifference],
		ISNULL(DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_LunchInPunches LIP
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = LIP.EmployeeCodeId AND FIP.[Date] = LIP.[Date] AND FIP.FirstInPunch = 'Lunch FIn'
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal LT ON LT.Terminal_ReaderID = LIP.DeviceId
	WHERE ISNULL(LIP.EmployeeCodeId, '') <> '' --AND (ISNULL(FT.Terminal_Description, '') <> '')
	UNION ALL
	SELECT BIP.EmployeeCodeId, BIP.[Date], BT.Terminal_Description [EntranceName], BIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), BIP.[DateTime], 109), 15)), ':000', ' ') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), ':000', ' ') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), '00:00') AS TIME), '23:59')) [PunchDifference],
		ISNULL(DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_BreakInPunches BIP 
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = BIP.EmployeeCodeId AND FIP.[Date] = BIP.[Date] AND FIP.FirstInPunch = 'Break FIn'
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal BT ON BT.Terminal_ReaderID = BIP.DeviceId
	WHERE ISNULL(BIP.EmployeeCodeId, '') <> '' --AND (ISNULL(FT.Terminal_Description, '') <> '')
GO
/****** Object:  Table [dbo].[TA_Tbl_Employee]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Employee](
	[Employee_Id] [int] IDENTITY(1,1) NOT NULL,
	[UserGroup_Id] [int] NULL,
	[Designation_Id] [int] NULL,
	[ShiftPattern_Id] [int] NULL,
	[Bus_Id] [int] NULL,
	[Employee_FirstName] [nvarchar](50) NULL,
	[Employee_MiddleName] [nvarchar](50) NULL,
	[Employee_LastName] [nvarchar](50) NULL,
	[Father_name] [nvarchar](50) NULL,
	[Mother_name] [nvarchar](50) NULL,
	[DateofBirth] [datetime] NULL,
	[DateofBirth_Record] [datetime] NULL,
	[Blood_Group] [nvarchar](10) NULL,
	[EmailId] [nvarchar](100) NULL,
	[Contact_Address] [nvarchar](255) NULL,
	[Permanent_Address] [nvarchar](255) NULL,
	[Phone_Number] [nvarchar](50) NULL,
	[Mobile_Number] [nvarchar](50) NULL,
	[Gender] [nvarchar](10) NULL,
	[Marital_status] [nvarchar](10) NULL,
	[Nationality] [nvarchar](50) NULL,
	[Religion] [int] NULL,
	[Photo] [image] NULL,
	[Personal_mailid] [nvarchar](100) NULL,
	[Passport_No] [nvarchar](50) NULL,
	[Passport_expirydate] [datetime] NULL,
	[Visa_No] [nvarchar](50) NULL,
	[Visa_expirydate] [datetime] NULL,
	[Vehicle_Type] [nvarchar](20) NULL,
	[Vehicle_No] [nvarchar](50) NULL,
	[Anniversary_Date] [datetime] NULL,
	[Native_Place] [int] NULL,
	[District] [nvarchar](50) NULL,
	[State] [int] NULL,
	[Country] [int] NULL,
	[Spouse_No] [int] NULL,
	[Children_No] [int] NULL,
	[Employee_Code_Id] [nvarchar](15) NULL,
	[DateOfJoining] [datetime] NULL,
	[Reporting_To] [int] NULL,
	[Leave_Sanc_Authority] [int] NULL,
	[Prev_Experience] [float] NULL,
	[Basic_Salary] [float] NULL,
	[Allowances] [float] NULL,
	[UserName] [nvarchar](15) NULL,
	[Emp_password] [nvarchar](50) NULL,
	[Qual_JoiningTime] [nvarchar](50) NULL,
	[Qual_Employment] [nvarchar](50) NULL,
	[OutDoorJob] [bit] NULL,
	[CompOff_Eligible] [bit] NOT NULL,
	[OT_Eligible] [bit] NOT NULL,
	[ESI_Eligible] [bit] NOT NULL,
	[PF_Eligible] [bit] NULL,
	[Report_Exclude] [bit] NULL,
	[Employee_Status] [bit] NULL,
	[SwipeCardNo] [nvarchar](20) NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_ID] [int] NULL,
	[Isdeleted] [bit] NULL,
	[Hostel] [bit] NULL,
	[IsFlexible] [bit] NULL,
	[InActiveDate] [datetime] NULL,
	[CustomField1] [nvarchar](1000) NULL,
	[CustomField2] [nvarchar](1000) NULL,
	[CustomField3] [nvarchar](1000) NULL,
	[CustomField4] [nvarchar](1000) NULL,
	[CustomField5] [nvarchar](1000) NULL,
	[IsComplete] [bit] NULL,
	[Isdeleted_Status] [bit] NULL,
	[InActive_Status] [bit] NULL,
	[IsImported] [bit] NULL,
	[modify_date] [datetime] NULL,
	[modify_by] [bigint] NULL,
	[penalty] [bit] NULL,
	[MobileClockInOUt] [bit] NOT NULL,
	[SMSEnabled] [bit] NOT NULL,
	[IsPassportReminderRequired] [bit] NULL,
	[PassportRemindDays] [int] NULL,
	[IsVisaReminderRequired] [bit] NULL,
	[VisaRemindDays] [int] NULL,
	[IsMailSentForPassport] [bit] NULL,
	[IsMailSentForVisa] [bit] NULL,
	[IsPass_LastUpdatedOn] [datetime] NULL,
	[IsVisa_LastUpdatedOn] [datetime] NULL,
	[IsMyProfileRqrd] [bit] NULL,
	[Emp_Ctc] [bigint] NULL,
	[HRA] [int] NULL,
	[DA] [int] NULL,
	[PF_Policy] [int] NULL,
	[CA] [int] NULL,
	[MedicalAlllowance] [int] NULL,
	[CEDAllowance] [int] NULL,
	[Tax_Policy] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Employee] PRIMARY KEY CLUSTERED 
(
	[Employee_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  View [dbo].[OrderByEmployeeCodeId]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[OrderByEmployeeCodeId]
AS
select cast(substring(Employee_Code_Id,Len(Employee_Code_Id) - Len(Replace(Employee_Code_Id, '0', ''))+1,
len(Employee_Code_Id))as int)as Order1,
Employee_Code_Id,
cast(Len(Employee_Code_Id) - Len(Replace(Employee_Code_Id, '0', ''))as int)as Order2
from ta_tbl_employee where Employee_Code_Id like('0%')
GO
/****** Object:  Table [dbo].[TA_Tbl_ProcessedData]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ProcessedData](
	[Process_Rec_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Date] [datetime] NULL,
	[Shift_Id] [int] NULL,
	[InTime] [nvarchar](25) NULL,
	[OutTime] [nvarchar](25) NULL,
	[HrsWork] [nvarchar](10) NULL,
	[HrsOT] [nvarchar](10) NULL,
	[NormOT] [nvarchar](10) NULL,
	[OffOT] [nvarchar](10) NULL,
	[HolOT] [nvarchar](10) NULL,
	[EarlyOut] [nvarchar](10) NULL,
	[LateIn] [nvarchar](10) NULL,
	[Attendance] [nvarchar](20) NULL,
	[WorkHrs] [nvarchar](10) NULL,
	[HrsLess] [nvarchar](10) NULL,
	[HrsExtra] [nvarchar](10) NULL,
	[LateInMins] [float] NULL,
	[EarlyOutMins] [float] NULL,
	[ExtraMins] [float] NULL,
	[OtMins] [float] NULL,
	[OvertimeStatus] [nvarchar](50) NULL,
	[TotalDays] [numeric](18, 1) NULL,
	[LeaveCode] [nvarchar](20) NULL,
	[LateEntryReason] [nvarchar](260) NULL,
	[EarlyOutReason] [nvarchar](260) NULL,
	[BreakOut] [nvarchar](25) NULL,
	[BreakIn] [nvarchar](25) NULL,
	[BreakHours] [nvarchar](10) NULL,
	[BreakLate] [nvarchar](10) NULL,
	[BreakLateMins] [float] NULL,
	[TotalLate] [nvarchar](10) NULL,
	[TotalLateMins] [float] NULL,
	[ProcessFlag] [int] NULL,
	[Status] [nvarchar](50) NULL,
	[FNAttendanceCode] [nvarchar](15) NULL,
	[ANAttendanceCode] [nvarchar](15) NULL,
	[DinnerOut] [nvarchar](25) NULL,
	[DinnerIn] [nvarchar](25) NULL,
	[DinnerHours] [nvarchar](10) NULL,
	[DinnerLate] [nvarchar](10) NULL,
	[DinnerLateMins] [float] NULL,
	[LateExit] [bit] NULL,
	[EarlyEntry] [bit] NULL,
	[BreakHrs] [nvarchar](10) NULL,
	[LunchHrs] [nvarchar](10) NULL,
	[BreakHrsInMins] [float] NULL,
	[LunchHrsInMins] [float] NULL,
	[InNotation] [char](1) NULL,
	[OutNotation] [char](1) NULL,
	[Shift_StartTime] [nvarchar](20) NULL,
	[Shift_EndTime] [nvarchar](20) NULL,
	[PermissionHrs] [nvarchar](10) NULL,
	[PermissionHrsInMins] [float] NULL,
	[HoursWorkInMins] [float] NULL,
	[WorkHoursInMins] [float] NULL,
	[LessHoursInMins] [float] NULL,
	[IsOnduty] [bit] NULL,
	[LeaveStatus] [nvarchar](50) NULL,
	[PermissionStatus] [nvarchar](50) NULL,
	[NormOtmins] [float] NULL,
	[OffOtmins] [float] NULL,
	[HolOtMins] [float] NULL,
	[CLAvailed]  AS (case when [FNAttendanceCode]='CL' AND [ANAttendanceCode]='CL' then (1) when [FNAttendanceCode]='CL' AND [ANAttendanceCode]<>'CL' then (0.5) when [FNAttendanceCode]<>'CL' AND [ANAttendanceCode]='CL' then (0.5) else (0) end),
	[YearSettingId] [int] NULL,
	[LeaveType_Id] [int] NULL,
	[Holiday_Description] [nvarchar](250) NULL,
	[EarlyInmins] [int] NULL,
	[EarlyInHrs] [varchar](20) NULL,
	[lateExitMins] [int] NULL,
	[LateExitHours] [varchar](20) NULL,
	[ActNormOTMins] [float] NULL,
	[ActOffOTMins] [float] NULL,
	[ActHolOTMins] [float] NULL,
	[ActOTMins] [float] NULL,
	[ActHrsOT] [nvarchar](20) NULL,
	[ActNormOT] [nvarchar](20) NULL,
	[ActOffOT] [nvarchar](20) NULL,
	[ActHolOT] [nvarchar](20) NULL,
	[Inpunch] [varchar](20) NULL,
	[Outpunch] [varchar](20) NULL,
	[Indate] [datetime] NULL,
	[Outdate] [datetime] NULL,
	[SPEC_NormOT1] [varchar](10) NULL,
	[SPEC_NormOTMins1] [int] NULL,
	[SPEC_NormOT2] [varchar](10) NULL,
	[SPEC_NormOTMins2] [int] NULL,
	[SPEC_OffOT1] [varchar](10) NULL,
	[SPEC_OffOTMins1] [int] NULL,
	[SPEC_OffOT2] [varchar](10) NULL,
	[SPEC_OffOTMins2] [int] NULL,
	[SPEC_HOLOT1] [varchar](10) NULL,
	[SPEC_HOLOTMins1] [int] NULL,
	[SPEC_HOLOT2] [varchar](10) NULL,
	[SPEC_HOLOTMins2] [int] NULL,
	[InLocation] [varchar](500) NULL,
	[OutLocation] [varchar](500) NULL,
	[Level_Id] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_ProcessedData] PRIMARY KEY CLUSTERED 
(
	[Process_Rec_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[SPMPClientSAPView]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[SPMPClientSAPView]
AS
SELECT        Employee_Code_Id, Format(Date, 'dd-MM-yyyy') AS ShiftDate, Format(Indate, 'dd-MM-yyyy') AS StartDate, InTime AS Punch_In, Outdate AS EndDate, OutTime AS Punch_Out
FROM            dbo.TA_Tbl_ProcessedData
GO
/****** Object:  Table [dbo].[TA_Tbl_Shift]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Shift](
	[Shift_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[Shift_Name] [nvarchar](50) NULL,
	[Shift_ShortName] [varchar](8) NULL,
	[Shift_Description] [nvarchar](255) NULL,
	[Shift_StartTime] [nvarchar](10) NULL,
	[Shift_EndTime] [nvarchar](10) NOT NULL,
	[Shift_FirstHalf_StartTime] [nvarchar](10) NULL,
	[Shift_FirstHalf_EndTime] [nvarchar](10) NULL,
	[Shift_SecondHalf_StartTime] [nvarchar](10) NULL,
	[Shift_SecondHalf_EndTime] [nvarchar](10) NULL,
	[Shift_GraceInTime] [nvarchar](10) NOT NULL,
	[Shift_GraceOutTime] [nvarchar](10) NULL,
	[Shift_BreakStartTime1] [nvarchar](10) NULL,
	[Shift_BreakEndTime1] [nvarchar](10) NULL,
	[Shift_BreakStartTime2] [nvarchar](10) NULL,
	[Shift_BreakEndTime2] [nvarchar](10) NULL,
	[Shift_BreakStartTime3] [nvarchar](10) NULL,
	[Shift_BreakEndTime3] [nvarchar](10) NULL,
	[Shift_MinTimeOT] [nvarchar](50) NULL,
	[Shift_MaxTimeOT] [nvarchar](50) NULL,
	[Shift_WorkingDay_OverTime] [float] NULL,
	[Shift_TotalWorkingHours] [nvarchar](50) NULL,
	[Shift_LunchOutTimeGrace] [nvarchar](10) NULL,
	[Shift_LunchInTimeGrace] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceBefore] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceAfter] [nvarchar](10) NULL,
	[Shift_LunchInTimeGraceBefore] [nvarchar](10) NULL,
	[Shift_LunchInTimeGraceAfter] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceBeforeChk] [bit] NULL,
	[Shift_LunchOutTimeGraceAfterChk] [bit] NULL,
	[Shift_LunchInTimeGraceBeforeChk] [bit] NULL,
	[Shift_LunchInTimeGraceAfterChk] [bit] NULL,
	[Isdeleted] [bit] NULL,
	[Emp_ID] [nvarchar](50) NULL,
	[Shift_FirstHalfWorkingHours] [nvarchar](5) NULL,
	[Shift_SecondHalfWorkingHours] [nvarchar](5) NULL,
	[IsBreakDeducted] [bit] NULL,
	[DefaultShift] [bit] NULL,
	[ShiftType] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
	[24HrsShift] [bit] NULL,
	[isStraightShift] [bit] NULL,
	[StraightPresentTime] [nvarchar](10) NULL,
	[BreakHours] [nvarchar](6) NULL,
	[empCategory] [int] NULL,
	[specialOvertime_start1] [varchar](10) NULL,
	[specialOvertime_start2] [varchar](10) NULL,
	[MaxShiftWorkHours] [varchar](10) NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Shift] PRIMARY KEY CLUSTERED 
(
	[Shift_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  View [dbo].[ta_view]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[ta_view] 
 as
 select Shift_ShortName from ta_tbl_shift group by Shift_ShortName
GO
/****** Object:  View [dbo].[TA_VW_BreakFirstInPunches]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[TA_VW_BreakFirstInPunches]
AS
SELECT TOP (100) PERCENT ROW_NUMBER() OVER(ORDER BY [EmployeeCodeId]) Id, [EmployeeCodeId], [DeviceId], [Date], [DateTime], [PunchType] FROM (
	SELECT DISTINCT [EmployeeCodeId], [DeviceId], [Date], [DateTime], [PunchType] FROM 
		(SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], (CD.Clk_InDate + CD.Clk_InTime) [DateTime], CD.Clk_InPunchType [PunchType] FROM TA_Tbl_ClockDetails CD 
			RIGHT OUTER JOIN TA_Tbl_Terminal T ON T.Terminal_ReaderID = CD.Clk_InDeviceId
			RIGHT OUTER JOIN TA_Tbl_Entrance_INOUTDetails E ON E.Reader_Id = T.Terminal_Id
		WHERE (CD.Clk_Process = 'N') AND CD.Clk_Date >= '01-Jul-2014' AND CD.Clk_InPunchType IN('In', 'Break In'))Tbl) Tbl2
GO
/****** Object:  View [dbo].[VW_FetchDataFromProcessedData]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[VW_FetchDataFromProcessedData]
AS
SELECT        P.Date, P.Shift_Id, P.InTime, P.OutTime, P.Employee_Code_Id, P.Process_Rec_ID, P.HrsWork, P.HrsOT, P.NormOT, P.OffOT, P.HolOT, P.EarlyOut, P.LateIn, P.WorkHrs, P.Attendance, P.HrsLess, P.HrsExtra, P.LateInMins, 
                         P.EarlyOutMins, P.ExtraMins, P.OtMins, P.OvertimeStatus, P.TotalDays, P.LeaveCode, P.LateEntryReason, P.EarlyOutReason, P.BreakOut, P.BreakIn, P.BreakHours, P.BreakLateMins, P.BreakLate, P.TotalLate, P.TotalLateMins, 
                         P.ProcessFlag, P.Status, P.FNAttendanceCode, P.ANAttendanceCode, P.LateExit, P.EarlyEntry, P.BreakHrs, P.LunchHrs, P.BreakHrsInMins, P.InNotation, P.LunchHrsInMins, P.OutNotation, P.Shift_EndTime, P.Inpunch, 
                         P.Outpunch, dbo.TA_Tbl_Shift.Shift_StartTime, dbo.TA_Tbl_Shift.Shift_SecondHalf_StartTime, P.ActOTMins, P.ActNormOT, P.SPEC_NormOT1, P.SPEC_NormOTMins1, P.SPEC_NormOT2, P.SPEC_NormOTMins2, P.SPEC_OffOT1, 
                         P.SPEC_OffOTMins1, P.SPEC_OffOT2, P.SPEC_OffOTMins2, P.SPEC_HOLOT1, P.SPEC_HOLOTMins1, P.SPEC_HOLOT2, P.SPEC_HOLOTMins2, P.ActHolOTMins, P.ActOffOTMins, P.ActHolOT, P.ActOffOT, P.PermissionHrs, 
                         P.PermissionHrsInMins, P.PermissionStatus, P.InLocation, P.OutLocation, '' AS In_Latitude, '' AS In_Longitude, '' AS Out_Latitude, '' AS Out_Longitude, P.Level_Id,p.Indate,p.Outdate
FROM            dbo.TA_Tbl_ProcessedData AS P LEFT OUTER JOIN
                         dbo.TA_Tbl_Shift ON P.Shift_Id = dbo.TA_Tbl_Shift.Shift_Id
GO
/****** Object:  Table [dbo].[AutoLeaveupdation]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AutoLeaveupdation](
	[autoid] [int] IDENTITY(1,1) NOT NULL,
	[leaveapplicationID] [bigint] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ImportFromExcel]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ImportFromExcel](
	[Sl.No] [varchar](50) NULL,
	[Employeeid] [varchar](50) NULL,
	[LeaveType1] [decimal](18, 1) NULL,
	[LeaveType2] [decimal](18, 1) NULL,
	[LeaveType3] [decimal](18, 1) NULL,
	[LeaveType4] [decimal](18, 1) NULL,
	[LeaveType5] [decimal](18, 1) NULL,
	[LeaveType6] [decimal](18, 1) NULL,
	[LeaveType7] [decimal](18, 1) NULL,
	[LeaveType8] [decimal](18, 1) NULL,
	[LeaveType9] [decimal](18, 1) NULL,
	[LeaveType10] [decimal](18, 1) NULL,
	[LeaveType11] [decimal](18, 1) NULL,
	[LeaveType12] [decimal](18, 1) NULL,
	[LeaveType13] [decimal](18, 1) NULL,
	[LeaveType14] [decimal](18, 1) NULL,
	[LeaveType15] [decimal](18, 1) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[PolygonTable]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PolygonTable](
	[ID] [int] NOT NULL,
	[Polygon] [geometry] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Proc_ImportOvertime]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Proc_ImportOvertime](
	[autoid] [bigint] IDENTITY(1,1) NOT NULL,
	[Sl.no] [varchar](20) NULL,
	[Employee_Code_Id] [varchar](20) NULL,
	[Employee_FirstName] [varchar](max) NULL,
	[LevelName] [varchar](max) NULL,
	[date] [varchar](20) NULL,
	[HrsOT] [varchar](20) NULL,
	[ActHrsOT] [varchar](20) NULL,
	[OffOT] [varchar](20) NULL,
	[ActOffOT] [varchar](20) NULL,
	[HolOT] [varchar](20) NULL,
	[ActHolOT] [varchar](20) NULL,
	[SPEC_NormOT1] [varchar](20) NULL,
	[Modified_Spec_NormOTHrs1] [varchar](20) NULL,
	[SPEC_NormOT2] [varchar](20) NULL,
	[Modified_Spec_NormOTHrs2] [varchar](20) NULL,
	[SPEC_OffOT1] [varchar](20) NULL,
	[Modified_Spec_OffOTHrs1] [varchar](20) NULL,
	[SPEC_OffOT2] [varchar](20) NULL,
	[Modified_Spec_OffOTHrs2] [varchar](20) NULL,
	[SPEC_HOLOT1] [varchar](20) NULL,
	[Modified_Spec_HolOTHrs1] [varchar](20) NULL,
	[SPEC_HOLOT2] [varchar](20) NULL,
	[Modified_Spec_HolOTHrs2] [varchar](20) NULL,
	[OverTimeStatus] [varchar](20) NULL,
	[Error] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[SlabTable]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SlabTable](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[slabrow] [int] NULL,
	[policyId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_ExportData_CustomFormat]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_ExportData_CustomFormat](
	[OptionType] [varchar](50) NOT NULL,
	[DateFormat] [varchar](50) NOT NULL,
	[TimeFormat] [varchar](50) NOT NULL,
	[DateTimeFormat] [varchar](50) NOT NULL,
	[XML_RootTag] [varchar](50) NOT NULL,
	[XML_FirstChildTag] [varchar](50) NOT NULL,
	[DataType] [varchar](50) NULL,
	[CompanyID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_ExportData_FieldData]    Script Date: 10-30-2024 09:39:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_ExportData_FieldData](
	[OptionType] [varchar](50) NOT NULL,
	[FieldName] [varchar](50) NOT NULL,
	[UserDefinedFieldName] [varchar](50) NOT NULL,
	[FieldType] [varchar](50) NOT NULL,
	[DataType] [varchar](50) NULL,
	[CompanyID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AccessDeniedSettings]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AccessDeniedSettings](
	[AccessDenied_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_ReaderID] [nvarchar](10) NULL,
	[Employee_Code_Id] [nvarchar](10) NULL,
	[AccessDeniedKey] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Additional_WeeklyOff](
	[Addl_WeeklyOff_Id] [int] IDENTITY(1,1) NOT NULL,
	[Addl_WeekOff_Day] [nvarchar](50) NULL,
	[Addl_WeekOff_Week] [nvarchar](50) NULL,
	[LevelId_Id] [int] NULL,
	[IsDeleted] [bit] NULL,
	[Emp_Id] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Additional_WeeklyOff] PRIMARY KEY CLUSTERED 
(
	[Addl_WeeklyOff_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Addl_WeeklyOff_Id] [int] NOT NULL,
	[LevelId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_AdditionalWeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_APIConfig]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_APIConfig](
	[APIID] [int] IDENTITY(1,1) NOT NULL,
	[APIURL] [nvarchar](2000) NULL,
	[BiostarUsername] [nvarchar](200) NULL,
	[BiostarPassword] [nvarchar](200) NULL,
	[syncEmp] [bit] NULL,
	[WhatsAPP_SID] [nvarchar](max) NULL,
	[WhatsApp_authToken] [nvarchar](max) NULL,
	[WhatsApp_SenderNumber] [nvarchar](50) NULL,
	[createdBy] [nvarchar](50) NULL,
	[createdDate] [datetime] NULL,
	[ModifyDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ApprovalSettings]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ApprovalSettings](
	[CompanyId] [int] NOT NULL,
	[OTApproval] [bit] NOT NULL,
	[LeaveSanction] [bit] NOT NULL,
	[PermissionSanction] [bit] NOT NULL,
	[ManualEntry] [bit] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[Roster] [bit] NULL,
	[Pattern] [bit] NOT NULL,
	[ODEntry] [bit] NULL,
	[Approval] [bit] NOT NULL,
	[webClockInOut] [bit] NULL,
	[ShiftRequisition] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AttandanceCode]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AttandanceCode](
	[AttandanceID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyID] [int] NULL,
	[AttandanceCode] [nvarchar](50) NULL,
	[AttandanceValue] [nvarchar](50) NULL,
	[EmpID] [int] NULL,
	[isDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AttendenceData]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AttendenceData](
	[Attendence_Id] [int] IDENTITY(1,1) NOT NULL,
	[EmpId] [nvarchar](50) NOT NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[OD] [numeric](18, 1) NULL,
	[EL] [numeric](18, 1) NULL,
	[CL] [numeric](18, 1) NULL,
	[SL] [numeric](18, 1) NULL,
	[LOP_Absent] [numeric](18, 1) NULL,
	[Difference_Days] [numeric](18, 1) NULL,
	[Total] [numeric](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_AttendenceData] PRIMARY KEY CLUSTERED 
(
	[Attendence_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditField]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AuditField](
	[FieldID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableID] [decimal](18, 0) NOT NULL,
	[FieldName] [nvarchar](100) NOT NULL,
	[FieldDescription] [nvarchar](100) NOT NULL,
	[InsertBit] [bit] NOT NULL,
	[UpdateBit] [bit] NOT NULL,
	[DeleteBit] [bit] NOT NULL,
	[Status] [bit] NOT NULL,
	[Datatype] [varchar](50) NULL,
 CONSTRAINT [PK_TA_Tbl_AuditField_1] PRIMARY KEY CLUSTERED 
(
	[FieldID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditOperation]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AuditOperation](
	[ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableID] [decimal](18, 0) NOT NULL,
	[RecordID] [decimal](18, 0) NOT NULL,
	[FieldID] [decimal](18, 0) NOT NULL,
	[Opr] [nvarchar](25) NOT NULL,
	[OldValue] [nvarchar](500) NULL,
	[NewValue] [nvarchar](500) NULL,
	[EmployeeID] [int] NULL,
	[OprDate] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_AuditOperation] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditTable]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AuditTable](
	[TableID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableName] [nvarchar](100) NOT NULL,
	[TableDescription] [nvarchar](100) NOT NULL,
	[Status] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_AuditTable] PRIMARY KEY CLUSTERED 
(
	[TableID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_AutoShiftConfiguration]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_AutoShiftConfiguration](
	[AutoShiftConfigId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[ShiftId1] [int] NULL,
	[ShiftId2] [int] NULL,
	[ShiftId3] [int] NULL,
	[ShiftId4] [int] NULL,
	[ShiftId5] [int] NULL,
	[CreatedBy] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL,
	[IsImport] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_AutoShiftConfiguration] PRIMARY KEY CLUSTERED 
(
	[AutoShiftConfigId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_BiostarAPIDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_BiostarAPIDetails](
	[APIID] [int] IDENTITY(1,1) NOT NULL,
	[APIURL] [nvarchar](2000) NULL,
	[BiostarUsername] [nvarchar](200) NULL,
	[BiostarPassword] [nvarchar](200) NULL,
	[isMainAPI] [int] NULL,
	[Createdby] [bigint] NULL,
	[Modifyby] [bigint] NULL,
	[createdDate] [datetime] NULL,
	[Modifydate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_BlockedEmployeeLogs]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_BlockedEmployeeLogs](
	[AutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeCodeID] [nvarchar](100) NULL,
	[PunchDate] [datetime] NULL,
	[PunchTime] [nvarchar](100) NULL,
	[DeviceID] [nvarchar](20) NULL,
	[ToMailID] [nvarchar](max) NULL,
	[CCMailID] [nvarchar](max) NULL,
	[MailContent] [nvarchar](max) NULL,
	[Timestamp] [datetime] NULL,
	[isMailSent] [int] NULL,
	[SentDatetime] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_BlockedEmployees]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_BlockedEmployees](
	[BlockId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeCard] [varchar](20) NULL,
	[Daily] [bit] NULL,
	[DayWise] [bit] NULL,
	[WeekWise] [bit] NULL,
	[QuarterWise] [bit] NULL,
	[ContinuousDayWise] [bit] NULL,
	[WhenBlocked_Daily] [datetime] NULL,
	[WhenBlocked_DayWise] [datetime] NULL,
	[WhenBlocked_WeekWise] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_BlockedEmployeesHistory]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory](
	[BlockId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeCard] [varchar](20) NULL,
	[Daily] [bit] NULL,
	[DayWise] [bit] NULL,
	[WeekWise] [bit] NULL,
	[QuarterWise] [bit] NULL,
	[ContinuousDayWise] [bit] NULL,
	[WhenBlocked_Daily] [datetime] NULL,
	[WhenBlocked_DayWise] [datetime] NULL,
	[WhenBlocked_WeekWise] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_BlockingType]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_BlockingType](
	[BlockingTypeID] [bigint] IDENTITY(1,1) NOT NULL,
	[BlockingType] [nvarchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_BlockingUnblockingEmployee]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_BlockingUnblockingEmployee](
	[AutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeCodeID] [nvarchar](200) NULL,
	[ShiftID] [bigint] NULL,
	[BlockingTypeID] [bigint] NULL,
	[BlockingDate] [datetime] NULL,
	[UnBlockingDate] [datetime] NULL,
	[ServiceExecuteTime] [datetime] NULL,
	[isStatus] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Branding]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_Branding](
	[img_id] [int] IDENTITY(1,1) NOT NULL,
	[Cus_Image] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Category]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Category](
	[CategoryId] [bigint] IDENTITY(1,1) NOT NULL,
	[CategoryName] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[EmpId] [bigint] NULL,
	[IsFlexible] [bit] NULL,
	[MonToSat_WorkHrs] [varchar](20) NULL,
	[Sat_WorkHrs] [numeric](18, 1) NULL,
	[WeekDay_WorkHrs] [varchar](20) NULL,
	[ARMIS_WorkHrs] [numeric](18, 1) NULL,
	[ParentIdForSubMenu] [int] NULL,
	[InActiveDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_ODApproval]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CCGroup_ODApproval](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupId] [bigint] NOT NULL,
	[CC_ODApproval] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_ODApproval] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Others]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CCGroup_Others](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupId] [bigint] NOT NULL,
	[CC_Others] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_Others] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Planned]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CCGroup_Planned](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupID] [bigint] NOT NULL,
	[CC_Planned] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_Planned] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_UnPlanned]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupID] [bigint] NOT NULL,
	[CC_UnPlanned] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_UnPlanned] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCMailGroup]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CCMailGroup](
	[CCGroupID] [bigint] IDENTITY(1,1) NOT NULL,
	[LevelID] [int] NOT NULL,
	[DesignationID] [int] NOT NULL,
	[MailTo_SecondLevel_Planned] [bit] NOT NULL,
	[MailTo_SecondLevel_UnPlanned] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCMailGroup] PRIMARY KEY CLUSTERED 
(
	[CCGroupID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ChangePassword]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ChangePassword](
	[EmployeeId] [int] NOT NULL,
	[OldPassword] [nvarchar](16) NOT NULL,
	[NewPassword] [nvarchar](16) NOT NULL,
	[ConfirmNewPassword] [nvarchar](16) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Clk_RawData]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Clk_RawData](
	[CLK_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimeStamp] [datetime] NOT NULL,
	[TimecheckDateTime] [datetime] NULL,
	[ReasonId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Clk_RawData] PRIMARY KEY CLUSTERED 
(
	[CLK_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Clk_RawDataErrorLogForAPIInsert]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Clk_RawDataErrorLogForAPIInsert](
	[CLK_ID] [int] IDENTITY(1,1) NOT NULL,
	[CLK_CARDID] [nvarchar](max) NULL,
	[CLK_DEVICEID] [nvarchar](max) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](50) NULL,
	[CLK_TYPE] [int] NULL,
	[ErrorMessage] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CMITechSyncEmployeeInfo]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CMITechSyncEmployeeInfo](
	[CMITechRecordNo] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [varchar](max) NOT NULL,
	[EmployeeName] [varchar](max) NOT NULL,
 CONSTRAINT [TA_Tbl_CMITechEmployeeInfo] PRIMARY KEY CLUSTERED 
(
	[CMITechRecordNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_CompanyGroup]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_CompanyGroup](
	[CompanyGroup] [varchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Compensation]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Compensation](
	[Compensation_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[ApplicationDate] [datetime] NULL,
	[FromDate] [datetime] NULL,
	[ToDate] [datetime] NULL,
	[Type] [numeric](18, 1) NULL,
	[Remarks] [nvarchar](2000) NULL,
	[Isdeleted] [bit] NULL,
	[LevelId] [bigint] NULL,
	[Status] [nvarchar](50) NULL,
	[LeaveApplication_Id] [nvarchar](200) NULL,
	[NoOfLeaveDays] [float] NULL,
	[InTime] [varchar](100) NULL,
	[OutTime] [varchar](100) NULL,
	[WorkedHours] [varchar](100) NULL,
	[DayWorked] [varchar](100) NULL,
	[Comments] [nvarchar](2000) NULL,
	[ExpiredDate] [datetime] NULL,
	[Quota] [float] NULL,
	[empid] [int] NULL,
	[ApprovedBy] [int] NULL,
	[ApprovedDate] [datetime] NULL,
	[RejectedBy] [int] NULL,
	[RejectedDate] [datetime] NULL,
	[TimeStamp] [datetime] NULL,
	[RemainingLeave] [float] NULL,
	[CompOffSatus] [nvarchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ConcurrentUser]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ConcurrentUser](
	[ConcurrentUserId] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [nvarchar](15) NOT NULL,
	[IpAddress] [nvarchar](15) NOT NULL,
	[LoginTime] [datetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[SessionId] [nvarchar](25) NOT NULL,
 CONSTRAINT [PK_TA_Tbl_ConcurrentUser] PRIMARY KEY CLUSTERED 
(
	[ConcurrentUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ConveyanceAllowance]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ConveyanceAllowance](
	[C_Id] [int] IDENTITY(1,1) NOT NULL,
	[ConPolicyName] [nvarchar](30) NULL,
	[conPercentage] [float] NULL,
	[conAmount] [bigint] NULL,
	[LimitAmount] [bigint] NULL,
	[Con_type] [varchar](50) NULL,
	[CompanyId] [int] NULL,
	[EmployeeCategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [int] NULL,
	[Created_BY] [int] NULL,
	[Created_Date] [date] NULL,
	[Modify_Date] [date] NULL,
	[isDeleted] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardData]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_DashboardData](
	[DataId] [int] IDENTITY(1,1) NOT NULL,
	[BoardParentName] [varchar](50) NULL,
	[BoardChildName] [varchar](50) NULL,
	[BoardId] [int] NULL,
 CONSTRAINT [PK__ta_tbl_D__9D05303DC71941DA] PRIMARY KEY CLUSTERED 
(
	[DataId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardUserrights]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_DashboardUserrights](
	[Rightsid] [int] IDENTITY(1,1) NOT NULL,
	[Usergroupid] [int] NULL,
	[Boardid] [int] NULL,
	[ViewPrev] [int] NULL,
	[Dashboard] [int] NULL,
	[Gridview] [int] NULL,
	[Chart] [int] NULL,
	[Empid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp](
	[LevelId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_DataProcessTemp]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_DataProcessTemp](
	[ProcessDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_DateandTimeFormat]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_DateandTimeFormat](
	[DateandTimeFormatId] [int] IDENTITY(1,1) NOT NULL,
	[DateFormat] [nvarchar](50) NULL,
	[TimeFormat] [nvarchar](50) NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[isDomain] [int] NULL,
	[DomainName] [nvarchar](500) NULL,
	[DomainAdminUserName] [nvarchar](500) NULL,
	[DomainAdminPassword] [nvarchar](1000) NULL,
 CONSTRAINT [PK_TA_Tbl_DateandTimeFormat] PRIMARY KEY CLUSTERED 
(
	[DateandTimeFormatId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Demo]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Demo](
	[InstalledDate] [nvarchar](100) NULL,
	[DemoExpiryDate] [nvarchar](100) NULL,
	[DemoType] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_DeviceLogTableDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_DeviceLogTableDetails](
	[tblAutoID] [int] IDENTITY(1,1) NOT NULL,
	[DeviceLog_TableName] [varchar](50) NULL,
	[LastLogID] [bigint] NULL,
	[LogFetch_LastTime] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_DeviceServerDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_DeviceServerDetails](
	[ServerName] [nvarchar](1000) NULL,
	[DatabaseName] [nvarchar](1000) NULL,
	[UserId] [varchar](100) NULL,
	[Password] [varchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_DummyShiftDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_DummyShiftDetails](
	[ShiftName] [varchar](100) NULL,
	[RecordID] [int] NULL,
	[FullShiftName] [varchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_EmailReportNotSendedDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_EmailReportNotSendedDetails](
	[ReScheduleid] [bigint] IDENTITY(1,1) NOT NULL,
	[Id] [bigint] NULL,
	[FromMailId] [nvarchar](max) NULL,
	[ToEmailIds] [nvarchar](max) NULL,
	[CCEmailIds] [nvarchar](max) NULL,
	[EmailSubject] [nvarchar](300) NULL,
	[Content] [nvarchar](max) NULL,
	[Attachment] [nvarchar](max) NULL,
	[AraisedFrom] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailSchedule]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmailSchedule](
	[ScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleName] [varchar](250) NOT NULL,
	[ReportId] [int] NOT NULL,
	[Frequency] [varchar](20) NOT NULL,
	[DayToSend] [varchar](10) NOT NULL,
	[DayFrom] [varchar](10) NOT NULL,
	[DayTo] [varchar](10) NOT NULL,
	[DateToSend] [int] NOT NULL,
	[DateFrom] [int] NOT NULL,
	[DateTo] [int] NOT NULL,
	[TimeToSend] [varchar](20) NOT NULL,
	[EmployeeId] [int] NOT NULL,
	[EmailSendType] [bit] NOT NULL,
	[Authentication] [bit] NOT NULL,
	[FileType] [varchar](20) NOT NULL,
	[Enabled] [bit] NOT NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[ReportName] [varchar](50) NULL,
	[ToWhom] [int] NULL,
	[TimeSendOption] [int] NULL,
	[Reminder_afterDays] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_EmailSchedule] PRIMARY KEY CLUSTERED 
(
	[ScheduleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduled_Employees]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmailScheduled_Employees](
	[ScheduleId] [bigint] NULL,
	[Employee_id] [bigint] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduleFilters]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmailScheduleFilters](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Filters] [varchar](max) NULL,
	[ReportType] [varchar](25) NULL,
	[CompanyId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_EmailScheduleFilters] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_EmailScheduleReminder]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_EmailScheduleReminder](
	[AutoID] [int] IDENTITY(1,1) NOT NULL,
	[ScheduledID] [bigint] NULL,
	[ReminderDate] [datetime] NULL,
	[status] [int] NULL,
	[frmDate] [datetime] NULL,
	[ToDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_EmailScheduleStatus]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_EmailScheduleStatus](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[DurationFrom] [datetime] NOT NULL,
	[DurationTo] [datetime] NOT NULL,
	[SentDate] [datetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[To_Mail] [varchar](50) NULL,
	[EmailID] [varchar](max) NULL,
	[ErrorMessage] [nvarchar](max) NULL,
 CONSTRAINT [PK_TA_tbl_EmailScheduleStatus] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_TBL_EmailScripts]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_TBL_EmailScripts](
	[ScriptId] [int] NOT NULL,
	[ScriptText] [varchar](max) NULL,
	[ScriptType] [nvarchar](200) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailTemplate]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmailTemplate](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Subject] [varchar](300) NOT NULL,
	[EmailContent] [varchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_EmailContent] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicy]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Emp_LeavePolicy](
	[Emp_LeavePolicyId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LeavePolicy_Id] [int] NULL,
	[FromDate] [datetime] NULL,
	[ToDate] [datetime] NULL,
	[YearSettingId] [int] NULL,
	[Isdeleted] [bit] NULL,
	[Time_stamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[AutoCredit] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_Emp_LeavePolicy] PRIMARY KEY CLUSTERED 
(
	[Emp_LeavePolicyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicyDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails](
	[Emp_LeavePolicyDetailsId] [int] IDENTITY(1,1) NOT NULL,
	[Emp_LeavePolicyId] [int] NULL,
	[EmpID] [int] NULL,
	[Policy_ID] [int] NULL,
	[LeaveType_Id] [int] NULL,
	[No_Of_Days] [decimal](18, 1) NULL,
	[Isdeleted] [bit] NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[MaxDays_Month] [decimal](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_Emp_LeavePolicyDetails] PRIMARY KEY CLUSTERED 
(
	[Emp_LeavePolicyDetailsId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_emp_LeaveTypedetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_emp_LeaveTypedetails](
	[LeaveTypeDetailsId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LeaveTypeId] [int] NULL,
	[PreviousYearBalance] [decimal](18, 1) NULL,
	[NoOffLeaveAvailed] [decimal](18, 1) NULL,
	[YearSettingsId] [int] NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_TaxPolicy]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Emp_TaxPolicy](
	[Emp_TaxPolicyId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[TaxPolicy_Id] [int] NULL,
	[isdeleted] [bit] NULL,
	[Time_stamp] [datetime] NULL,
	[Created_By] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[Emp_TaxPolicyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmpChildrenDetails]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmpChildrenDetails](
	[ChildEmp_ID] [int] IDENTITY(1,1) NOT NULL,
	[Emp_ID] [int] NOT NULL,
	[Spouse_Child] [char](1) NULL,
	[Name] [nvarchar](50) NULL,
	[DOB] [datetime] NULL,
	[Isdeleted] [bit] NULL,
	[Time_stamp] [datetime] NULL,
	[Employee_ID] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_EmpChildrenDetails] PRIMARY KEY CLUSTERED 
(
	[ChildEmp_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_EmployeeAPILog]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_EmployeeAPILog](
	[AutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[LogID] [bigint] NULL,
	[Log_Timestamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_EmployeeApprovedData_Samsung]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_EmployeeApprovedData_Samsung](
	[RecordID] [bigint] NULL,
	[Employee ID] [varchar](50) NULL,
	[Name] [varchar](250) NULL,
	[Organization] [varchar](500) NULL,
	[CL	Name] [varchar](20) NULL,
	[Gender] [varchar](20) NULL,
	[Work Group] [varchar](100) NULL,
	[Work Type] [varchar](100) NULL,
	[Work Date] [varchar](20) NULL,
	[Day Type] [varchar](100) NULL,
	[After Approve IN] [varchar](100) NULL,
	[After Approve OUT] [varchar](100) NULL,
	[Over Time Actual] [varchar](100) NULL,
	[Error_Message] [varchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeBonusLeave]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeBonusLeave](
	[BonusLeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[YearSettingId] [int] NULL,
	[EmployeeId] [int] NULL,
	[BonusLeaveQuota] [int] NULL,
	[EmpId] [int] NULL,
	[Timestamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_EmployeeBonusLeave] PRIMARY KEY CLUSTERED 
(
	[BonusLeaveId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeCategory]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeCategory](
	[EmployeeId] [bigint] NOT NULL,
	[CategoryId] [bigint] NOT NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeDesignation]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeDesignation](
	[EmpDesignationID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeID] [int] NULL,
	[DesignationID] [int] NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpID] [int] NULL,
	[Timestamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_EmployeeDesignation] PRIMARY KEY CLUSTERED 
(
	[EmpDesignationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_EmployeeErrorLog]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_EmployeeErrorLog](
	[autoID] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeCode] [nvarchar](250) NULL,
	[Error] [nvarchar](max) NULL,
	[ErrorTimestamp] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLevel]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeLevel](
	[EmployeeId] [bigint] NULL,
	[LevelId] [bigint] NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLingual]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeLingual](
	[EmployeeLingualId] [int] IDENTITY(1,1) NOT NULL,
	[LanguageId] [int] NOT NULL,
	[EmployeeId] [int] NOT NULL,
 CONSTRAINT [PK_EmployeeLingual] PRIMARY KEY CLUSTERED 
(
	[EmployeeLingualId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeePay]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeePay](
	[PayID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[BasicPay] [numeric](18, 2) NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpID] [int] NULL,
	[Timestamp] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_EmployeePay] PRIMARY KEY CLUSTERED 
(
	[PayID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_EmployeePunch]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_EmployeePunch](
	[RecordId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [varchar](5) NULL,
	[Date] [date] NULL,
	[Time] [time](7) NULL,
 CONSTRAINT [PK_Ta_Tbl_EmployeePunch] PRIMARY KEY CLUSTERED 
(
	[RecordId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]    Script Date: 10-30-2024 09:39:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation](
	[EmployeeAutoId] [bigint] NULL,
	[Date] [datetime] NULL,
	[CurrentShiftId] [int] NULL,
	[PreviousDayShift] [int] NULL,
	[NextDayShift] [int] NULL,
	[LoggedInEmployeId] [int] NULL,
	[Flag] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeTransferModule]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeTransferModule](
	[TrnsfrID] [int] IDENTITY(1,1) NOT NULL,
	[Employeeid] [int] NULL,
	[Employee_Code] [nvarchar](50) NULL,
	[Employee_Name] [nvarchar](100) NULL,
	[OrganizationLevels] [nvarchar](max) NULL,
	[Trnsfr_From] [nvarchar](50) NULL,
	[NwOrganizationLevels] [nvarchar](max) NULL,
	[OldLevelID] [int] NULL,
	[NwLevelID] [int] NULL,
	[NwDsgtonID] [int] NULL,
	[NwDsgton] [nvarchar](max) NULL,
	[Remarks] [nvarchar](max) NULL,
	[Trnsfr_EtyDteTme] [nvarchar](50) NULL,
	[Trnsfr_Emp_ID] [nvarchar](50) NULL,
	[Flag] [int] NULL,
	[EmployeeTrans_fr_Date] [nvarchar](50) NULL,
	[EmployeeTrans_To_Date] [nvarchar](50) NULL,
	[OldDsgtonID] [int] NULL,
	[IsDelete] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeType]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_EmployeeType](
	[EmployeeId] [bigint] NOT NULL,
	[TypeId] [bigint] NOT NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Encashment]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Encashment](
	[EncashmentId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[LeaveTypeId] [int] NOT NULL,
	[NumberOfDays] [decimal](18, 1) NOT NULL,
	[DateOfEncashment] [datetime] NOT NULL,
	[YearSettingId] [bigint] NOT NULL,
	[Reason] [nvarchar](50) NOT NULL,
	[Isdeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Encashment] PRIMARY KEY CLUSTERED 
(
	[EncashmentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Entrance](
	[Entrance_Id] [int] IDENTITY(1,1) NOT NULL,
	[Entrance_Name] [nvarchar](50) NOT NULL,
	[Entrance_Description] [nvarchar](250) NULL,
	[OrgLevel_Id] [int] NULL,
	[NoOfInTerminals] [int] NULL,
	[NoOfOutTerminals] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Emp_ID] [int] NULL,
	[Flag] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Entrance] PRIMARY KEY CLUSTERED 
(
	[Entrance_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrLog]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ErrLog](
	[ErrId] [bigint] IDENTITY(1,1) NOT NULL,
	[ErrMessage] [nvarchar](4000) NULL,
	[ErrSource] [nvarchar](4000) NULL,
	[ErrStackTrace] [nvarchar](4000) NULL,
	[ErrException] [nvarchar](4000) NULL,
	[TimestampRec] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Error_ImportData_Samsung]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_Error_ImportData_Samsung](
	[ErrorId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [varchar](100) NULL,
	[ErrorMsg] [varchar](max) NULL,
	[createdDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ClockRawData]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ErrorLog_ClockRawData](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Clock_Id] [nchar](20) NULL,
	[ErrorMessage] [varchar](max) NULL,
	[TimeStamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_ErrorLog_ClockRawData] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ProcessedData]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ErrorLog_ProcessedData](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Process_Rec_ID] [bigint] NULL,
	[ErrorMessage] [varchar](max) NULL,
	[TimeStamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_ErrorLog_ProcessedData] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_ExistingRightsDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_ExistingRightsDetails](
	[id] [int] NULL,
	[groupName] [nvarchar](500) NULL,
	[groupId] [int] NULL,
	[pageId] [float] NULL,
	[pageGroupId] [int] NULL,
	[addPrv] [bit] NULL,
	[modifyPrv] [bit] NULL,
	[deletePrv] [bit] NULL,
	[viewPrv] [bit] NULL,
	[isDeleted] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[employeeId] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ExportDataCentena]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ExportDataCentena](
	[DateImport] [datetime] NULL,
	[EmpCode] [varchar](50) NULL,
	[LeaveType] [varchar](20) NULL,
	[Days] [numeric](2, 1) NULL,
	[Remarks] [varchar](8000) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_Fencing]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_Fencing](
	[FencingId] [int] IDENTITY(1,1) NOT NULL,
	[Fencing_Name] [varchar](20) NULL,
	[LandmarkId] [varchar](20) NULL,
	[Createdby] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifyDate] [datetime] NULL,
	[CompanyId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_FencingAttendance]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_FencingAttendance](
	[EmpID] [int] NULL,
	[CurrentLatitude] [float] NULL,
	[CurrenrLongitude] [float] NULL,
	[EntryDate] [varchar](20) NULL,
	[EntryTime] [varchar](10) NULL,
	[PunchType] [varchar](20) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_FolderPathConfiguration]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_FolderPathConfiguration](
	[FolderPathConfiguration_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeFolderPath] [varchar](max) NULL,
	[OndutyFolderPath] [varchar](max) NULL,
	[LeaveFolderPath] [varchar](max) NULL,
	[CreatedBy] [bigint] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedBy] [bigint] NULL,
	[ModifiedDate] [datetime] NULL,
	[AttendanceData] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_GeoFencing]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_GeoFencing](
	[Fencing_Id] [int] IDENTITY(1,1) NOT NULL,
	[FencingName] [varchar](30) NULL,
	[LandmarkId] [varchar](100) NULL,
	[CompanyId] [int] NULL,
	[Created_By] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifyDate] [datetime] NULL,
	[isDeleted] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_GeoFencingAllocation]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_GeoFencingAllocation](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[FencingId] [int] NULL,
	[FromDate] [varchar](20) NULL,
	[Todate] [varchar](20) NULL,
	[CreatedBy] [int] NULL,
	[CreatedOn] [varchar](20) NULL,
	[ModifyBy] [int] NULL,
	[ModifyOn] [varchar](20) NULL,
	[months] [int] NULL,
	[years] [bigint] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_GlobalWeekdaySettings]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_GlobalWeekdaySettings](
	[GlobalWeekday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[GlobalWeekday_HrsMonday] [int] NOT NULL,
	[GlobalWeekday_HrsTuesday] [int] NOT NULL,
	[GlobalWeekday_HrsWenesday] [int] NOT NULL,
	[GlobalWeekday_HrsThursday] [int] NOT NULL,
	[GlobalWeekday_HrsFriday] [int] NOT NULL,
	[GlobalWeekday_HrsSaturday] [int] NOT NULL,
	[GlobalWeekday_HrsSunday] [int] NOT NULL,
	[GlobalWeekday_MondayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_TuesdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_WensdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_ThursdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_FridayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_SaturdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_SundayWeekOff] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_GraceDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_GraceDetails](
	[ShiftID] [int] NULL,
	[OldGraceShiftIn] [nvarchar](6) NULL,
	[OldGraceShiftOut] [nvarchar](6) NULL,
	[Shift_BreakStartTime1] [nvarchar](10) NULL,
	[Shift_BreakEndTime1] [nvarchar](10) NULL,
	[Shift_BreakStartTime2] [nvarchar](10) NULL,
	[Shift_BreakEndTime2] [nvarchar](10) NULL,
	[Shift_BreakStartTime3] [nvarchar](10) NULL,
	[Shift_BreakEndTime3] [nvarchar](10) NULL,
	[TimeStamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Grade]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Grade](
	[Grade_ID] [int] IDENTITY(1,1) NOT NULL,
	[Grade_Name] [nvarchar](50) NOT NULL,
	[Grade_Level] [int] NULL,
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL,
	[Isdeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_Grade] PRIMARY KEY CLUSTERED 
(
	[Grade_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_GroupDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_GroupDetails](
	[Group_Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Name] [nvarchar](50) NOT NULL,
	[Group_Description] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_HelpContent]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_HelpContent](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Header] [nvarchar](max) NULL,
	[Paragraph] [nvarchar](max) NULL,
	[createdDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Holiday]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Holiday](
	[Holiday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Holiday_Type] [char](1) NOT NULL,
	[Holiday_FromDate] [datetime] NOT NULL,
	[Holiday_ToDate] [datetime] NULL,
	[Holiday_Description] [nvarchar](250) NOT NULL,
	[YearSettings_Id] [int] NULL,
	[Isdeleted] [bit] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[LevelId] [bigint] NULL,
 CONSTRAINT [PK_TA_Tbl_Holiday] PRIMARY KEY CLUSTERED 
(
	[Holiday_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidayChildTable]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_HolidayChildTable](
	[Holiday_ChildId] [int] IDENTITY(1,1) NOT NULL,
	[LevelId] [bigint] NULL,
	[Holiday_Id] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_HolidayHistory]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_HolidayHistory](
	[Holiday_Id] [int] NULL,
	[userId] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[Type] [varchar](20) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidaySettings]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_HolidaySettings](
	[Holiday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Global_Maxdays] [int] NOT NULL,
	[Yearly_Maxdays] [int] NOT NULL,
	[YearSettingId] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_HolidaySettings] PRIMARY KEY CLUSTERED 
(
	[Holiday_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidayTriggerforAudit]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_HolidayTriggerforAudit](
	[TriggerID] [int] IDENTITY(1,1) NOT NULL,
	[HolidayID] [int] NULL,
	[EmployeeID] [int] NULL,
	[Type] [nvarchar](50) NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_ImportMasterData]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_ImportMasterData](
	[EmployeeID] [int] NULL,
	[Emp_FirstName] [nvarchar](250) NULL,
	[Emp_MiddleName] [nvarchar](250) NULL,
	[Emp_LastName] [nvarchar](250) NULL,
	[Father_Name] [nvarchar](250) NULL,
	[Mother_Name] [nvarchar](250) NULL,
	[DateOfBirth] [nvarchar](250) NULL,
	[DateOfBirth_Record] [nvarchar](250) NULL,
	[Blood_Group] [nvarchar](5) NULL,
	[Email_Id] [nvarchar](250) NULL,
	[Contact_Address] [nvarchar](2250) NULL,
	[Permanent_Address] [nvarchar](2250) NULL,
	[Phone_Number] [nvarchar](250) NULL,
	[Mobile_Number] [nvarchar](250) NULL,
	[Gender] [nvarchar](250) NULL,
	[Marital_Status] [nvarchar](250) NULL,
	[Nationality] [nvarchar](250) NULL,
	[Religion] [nvarchar](250) NULL,
	[Personal_EmailID] [nvarchar](250) NULL,
	[Passport_No] [nvarchar](250) NULL,
	[Passport_ExpiryDate] [nvarchar](250) NULL,
	[Visa_No] [nvarchar](250) NULL,
	[Visa_ExpiryDate] [nvarchar](250) NULL,
	[Employee_Code] [nvarchar](25) NULL,
	[DateOfJoining] [nvarchar](25) NULL,
	[Qualification_joiningtime] [nvarchar](25) NULL,
	[Qualification_Employement] [nvarchar](25) NULL,
	[OutDoorJob] [bit] NULL,
	[CompOff_Eligible] [bit] NULL,
	[OT_Eligible] [bit] NULL,
	[ESI_Eligible] [bit] NULL,
	[PF_Eligible] [bit] NULL,
	[Report_Exclude] [bit] NULL,
	[Employee_Status] [bit] NULL,
	[SwipeCardNo] [nvarchar](250) NULL,
	[IsDeleted] [bit] NULL,
	[Hostel] [bit] NULL,
	[Designation] [nvarchar](250) NULL,
	[Grade] [nvarchar](250) NULL,
	[GradeNo] [nvarchar](250) NULL,
	[EmployeeType] [nvarchar](250) NULL,
	[EmployeeCategory] [nvarchar](250) NULL,
	[BasicSalary] [nvarchar](10) NULL,
	[Level1] [nvarchar](250) NULL,
	[Level2] [nvarchar](250) NULL,
	[Level3] [nvarchar](250) NULL,
	[Level4] [nvarchar](250) NULL,
	[Level5] [nvarchar](250) NULL,
	[Level6] [nvarchar](250) NULL,
	[Level7] [nvarchar](250) NULL,
	[Level8] [nvarchar](250) NULL,
	[Level9] [nvarchar](250) NULL,
	[Level10] [nvarchar](250) NULL,
	[Level1_Id] [int] NULL,
	[Level2_Id] [int] NULL,
	[Level3_Id] [int] NULL,
	[Level4_Id] [int] NULL,
	[Level5_Id] [int] NULL,
	[Level6_Id] [int] NULL,
	[Level7_Id] [int] NULL,
	[Level8_Id] [int] NULL,
	[Level9_Id] [int] NULL,
	[Level10_Id] [int] NULL,
	[childLevelId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportMasterError]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ImportMasterError](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[Emp_FirstName] [nvarchar](50) NULL,
	[Emp_MiddleName] [nvarchar](50) NULL,
	[Emp_LastName] [nvarchar](50) NULL,
	[Father_Name] [nvarchar](50) NULL,
	[Mother_Name] [nvarchar](50) NULL,
	[DateOfBirth] [nvarchar](20) NULL,
	[DateOfBirth_Record] [nvarchar](20) NULL,
	[Blood_Group] [nvarchar](10) NULL,
	[Email_Id] [nvarchar](100) NULL,
	[Contact_Address] [nvarchar](max) NULL,
	[Permanent_Address] [nvarchar](max) NULL,
	[Phone_Number] [nvarchar](50) NULL,
	[Mobile_Number] [nvarchar](50) NULL,
	[Gender] [nvarchar](10) NULL,
	[Marital_Status] [nvarchar](10) NULL,
	[Nationality] [nvarchar](50) NULL,
	[Religion] [nvarchar](50) NULL,
	[Personal_EmailID] [nvarchar](100) NULL,
	[Passport_No] [nvarchar](50) NULL,
	[Passport_ExpiryDate] [nvarchar](20) NULL,
	[Visa_No] [nvarchar](50) NULL,
	[Visa_ExpiryDate] [nvarchar](20) NULL,
	[Employee_Code] [nvarchar](50) NULL,
	[DateOfJoining] [nvarchar](20) NULL,
	[Qualification_joiningtime] [nvarchar](50) NULL,
	[Qualification_Employement] [nvarchar](50) NULL,
	[CompOff_Eligible] [nvarchar](5) NULL,
	[OT_Eligible] [nvarchar](5) NULL,
	[Report_Exclude] [nvarchar](5) NULL,
	[Employee_Status] [nvarchar](5) NULL,
	[IsDeleted] [nvarchar](5) NULL,
	[Hostel] [nvarchar](5) NULL,
	[Designation] [nvarchar](200) NULL,
	[Grade] [nvarchar](50) NULL,
	[GradeNo] [nvarchar](50) NULL,
	[Employee_Type] [nvarchar](100) NULL,
	[Employee_Category] [nvarchar](100) NULL,
	[BasicSalary] [nvarchar](50) NULL,
	[Level1] [nvarchar](100) NULL,
	[Level2] [nvarchar](100) NULL,
	[Level3] [nvarchar](100) NULL,
	[Level4] [nvarchar](100) NULL,
	[Level5] [nvarchar](100) NULL,
	[Level6] [nvarchar](100) NULL,
	[Level7] [nvarchar](100) NULL,
	[Level8] [nvarchar](100) NULL,
	[Level9] [nvarchar](100) NULL,
	[Level10] [nvarchar](100) NULL,
	[IsValid] [int] NULL,
	[Error] [nvarchar](max) NULL,
	[RecordNumber] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportShiftAllocation]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ImportShiftAllocation](
	[Employee_Id] [int] NULL,
	[Employee_Code_Id] [varchar](100) NULL,
	[Company_Id] [int] NULL,
	[Company_Name] [varchar](250) NULL,
	[Year] [varchar](5) NULL,
	[Mon] [varchar](20) NULL,
	[Day1] [varchar](8) NULL,
	[Day2] [varchar](8) NULL,
	[Day3] [varchar](8) NULL,
	[Day4] [varchar](8) NULL,
	[Day5] [varchar](8) NULL,
	[Day6] [varchar](8) NULL,
	[Day7] [varchar](8) NULL,
	[Day8] [varchar](8) NULL,
	[Day9] [varchar](8) NULL,
	[Day10] [varchar](8) NULL,
	[Day11] [varchar](8) NULL,
	[Day12] [varchar](8) NULL,
	[Day13] [varchar](8) NULL,
	[Day14] [varchar](8) NULL,
	[Day15] [varchar](8) NULL,
	[Day16] [varchar](8) NULL,
	[Day17] [varchar](8) NULL,
	[Day18] [varchar](8) NULL,
	[Day19] [varchar](8) NULL,
	[Day20] [varchar](8) NULL,
	[Day21] [varchar](8) NULL,
	[Day22] [varchar](8) NULL,
	[Day23] [varchar](8) NULL,
	[Day24] [varchar](8) NULL,
	[Day25] [varchar](8) NULL,
	[Day26] [varchar](8) NULL,
	[Day27] [varchar](8) NULL,
	[Day28] [varchar](8) NULL,
	[Day29] [varchar](8) NULL,
	[Day30] [varchar](8) NULL,
	[Day31] [varchar](8) NULL,
	[ImportID] [int] IDENTITY(1,1) NOT NULL,
	[RecordNumber] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_LandMarks]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_LandMarks](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Options] [nvarchar](max) NULL,
	[LocationName] [nvarchar](500) NULL,
	[Radius] [int] NULL,
	[Description] [nvarchar](1000) NULL,
	[Address] [nvarchar](500) NULL,
	[City] [nvarchar](500) NULL,
	[State] [nvarchar](500) NULL,
	[Country] [nvarchar](500) NULL,
	[latitude] [varchar](30) NULL,
	[longitude] [varchar](30) NULL,
	[CreatedBy] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_LastUpdationofFile_Samsung]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_LastUpdationofFile_Samsung](
	[UpdationId] [bigint] IDENTITY(1,1) NOT NULL,
	[UpdationDatetime] [datetime] NULL,
	[Recordscount] [bigint] NULL,
	[LastEmployeeAutoId] [bigint] NULL,
	[DataName] [varchar](25) NULL,
	[Filepath] [varchar](max) NULL,
	[LastFileModifiedDate] [datetime] NULL,
	[LastFileCreationDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveAnalysisNotes]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Notes] [varchar](8000) NULL,
	[DateInserted] [datetime] NULL,
	[EmpID] [int] NULL,
	[IsDeleted] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplication]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveApplication](
	[LeaveApplication_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [int] NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[LeaveType_id] [int] NOT NULL,
	[Type] [nvarchar](50) NOT NULL,
	[Leave_FromDate] [datetime] NOT NULL,
	[Leave_ToDate] [datetime] NOT NULL,
	[Leave_SessionFrom] [nvarchar](50) NULL,
	[Leave_SessionTo] [nvarchar](50) NULL,
	[NumberOfDays] [decimal](18, 1) NOT NULL,
	[Reason] [nvarchar](1000) NULL,
	[IntimationType] [nvarchar](25) NULL,
	[Status] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Remarks] [nvarchar](1000) NULL,
	[IsBorrow] [bit] NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[CheckedIDs] [int] NULL,
	[InformTo] [varchar](max) NULL,
	[companyId] [int] NULL,
	[Successiveyear] [bit] NULL,
	[Intervening] [char](5) NULL,
	[MCFilePath] [varchar](200) NULL,
	[isCalanderflag] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveApplication] PRIMARY KEY CLUSTERED 
(
	[LeaveApplication_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplication_FileUpload]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[FileName] [varchar](50) NOT NULL,
	[FilePath] [nvarchar](200) NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[LeaveApplication_Id] [bigint] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationExists]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationExists](
	[LeaveApplicationId] [bigint] NULL,
	[Employee_Id] [nvarchar](20) NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[Leave_FromDate] [datetime] NOT NULL,
	[Leave_ToDate] [datetime] NOT NULL,
	[Leave_SessionFrom] [nvarchar](50) NOT NULL,
	[Leave_SessionTo] [nvarchar](50) NOT NULL,
	[Status] [nvarchar](50) NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationMaster]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationMaster](
	[LeaveApplication_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [nvarchar](20) NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[Reason] [nvarchar](1000) NULL,
	[IntimationType] [nvarchar](25) NULL,
	[Status] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[CCMail] [varchar](3000) NULL,
	[LeaveAvailedYear] [decimal](18, 1) NULL,
	[LeaveAvailedMonth] [decimal](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveApplicationMaster] PRIMARY KEY CLUSTERED 
(
	[LeaveApplication_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman](
	[Autoid] [int] NOT NULL,
	[leaveAppID] [bigint] NULL,
	[LeaveTaken] [decimal](18, 1) NULL,
	[EarnedLeave] [decimal](18, 1) NULL,
	[LOP] [decimal](18, 1) NULL,
	[LeaveBalance] [decimal](18, 1) NULL,
	[WaiveOff] [decimal](18, 1) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveConversation]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveConversation](
	[LeaveConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[LeaveApplicationId] [bigint] NOT NULL,
	[CommentsBy] [int] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveConversation] PRIMARY KEY CLUSTERED 
(
	[LeaveConversationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicy]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeavePolicy](
	[Policy_Id] [int] IDENTITY(1,1) NOT NULL,
	[PolicyName] [nvarchar](50) NOT NULL,
	[Permission_MaxHrs_Month] [nvarchar](5) NULL,
	[Permission_MaxInstances_Month] [int] NULL,
	[Permission_MaxHrs_Instance] [nvarchar](5) NULL,
	[PermissionBeforeLeave] [bit] NULL,
	[PermissionAfterLeave] [bit] NULL,
	[OtHourWise] [bit] NULL,
	[OtDayWise] [bit] NULL,
	[OtMinHrs] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[EmployeeCategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](10) NULL,
	[Religion] [int] NULL,
	[CompOffValidDays] [int] NULL,
	[FullDayOTMinHrs] [nvarchar](5) NULL,
	[companyID] [int] NULL,
	[Permission_MinHrs_Instance] [nvarchar](5) NULL,
 CONSTRAINT [PK_TA_Tbl_LeavePolicy] PRIMARY KEY CLUSTERED 
(
	[Policy_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicyDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeavePolicyDetails](
	[PolicyDetails_Id] [int] IDENTITY(1,1) NOT NULL,
	[Policy_Id] [int] NOT NULL,
	[LeaveType_Id] [int] NOT NULL,
	[MaxDays_applicable] [decimal](18, 1) NOT NULL,
	[MaxDays_avail] [decimal](18, 1) NULL,
	[MinDays_avail] [decimal](18, 1) NULL,
	[Spells] [int] NULL,
	[MaxDays_Acc] [decimal](18, 1) NULL,
	[LossOfPay] [bit] NOT NULL,
	[Max_LOP_Days] [decimal](18, 1) NOT NULL,
	[Count_BeforeWeeklyOff] [bit] NOT NULL,
	[Count_AfterWeeklyOff] [bit] NOT NULL,
	[Count_Intervening] [bit] NULL,
	[Borrow_FromNextYear] [bit] NOT NULL,
	[Carry_ToNextYear] [bit] NOT NULL,
	[Encashment] [bit] NULL,
	[Calc_Factor] [decimal](18, 1) NULL,
	[MinWorkDays] [decimal](18, 0) NULL,
	[WeekDays] [bit] NULL,
	[WeekOff] [bit] NULL,
	[Leave] [bit] NULL,
	[Holidays] [bit] NULL,
	[ApplicableAfterDays] [decimal](18, 1) NULL,
	[Emp_Id] [int] NOT NULL,
	[Time_stamp] [datetime] NULL,
	[MaxDays_Month] [decimal](18, 1) NULL,
	[AvailServicePeriod] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_LeavePolicyDetails] PRIMARY KEY CLUSTERED 
(
	[PolicyDetails_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePrivateNotes]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeavePrivateNotes](
	[LeavePrivateNotesId] [bigint] IDENTITY(1,1) NOT NULL,
	[LeaveApplicationId] [int] NOT NULL,
	[NotesBy] [int] NOT NULL,
	[Notes] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[ToMailIds] [nvarchar](4000) NULL,
	[CcMailIds] [nvarchar](4000) NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_TA_Tbl_LeavePrivateNotes] PRIMARY KEY CLUSTERED 
(
	[LeavePrivateNotesId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveSettings]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveSettings](
	[MailSettingId] [bigint] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NULL,
	[Approval] [bit] NULL,
	[FirstLevelIntimation] [bit] NULL,
	[SecondLevelIntimation] [bit] NULL,
	[ApprovalCC] [varchar](8000) NULL,
	[ToMail_DailyReport] [varchar](8000) NULL,
	[CCMail_DailyReport] [varchar](8000) NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveSettings] PRIMARY KEY CLUSTERED 
(
	[MailSettingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveType]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LeaveType](
	[LeaveType_Id] [int] IDENTITY(1,1) NOT NULL,
	[LeaveType] [nvarchar](10) NOT NULL,
	[LeaveDescription] [nvarchar](250) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL,
	[CountFactor] [bit] NOT NULL,
	[Employeecategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](10) NULL,
	[Religion] [int] NULL,
	[isWFH] [int] NULL,
	[IsProrataRequired] [bit] NULL,
	[IsDocProofRequired] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveType] PRIMARY KEY CLUSTERED 
(
	[LeaveType_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Level]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Level](
	[levelID] [int] IDENTITY(1,1) NOT NULL,
	[levelName] [nvarchar](255) NULL,
	[parentLevelID] [int] NULL,
	[isDeleted] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[emp_Id] [nvarchar](50) NULL,
 CONSTRAINT [PK_TA_Tbl_Level] PRIMARY KEY CLUSTERED 
(
	[levelID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LevelChanges]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LevelChanges](
	[LevelChangeId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[Emp_LevelID] [int] NULL,
	[Transfer_FromDate] [datetime] NULL,
	[Transfer_ToDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_levelDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_levelDetails](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[levelId] [int] NULL,
	[parentId] [int] NULL,
	[name] [nvarchar](255) NULL,
	[description] [nvarchar](255) NULL,
	[city] [nvarchar](100) NULL,
	[state] [nvarchar](100) NULL,
	[country] [nvarchar](100) NULL,
	[zip] [nvarchar](50) NULL,
	[phone1] [nvarchar](50) NULL,
	[phone2] [nvarchar](50) NULL,
	[fax1] [nvarchar](50) NULL,
	[fax2] [nvarchar](50) NULL,
	[email] [nvarchar](255) NULL,
	[webAddress] [nvarchar](255) NULL,
	[logo] [image] NULL,
	[isDeleted] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[Emp_id] [nvarchar](50) NULL,
	[ToMailIds] [varchar](4000) NULL,
	[CCMailIds] [varchar](4000) NULL,
	[TimezoneId] [int] NULL,
 CONSTRAINT [PK_Ta_Tbl_levelDetails] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LevelRights]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LevelRights](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[GroupId] [int] NULL,
	[LevelId] [nvarchar](50) NULL,
	[emp_id] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LIC_Details]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LIC_Details](
	[CustomerId] [nvarchar](200) NULL,
	[PackageId] [nvarchar](200) NOT NULL,
	[PackageVersion] [nvarchar](200) NOT NULL,
	[NoOfConcurrentUser] [nvarchar](200) NOT NULL,
	[MACAddress] [nvarchar](200) NOT NULL,
	[LicenseGenerationDate] [nvarchar](200) NOT NULL,
	[ExpiryDate] [nvarchar](200) NOT NULL,
	[Module] [nvarchar](200) NOT NULL,
	[Module1] [nvarchar](200) NOT NULL,
	[Module2] [nvarchar](200) NOT NULL,
	[Module3] [nvarchar](200) NOT NULL,
	[Module4] [nvarchar](200) NOT NULL,
	[Module5] [nvarchar](200) NOT NULL,
	[NoOfEmployee] [nvarchar](200) NULL,
	[NoOfTerminal] [nvarchar](200) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LicenseRequestDetail]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LicenseRequestDetail](
	[RequestID] [bigint] NOT NULL,
	[Status] [bit] NULL,
	[MacAddress] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LoanEntryDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LoanEntryDetails](
	[Loan_ID] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [int] NULL,
	[Loan_Amount] [bigint] NULL,
	[Total_DeductionMonth] [numeric](18, 0) NULL,
	[Deduction_StartMonth] [nvarchar](20) NULL,
	[Monthly_DeductAmount] [bigint] NULL,
	[Loan_BalanceAmount] [bigint] NULL,
	[Loan_Description] [nvarchar](50) NULL,
	[isdeleted] [bit] NULL,
	[Loan_Entry_Date] [datetime] NULL,
	[ModifyDate] [datetime] NULL,
	[ISLoanClose] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[Loan_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LoanTransaction]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LoanTransaction](
	[LoanTransact_Id] [int] IDENTITY(1,1) NOT NULL,
	[LoanID] [int] NULL,
	[LoanAmount] [bigint] NULL,
	[TransactionDate] [datetime] NULL,
	[CreditedAmount] [bigint] NULL,
	[Balance_Amount] [bigint] NULL,
	[Remaining_DueMonth] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[LoanTransact_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_LockLogin]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_LockLogin](
	[UserName] [nvarchar](1000) NULL,
	[LockedTime] [datetime] NULL,
	[IsActive] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_LogDownloaded]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_LogDownloaded](
	[LoggedId] [int] IDENTITY(1,1) NOT NULL,
	[LoggedEmployeeId] [int] NOT NULL,
	[LoggedDate] [datetime] NOT NULL,
 CONSTRAINT [PK__ta_tbl_L__0605AD131E9FCF4A] PRIMARY KEY CLUSTERED 
(
	[LoggedId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Login]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Login](
	[Username] [nvarchar](2000) NOT NULL,
	[LastLoginTime] [varchar](20) NULL,
	[LastLogoutTime] [varchar](20) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Lookup]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Lookup](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Type] [int] NULL,
	[Title] [nvarchar](50) NULL,
	[Parent] [int] NULL,
	[Remarks] [nvarchar](50) NULL,
	[EmpID] [int] NULL,
	[Time_stamp] [datetime] NULL,
	[Isdeleted] [bit] NULL,
	[Emp_ID] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Lookup] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_MailConfiguration]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_MailConfiguration](
	[FromEmailId] [varchar](300) NULL,
	[SMTPClientHost] [varchar](100) NULL,
	[SMTPPort] [varchar](50) NULL,
	[SSLEnable] [bit] NULL,
	[MailAuthentication] [bit] NULL,
	[MailAuthenticateUser] [nvarchar](30) NULL,
	[MailAuthenticatePassword] [nvarchar](30) NULL,
	[isRequired] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_MailIdsForTriggeringEmail]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[MailType] [varchar](5) NOT NULL,
	[EmailID] [varchar](250) NOT NULL,
 CONSTRAINT [PK_TA_tbl_MailIdsForTriggeringEmail] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ManualTimeEntry]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ManualTimeEntry](
	[ManualTimeEntry_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
	[ManualTimeEntry_Date] [datetime] NULL,
	[ManualTimeEntry_InDate] [datetime] NULL,
	[ManualTimeEntry_InTime] [nvarchar](50) NULL,
	[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_OutDate] [datetime] NULL,
	[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
	[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_InReaderID] [int] NULL,
	[ManualTimeEntry_OutReaderID] [int] NULL,
	[ManualTimeEntry_Reason] [nvarchar](255) NULL,
	[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
	[Route_Id] [int] NULL,
	[Clk_Process] [nvarchar](1) NULL,
	[ManualTimeEntry_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[IsDiscrepancyEntry] [bit] NULL,
	[IsOnDuty] [bit] NULL,
	[Shift_Id] [int] NULL,
	[Shift_Date] [datetime] NULL,
	[IsImported] [int] NULL,
	[OnDuty_ID] [bigint] NULL,
	[modify_By] [int] NULL,
	[modify_date] [datetime] NULL,
	[Latitude_value] [varchar](20) NULL,
	[Longitude_value] [varchar](20) NULL,
	[Clock_Address] [varchar](500) NULL,
 CONSTRAINT [PK_TA_Tbl_ManualTimeEntry] PRIMARY KEY CLUSTERED 
(
	[ManualTimeEntry_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_ManualTimeEntrybck]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_ManualTimeEntrybck](
	[ManualTimeEntry_Id] [int] IDENTITY(1,1) NOT NULL,
	[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
	[ManualTimeEntry_Date] [datetime] NULL,
	[ManualTimeEntry_InDate] [datetime] NULL,
	[ManualTimeEntry_InTime] [nvarchar](50) NULL,
	[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_OutDate] [datetime] NULL,
	[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
	[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_InReaderID] [int] NULL,
	[ManualTimeEntry_OutReaderID] [int] NULL,
	[ManualTimeEntry_Reason] [nvarchar](255) NULL,
	[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
	[Route_Id] [int] NULL,
	[Clk_Process] [char](1) NULL,
	[ManualTimeEntry_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_MatchedPunches]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_MatchedPunches](
	[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_EmpId] [nvarchar](20) NULL,
	[Clk_InDeviceId] [nvarchar](20) NULL,
	[Clk_InDate] [datetime] NULL,
	[Clk_InTime] [datetime] NULL,
	[Clk_InPunchType] [nvarchar](25) NULL,
	[Clk_OutDeviceId] [nvarchar](20) NULL,
	[Clk_OutDate] [datetime] NULL,
	[Clk_OutTime] [datetime] NULL,
	[Clk_OutPunchType] [nvarchar](25) NULL,
	[Clk_Date] [datetime] NULL,
	[PunchDiffInHours]  AS (isnull([clk_OutTime]-[clk_Intime],'')),
	[PunchDiffInMin]  AS (isnull(datepart(hour,[clk_OutTime]-[clk_Intime])*(60)+datepart(minute,[clk_OutTime]-[clk_Intime]),(0)))
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_mobileClockInAndOut]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_mobileClockInAndOut](
	[Autoid] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeCodeID] [varchar](20) NULL,
	[ClockDate] [datetime] NULL,
	[Clock_Time] [varchar](15) NULL,
	[PunchType] [varchar](20) NULL,
	[InsertedOn] [datetime] NULL,
	[Latitude_value] [varchar](20) NULL,
	[Longitude_value] [varchar](20) NULL,
	[Clock_Address] [varchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_MonthClosure]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_MonthClosure](
	[MonthClosure_Id] [int] IDENTITY(1,1) NOT NULL,
	[OrgLevel_Id] [int] NULL,
	[MonthClosure_Month] [nvarchar](15) NULL,
	[MonthClosure_Year] [int] NULL,
	[MonthClosure_StartDate] [datetime] NULL,
	[MonthClosure_EndDate] [datetime] NULL,
	[MonthClosure_ClosingDate] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[Process] [char](1) NULL,
	[TimeStamp] [datetime] NULL,
	[IsDeleted] [bit] NULL,
	[YearSettings_Id] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_MonthClosure] PRIMARY KEY CLUSTERED 
(
	[MonthClosure_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_MultiLingual]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_MultiLingual](
	[Language_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Language_Name] [nvarchar](50) NULL,
	[Resource_File_Name] [nvarchar](50) NULL,
	[IsActive] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_MultiLingual] PRIMARY KEY CLUSTERED 
(
	[Language_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_MyProfileDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_MyProfileDetails](
	[myprofileID] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [int] NULL,
	[SwipeCardNo] [nvarchar](50) NULL,
	[Employee_FirstName] [nvarchar](50) NULL,
	[Employee_MiddleName] [nvarchar](50) NULL,
	[Employee_LastName] [nvarchar](50) NULL,
	[Father_name] [nvarchar](50) NULL,
	[Mother_name] [nvarchar](50) NULL,
	[DateofBirth] [datetime] NULL,
	[DateofBirth_Record] [datetime] NULL,
	[Blood_Group] [nvarchar](10) NULL,
	[EmailId] [nvarchar](100) NULL,
	[Personal_mailid] [nvarchar](100) NULL,
	[Contact_Address] [nvarchar](255) NULL,
	[Permanent_Address] [nvarchar](255) NULL,
	[Phone_Number] [nvarchar](50) NULL,
	[Mobile_Number] [nvarchar](50) NULL,
	[Marital_status] [nvarchar](10) NULL,
	[Nationality] [nvarchar](50) NULL,
	[Religion] [int] NULL,
	[Country] [int] NULL,
	[State] [int] NULL,
	[City] [int] NULL,
	[District] [nvarchar](50) NULL,
	[Status] [varchar](30) NULL,
	[ModifiedDate] [datetime] NULL,
	[IsPath] [nvarchar](200) NULL,
	[Remarks] [varchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_NewsEvents]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_NewsEvents](
	[NewsEvent_Id] [int] IDENTITY(1,1) NOT NULL,
	[NewsEventFromDate] [datetime] NULL,
	[NewsEventToDate] [datetime] NULL,
	[NewsEventTitle] [nvarchar](100) NULL,
	[NewsEventDescription] [nvarchar](500) NULL,
	[NewsEventActive] [bit] NULL,
	[NewsEventImage] [nvarchar](255) NULL,
	[LeftNewsEvent] [bit] NULL,
	[RightNewsEvent] [bit] NULL,
	[LeftBanner] [bit] NULL,
	[RightBanner] [bit] NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [decimal](18, 0) NULL,
 CONSTRAINT [PK_TA_Tbl_NewsEvents] PRIMARY KEY CLUSTERED 
(
	[NewsEvent_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Armis]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Armis](
	[ArmisID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_Armis] PRIMARY KEY CLUSTERED 
(
	[ArmisID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry](
	[LateEntryID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_Lateentry] PRIMARY KEY CLUSTERED 
(
	[LateEntryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs](
	[WorkhrsID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_WorkHrs] PRIMARY KEY CLUSTERED 
(
	[WorkhrsID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_NotProcessedDataDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_NotProcessedDataDetails](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Process_Rec_ID] [int] NULL,
	[SwipeCardNumber] [varchar](50) NULL,
	[ReaderId] [int] NULL,
	[Reason] [varchar](200) NULL,
	[RaisedFrom] [char](1) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_OnDutyConversation]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_OnDutyConversation](
	[OnDutyConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[OnDutyApplicationId] [bigint] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_OndutyEntry]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_OndutyEntry](
	[Onduty_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[Onduty_EmployeeID] [nvarchar](20) NULL,
	[Onduty_EntryDate] [datetime] NULL,
	[Onduty_Type] [int] NULL,
	[IncludeWeekOff] [int] NULL,
	[Onduty_FromDate] [datetime] NULL,
	[Onduty_FromTime] [nvarchar](50) NULL,
	[Onduty_ToDate] [datetime] NULL,
	[Onduty_ToTime] [nvarchar](50) NULL,
	[Onduty_Reason] [nvarchar](255) NULL,
	[Onduty_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[From_Session] [nvarchar](20) NULL,
	[To_Session] [nvarchar](20) NULL,
	[YearSettings_Id] [int] NULL,
	[isImported] [bit] NULL,
PRIMARY KEY CLUSTERED 
(
	[Onduty_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_OracleDBConfiguration]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_OracleDBConfiguration](
	[HostName] [varchar](100) NULL,
	[Port] [varchar](5) NULL,
	[ServiceName] [varchar](100) NULL,
	[UserName] [varchar](100) NULL,
	[Pwd] [varchar](100) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_oracleSync]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_oracleSync](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[SyncDate] [date] NULL,
	[SyncTime] [time](7) NULL,
	[flag] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_OTRoundoffSettings]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_OTRoundoffSettings](
	[OTRoundoffId] [int] IDENTITY(1,1) NOT NULL,
	[ShiftSettingId] [int] NOT NULL,
	[StartTime] [nvarchar](5) NOT NULL,
	[EndTime] [nvarchar](5) NOT NULL,
	[StartMins] [float] NOT NULL,
	[EndMins] [float] NOT NULL,
	[RoundedAs] [nvarchar](5) NOT NULL,
 CONSTRAINT [PK_TA_Tbl_OTRoundoffSettings] PRIMARY KEY CLUSTERED 
(
	[OTRoundoffId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_OtType]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_OtType](
	[OtTypeID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyID] [int] NULL,
	[OtType] [varchar](50) NULL,
	[OtValue] [nchar](10) NULL,
	[EmpID] [int] NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_OverTimeStatus]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_OverTimeStatus](
	[ExtraTime_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Process_RecID] [bigint] NULL,
	[Employee_Id] [int] NULL,
	[Date] [datetime] NULL,
	[HrsExtra] [varchar](5) NULL,
	[ExtraMins] [int] NULL,
	[OverTimeStatus] [varchar](50) NULL,
	[CompOffEligible] [bit] NULL,
	[OTEligible] [bit] NULL,
	[DateToExpired] [datetime] NULL,
	[NoOfDays] [numeric](18, 1) NULL,
	[RemainingDays] [numeric](18, 1) NULL,
	[CompOffSatus] [varchar](30) NULL,
	[LeaveApplicationId] [varchar](150) NULL,
	[ActHrsExtra] [varchar](6) NULL,
	[ActExtraMins] [int] NULL,
	[isdelete] [bit] NULL,
	[isRequest] [bit] NULL,
	[DaysWorked] [nvarchar](100) NULL,
	[InTime] [nvarchar](20) NULL,
	[OutTime] [nvarchar](20) NULL,
	[Reason] [nvarchar](250) NULL,
	[ApplicationDate] [datetime] NULL,
	[Modified_By] [int] NULL,
	[Modified_On] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[Remarks] [nvarchar](250) NULL,
	[Forward_By] [int] NULL,
	[Forward_Date] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Page]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Page](
	[pageId] [float] NOT NULL,
	[displayName] [nvarchar](100) NULL,
	[path] [nvarchar](200) NULL,
	[parentId] [int] NULL,
	[orderBy] [float] NULL,
	[ParentIdForSubMenu] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PageError]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PageError](
	[ErrorId] [bigint] IDENTITY(1,1) NOT NULL,
	[ErrorMsg] [varchar](max) NULL,
	[ErrorDetails] [varchar](max) NULL,
	[PageName] [varchar](150) NULL,
	[ProductName] [varchar](100) NULL,
	[ProductVersion] [varchar](25) NULL,
	[ClientName] [varchar](260) NULL,
	[TrackingPlatForm] [varchar](150) NULL,
	[ErrorTime] [datetime] NULL,
	[BugStatus] [varchar](15) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageMandatoryFlag]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_PageMandatoryFlag](
	[MandatoryChecking] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PageMandatoryFlagStandard]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PageMandatoryFlagStandard](
	[MandatoryChecking] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirect]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_PageRedirect](
	[ID] [float] NULL,
	[PageId] [int] NULL,
	[TableName] [varchar](100) NULL,
	[Page] [varchar](500) NULL,
	[PageFullPath] [varchar](500) NULL,
	[Module] [varchar](150) NULL,
	[Rows] [int] NULL,
	[Active] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirectStandard]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_PageRedirectStandard](
	[ID] [float] NULL,
	[PageId] [int] NULL,
	[TableName] [varchar](100) NULL,
	[Page] [varchar](500) NULL,
	[PageFullPath] [varchar](500) NULL,
	[Module] [varchar](150) NULL,
	[Rows] [int] NULL,
	[Active] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ParentIDs]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ParentIDs](
	[LevelID] [int] NOT NULL,
	[LevelName] [nvarchar](50) NULL,
	[pid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollConfigSetting]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PayrollConfigSetting](
	[payroll_SettingId] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NULL,
	[D_Allowance] [float] NULL,
	[HRA_Metro] [float] NULL,
	[HRA_NonMetro] [float] NULL,
	[MedicalAmount] [bigint] NULL,
	[MedicalPercent] [float] NULL,
	[CEAAmount] [bigint] NULL,
	[CEAPercentage] [float] NULL,
	[isMedicalflag] [bit] NULL,
	[isCEAflag] [bit] NULL,
	[LessTaxDeduction] [bigint] NULL,
	[isDeleted] [bit] NULL,
	[createdBy] [int] NULL,
	[createDate] [date] NULL,
	[modifyDate] [date] NULL,
 CONSTRAINT [PK__TA_Tbl_P__6737CBEA4A805D72] PRIMARY KEY CLUSTERED 
(
	[payroll_SettingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PayrollProcessDetails](
	[PayrollProcess_Id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[HrsWork] [nvarchar](25) NULL,
	[HrsOT] [nvarchar](25) NULL,
	[NormOT] [nvarchar](25) NULL,
	[OffOT] [nvarchar](25) NULL,
	[HolOT] [nvarchar](25) NULL,
	[EarlyOut] [nvarchar](25) NULL,
	[LateIn] [nvarchar](25) NULL,
	[WorkHrs] [nvarchar](25) NULL,
	[HrsLess] [nvarchar](25) NULL,
	[HrsExtra] [nvarchar](25) NULL,
	[LeaveDays] [numeric](18, 1) NULL,
	[AbsentDays] [numeric](18, 1) NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[Holidays] [numeric](18, 1) NULL,
	[LOPDays] [numeric](18, 1) NULL,
	[Emp_Id] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[TotalPermissionHours] [varchar](100) NULL,
	[WeekOffDays] [decimal](18, 1) NULL,
	[SPEC_NormOT1] [nvarchar](10) NULL,
	[SPEC_NormOT2] [nvarchar](10) NULL,
	[SPEC_OffOT1] [nvarchar](10) NULL,
	[SPEC_OffOT2] [nvarchar](10) NULL,
	[SPEC_HOLOT1] [nvarchar](10) NULL,
	[SPEC_HOLOT2] [nvarchar](10) NULL,
 CONSTRAINT [PK_TA_Tbl_PayrollProcessDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcess_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessLeaveDetails]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails](
	[PayrollProcessLeave_id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NOT NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[LeaveType_id] [int] NULL,
	[Leave_Count] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_PayrollProcessLeaveDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcessLeave_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PaySlip]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PaySlip](
	[EmployeeName] [nvarchar](30) NULL,
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Designation] [nvarchar](30) NULL,
	[Gender] [char](10) NULL,
	[PayslipMonth] [nvarchar](20) NULL,
	[Calender_Days] [int] NULL,
	[Present_Days] [int] NULL,
	[Absent_Days] [int] NULL,
	[Leave_Days] [int] NULL,
	[Weekly_OFF_Days] [int] NULL,
	[Holiday_Days] [int] NULL,
	[LossofPay_Days] [int] NULL,
	[TotalOTHrs] [nvarchar](10) NULL,
	[CostToCompany] [bigint] NULL,
	[BasicSalary] [bigint] NULL,
	[EarnedAmount] [bigint] NULL,
	[Dearness_Allowance] [bigint] NULL,
	[HouseRent_Allowance] [bigint] NULL,
	[Conveyance_Allowance] [bigint] NULL,
	[Medical_Allowance] [bigint] NULL,
	[Children_Education_Allowance] [bigint] NULL,
	[Tds_PolicyId] [int] NULL,
	[ProvidentFund] [bigint] NULL,
	[ESI] [bigint] NULL,
	[LoanCount] [int] NULL,
	[LoanDueAmount] [bigint] NULL,
	[TDSAmount] [bigint] NULL,
	[Professional_Tax] [bigint] NULL,
	[TotalAdditions] [bigint] NULL,
	[TotalDeduction] [bigint] NULL,
	[NetSalary] [bigint] NULL,
	[generateDate] [nvarchar](20) NULL,
	[OA] [bigint] NULL,
	[PayslipYear] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_PenaltyPercentage]    Script Date: 10-30-2024 09:39:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_PenaltyPercentage](
	[CompanyId] [int] NULL,
	[categoryID] [int] NULL,
	[StartTime1] [varchar](5) NULL,
	[EndTime1] [varchar](5) NULL,
	[StartTime2] [varchar](5) NULL,
	[EndTime2] [varchar](5) NULL,
	[StartTime3] [varchar](5) NULL,
	[EndTime3] [varchar](5) NULL,
	[Day1] [decimal](18, 2) NULL,
	[Day2] [decimal](18, 2) NULL,
	[Day3] [decimal](18, 2) NULL,
	[Day4] [decimal](18, 2) NULL,
	[Day5] [decimal](18, 2) NULL,
	[Day6] [decimal](18, 2) NULL,
	[Day7] [decimal](18, 2) NULL,
	[Day8] [decimal](18, 2) NULL,
	[Day9] [decimal](18, 2) NULL,
	[Day10] [decimal](18, 2) NULL,
	[Day11] [decimal](18, 2) NULL,
	[Day12] [decimal](18, 2) NULL,
	[StartTime1Mins]  AS (substring([StartTime1],(0),charindex(':',[StartTime1]))*(60)+substring([StartTime1],charindex(':',[StartTime1])+(1),len([StartTime1]))),
	[EndTime1Mins]  AS (substring([EndTime1],(0),charindex(':',[EndTime1]))*(60)+substring([EndTime1],charindex(':',[EndTime1])+(1),len([EndTime1]))),
	[StartTime2Mins]  AS (substring([StartTime2],(0),charindex(':',[StartTime2]))*(60)+substring([StartTime2],charindex(':',[StartTime2])+(1),len([StartTime2]))),
	[EndTime2Mins]  AS (substring([EndTime2],(0),charindex(':',[EndTime2]))*(60)+substring([EndTime2],charindex(':',[EndTime2])+(1),len([EndTime2]))),
	[StartTime3Mins]  AS (substring([StartTime3],(0),charindex(':',[StartTime3]))*(60)+substring([StartTime3],charindex(':',[StartTime3])+(1),len([StartTime3]))),
	[EndTime3Mins]  AS (substring([EndTime3],(0),charindex(':',[EndTime3]))*(60)+substring([EndTime3],charindex(':',[EndTime3])+(1),len([EndTime3])))
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocation](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL,
	[ShiftAllocationID] [bigint] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationbck]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocationbck](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Permission]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Permission](
	[Permission_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [int] NOT NULL,
	[Permission_AppliedDate] [datetime] NOT NULL,
	[Permission_Date] [datetime] NOT NULL,
	[Permission_Type] [nvarchar](50) NULL,
	[Permission_FromTime] [datetime] NOT NULL,
	[Permission_ToTime] [datetime] NOT NULL,
	[Permission_Reason] [nvarchar](1000) NULL,
	[Permission_Status] [nvarchar](50) NULL,
	[Emp_Id_Sanction] [int] NULL,
	[Remarks] [nvarchar](1000) NULL,
	[IsDeleted] [bit] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[UnPlanned] [int] NULL,
	[CCMail] [varchar](3000) NULL,
	[Permission_Hours] [varchar](5) NULL,
	[No_Of_Hours] [nvarchar](10) NULL,
 CONSTRAINT [PK_TA_Tbl_Permission] PRIMARY KEY CLUSTERED 
(
	[Permission_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermissionConversation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PermissionConversation](
	[PermissionConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[PermissionId] [bigint] NOT NULL,
	[CommentsBy] [int] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_PermissionConversation] PRIMARY KEY CLUSTERED 
(
	[PermissionConversationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PF_ESIDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PF_ESIDetails](
	[PFESI_Id] [int] IDENTITY(1,1) NOT NULL,
	[PFESI_PolicyName] [varchar](50) NULL,
	[CompanyId] [int] NULL,
	[EmployeeCategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](5) NULL,
	[PF_Employer] [float] NULL,
	[PF_Employee] [float] NULL,
	[ESI_Employer] [float] NULL,
	[ESI_Employee] [float] NULL,
	[Created_Date] [date] NULL,
	[Creadted_BY] [int] NULL,
	[Modifi_Date] [date] NULL,
	[isDeleted] [bit] NULL,
 CONSTRAINT [PK__TA_Tbl_P__F0B6010EBD3C56BD] PRIMARY KEY CLUSTERED 
(
	[PFESI_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_PolicyConfiguration]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_PolicyConfiguration](
	[Pol_Config_id] [int] IDENTITY(1,1) NOT NULL,
	[Daily_Rrd] [bit] NULL,
	[Daily_Hrs] [int] NULL,
	[Day_Rqrd] [bit] NULL,
	[Day_Value] [int] NULL,
	[Weekly_Rqrd] [bit] NULL,
	[Weekly_Hrs] [int] NULL,
	[Quarterly_Rqrd] [bit] NULL,
	[Quarterly_Hrs] [int] NULL,
	[Cont_Absent] [bit] NULL,
	[Cont_Value] [int] NULL,
	[ApproFolderPath] [varchar](max) NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
	[CreatedBy] [int] NULL,
	[ModifiedBy] [int] NULL,
	[EmpAPI1] [varchar](max) NULL,
	[EmpAPI2] [varchar](max) NULL,
	[EmpAPI3] [varchar](max) NULL,
	[BlockAPI] [varchar](max) NULL,
	[LogDownloadAPI] [varchar](max) NULL,
	[userName] [varchar](50) NULL,
	[password] [varchar](50) NULL,
	[DataProcessDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Preferences]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Preferences](
	[isDomain] [int] NULL,
	[DomainName] [nvarchar](500) NULL,
	[DomainAdminUserName] [nvarchar](max) NULL,
	[DomainAdminPassword] [nvarchar](max) NULL,
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_PrevPermissionDetails_EastMan]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_PrevPermissionDetails_EastMan](
	[AutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[Cur_Perm_ID] [bigint] NULL,
	[Prev_Perm_ID] [bigint] NULL,
	[Timestamp] [datetime] NULL,
	[Prev_Perm_date] [varchar](20) NULL,
	[Prev_Perm_ShiftTime] [varchar](20) NULL,
	[Prev_Perm_InTime] [varchar](20) NULL,
	[Prev_Perm_LateHours] [varchar](20) NULL,
	[Prev_Perm_Reason] [varchar](500) NULL,
	[Prev_Perm_ReceivedDate] [varchar](20) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ProcessedDataTrigger]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ProcessedDataTrigger](
	[ReporcessID] [int] IDENTITY(1,1) NOT NULL,
	[RecordCount] [int] NULL,
	[ModifyFromDate] [datetime] NULL,
	[ModifyToDate] [datetime] NULL,
	[EmployeeID] [int] NULL,
	[ModifyType] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_ProfSlab]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_ProfSlab](
	[ProfId] [int] IDENTITY(1,1) NOT NULL,
	[Prof_SlabName] [nchar](20) NULL,
	[Prof_RangeFrom] [bigint] NULL,
	[Prof_RangeTO] [bigint] NULL,
	[Prof_Amount] [nvarchar](50) NULL,
	[Tax_PolicyId] [int] NULL,
	[IsPercentage] [bit] NULL,
 CONSTRAINT [PK__Ta_Tbl_P__0A883611B6B24E93] PRIMARY KEY CLUSTERED 
(
	[ProfId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Project]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Project](
	[Project_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Project_Name] [varchar](250) NULL,
	[Project_Code] [varchar](15) NULL,
	[Client_Name] [varchar](150) NULL,
	[Project_Description] [varchar](500) NULL,
	[Project_StartTime] [datetime] NULL,
	[Project_EndTime] [datetime] NULL,
	[Project_Status] [varchar](15) NULL,
	[IsDeleted] [bit] NULL,
	[Created_By] [bigint] NULL,
	[Created_On] [datetime] NULL,
	[Modified_By] [bigint] NULL,
	[Modified_On] [datetime] NULL,
	[LevelID] [int] NULL,
	[Mandays] [int] NULL,
	[ManHours] [int] NULL,
 CONSTRAINT [PK__TA_Tbl_P__1CB92E03DA08B5D4] PRIMARY KEY CLUSTERED 
(
	[Project_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_ProjectTaskList]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_ProjectTaskList](
	[ProjectID] [bigint] NOT NULL,
	[TaskID] [int] IDENTITY(1,1) NOT NULL,
	[TaskName] [nvarchar](max) NULL,
	[TaskHours] [varchar](25) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ProjectTerminals]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ProjectTerminals](
	[Project_Terminal_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Project_Id] [bigint] NOT NULL,
	[Terminal_id] [bigint] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_PunchtypeRemarks]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_PunchtypeRemarks](
	[Remarks_id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_Type] [nvarchar](10) NULL,
	[PunchType] [nvarchar](50) NULL,
	[Punchtype_Remarks] [nvarchar](max) NULL,
	[Timestamp] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_PunchTypes]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_PunchTypes](
	[PunchType_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_Id] [int] NOT NULL,
	[PunchType] [nvarchar](25) NOT NULL,
	[Value] [nvarchar](25) NOT NULL,
	[Isdeleted] [bit] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Addedby] [char](1) NULL,
	[Flag] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_INOUT] PRIMARY KEY CLUSTERED 
(
	[PunchType_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_ReasonForNonProcessedData]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_ReasonForNonProcessedData](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ReasonId] [int] NULL,
	[Reasons] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Religion]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Religion](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Description] [nvarchar](250) NULL,
	[IsDeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_Religion] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Results]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Results](
	[CardNo] [nvarchar](10) NULL,
	[EmpName] [nvarchar](100) NULL,
	[Department] [nvarchar](50) NULL,
	[SwipeData] [smalldatetime] NULL,
	[Swipes] [ntext] NULL,
	[SwipesCount] [nvarchar](50) NULL,
	[TotalHrs] [nvarchar](50) NULL,
	[d1] [nvarchar](20) NULL,
	[d2] [nvarchar](20) NULL,
	[d3] [nvarchar](20) NULL,
	[d4] [nvarchar](20) NULL,
	[d5] [nvarchar](20) NULL,
	[d6] [nvarchar](20) NULL,
	[d7] [nvarchar](20) NULL,
	[d8] [nvarchar](20) NULL,
	[d9] [nvarchar](20) NULL,
	[d10] [nvarchar](20) NULL,
	[d11] [nvarchar](20) NULL,
	[d12] [nvarchar](20) NULL,
	[d13] [nvarchar](20) NULL,
	[d14] [nvarchar](20) NULL,
	[d15] [nvarchar](20) NULL,
	[d16] [nvarchar](20) NULL,
	[d17] [nvarchar](20) NULL,
	[d18] [nvarchar](20) NULL,
	[d19] [nvarchar](20) NULL,
	[d20] [nvarchar](20) NULL,
	[d21] [nvarchar](20) NULL,
	[d22] [nvarchar](20) NULL,
	[d23] [nvarchar](20) NULL,
	[d24] [nvarchar](20) NULL,
	[d25] [nvarchar](20) NULL,
	[d26] [nvarchar](20) NULL,
	[d27] [nvarchar](20) NULL,
	[d28] [nvarchar](20) NULL,
	[d29] [nvarchar](20) NULL,
	[d30] [nvarchar](20) NULL,
	[d31] [nvarchar](20) NULL,
	[MusterComplete] [tinyint] NULL,
	[Emp_Location] [nvarchar](20) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_RouteMaster]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_RouteMaster](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[VehicleID] [int] NULL,
	[Route_Name] [nvarchar](50) NOT NULL,
	[Route_Description] [nvarchar](250) NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_ID] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[IsMapped] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_RouteMaster] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_ShiftAdd_Location]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_ShiftAdd_Location](
	[Shift_Lcoation_Id] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LocationId] [int] NULL,
	[ShiftDate] [datetime] NULL,
	[CreatedBy] [int] NULL,
	[CreatedOn] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedOn] [datetime] NULL,
	[months]  AS (datepart(month,[ShiftDate])),
 CONSTRAINT [PK_TA_tbl_ShiftAdd_Location] PRIMARY KEY CLUSTERED 
(
	[Shift_Lcoation_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftExchange]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ShiftExchange](
	[ShiftExchange_id] [bigint] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NOT NULL,
	[Date] [datetime] NOT NULL,
	[Employee1_Id] [int] NOT NULL,
	[Employee1_ActualShift] [int] NOT NULL,
	[Employee2_Id] [int] NOT NULL,
	[Employee2_ActualShift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[YearSettings_Id] [int] NULL,
	[TimeStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_ShiftExchange] PRIMARY KEY CLUSTERED 
(
	[ShiftExchange_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftPattern]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ShiftPattern](
	[ShiftPattern_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[Pattern_Name] [nvarchar](50) NOT NULL,
	[Shift_days] [int] NOT NULL,
	[Day1_Shift] [int] NULL,
	[Day2_shift] [int] NULL,
	[Day3_Shift] [int] NULL,
	[Day4_Shift] [int] NULL,
	[Day5_Shift] [int] NULL,
	[Day6_Shift] [int] NULL,
	[Day7_Shift] [int] NULL,
	[Day8_Shift] [int] NULL,
	[Day9_Shift] [int] NULL,
	[Day10_Shift] [int] NULL,
	[Day11_Shift] [int] NULL,
	[Day12_Shift] [int] NULL,
	[Day13_Shift] [int] NULL,
	[Day14_Shift] [int] NULL,
	[Day15_Shift] [int] NULL,
	[Day16_Shift] [int] NULL,
	[Day17_Shift] [int] NULL,
	[Day18_Shift] [int] NULL,
	[Day19_Shift] [int] NULL,
	[Day20_Shift] [int] NULL,
	[Day21_Shift] [int] NULL,
	[Day22_Shift] [int] NULL,
	[Day23_Shift] [int] NULL,
	[Day24_Shift] [int] NULL,
	[Day25_Shift] [int] NULL,
	[Day26_Shift] [int] NULL,
	[Day27_Shift] [int] NULL,
	[Day28_Shift] [int] NULL,
	[Day29_Shift] [int] NULL,
	[Day30_Shift] [int] NULL,
	[Day31_Shift] [int] NULL,
	[Emp_Id] [int] NULL,
	[Isdeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl] PRIMARY KEY CLUSTERED 
(
	[ShiftPattern_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftRequisition]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ShiftRequisition](
	[ShiftRequisitionID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeID] [nvarchar](50) NULL,
	[RequisitionDate] [datetime] NULL,
	[Status] [nvarchar](50) NULL,
	[Timestamp] [datetime] NULL,
	[EMP_ID] [nvarchar](50) NULL,
	[DAY1] [nvarchar](50) NULL,
	[DAY2] [nvarchar](50) NULL,
	[DAY3] [nvarchar](50) NULL,
	[DAY4] [nvarchar](50) NULL,
	[DAY5] [nvarchar](50) NULL,
	[DAY6] [nvarchar](50) NULL,
	[DAY7] [nvarchar](50) NULL,
	[DAY8] [nvarchar](50) NULL,
	[DAY9] [nvarchar](50) NULL,
	[DAY10] [nvarchar](50) NULL,
	[DAY11] [nvarchar](50) NULL,
	[DAY12] [nvarchar](50) NULL,
	[DAY13] [nvarchar](50) NULL,
	[DAY14] [nvarchar](50) NULL,
	[DAY15] [nvarchar](50) NULL,
	[DAY16] [nvarchar](50) NULL,
	[DAY17] [nvarchar](50) NULL,
	[DAY18] [nvarchar](50) NULL,
	[DAY19] [nvarchar](50) NULL,
	[DAY20] [nvarchar](50) NULL,
	[DAY21] [nvarchar](50) NULL,
	[DAY22] [nvarchar](50) NULL,
	[DAY23] [nvarchar](50) NULL,
	[DAY24] [nvarchar](50) NULL,
	[DAY25] [nvarchar](50) NULL,
	[DAY26] [nvarchar](50) NULL,
	[DAY27] [nvarchar](50) NULL,
	[DAY28] [nvarchar](50) NULL,
	[DAY29] [nvarchar](50) NULL,
	[DAY30] [nvarchar](50) NULL,
	[DAY31] [nvarchar](50) NULL,
	[CompanyID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftRoaster]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ShiftRoaster](
	[ShiftRoaster_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[ShiftRoaster_Name] [nvarchar](50) NULL,
	[NumberOfPatterns] [int] NOT NULL,
	[Pattern1] [int] NULL,
	[Pattern2] [int] NULL,
	[Pattern3] [int] NULL,
	[Pattern4] [int] NULL,
	[Pattern5] [int] NULL,
	[Pattern6] [int] NULL,
	[Pattern7] [int] NULL,
	[Pattern8] [int] NULL,
	[Pattern9] [int] NULL,
	[Pattern10] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_ShiftRoaster] PRIMARY KEY CLUSTERED 
(
	[ShiftRoaster_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftSettings]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_ShiftSettings](
	[ShiftSettingId] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NULL,
	[MaxHoursBeforeShift] [nvarchar](50) NULL,
	[MaxHoursAfterShift] [nvarchar](50) NULL,
	[ShiftBreak] [nvarchar](50) NULL,
	[ShiftMaxBreakHours] [nvarchar](50) NULL,
	[MonthlyWorkingHours] [nvarchar](50) NULL,
	[WeeklyWorkingHours] [nvarchar](50) NULL,
	[EmpID] [nvarchar](50) NULL,
	[HolidayOT] [decimal](18, 2) NULL,
	[WeekOffOT] [decimal](18, 2) NULL,
	[otOption] [nvarchar](50) NULL,
	[DefaultMonthClosureDate] [datetime] NULL,
	[IsFlexible] [bit] NULL,
	[FlexibleFlag] [tinyint] NULL,
	[OTRoundoffEnable] [bit] NULL,
	[FullDayAttendanceHrs] [nvarchar](5) NULL,
	[HalfDayAttendanceHrs] [nvarchar](5) NULL,
	[HalfDayAttendance] [bit] NULL,
	[FullDayAttendance] [bit] NULL,
	[DefaultLunchHours] [nvarchar](5) NULL,
	[MaxLunchHours] [nvarchar](5) NULL,
	[WeeklyOffStartHours] [nvarchar](5) NULL,
	[IgnoreDuplicatePunch] [bit] NULL,
	[PunchInterval] [nvarchar](5) NULL,
	[AfterShiftTime] [bit] NULL,
	[BeforeShiftTime] [bit] NULL,
	[DefinedWorkhrs] [bit] NULL,
	[NoOfSuccessiveDaysInYear] [int] NULL,
	[CompensationValitityDays] [int] NULL,
	[VaildityCompOffDays] [int] NULL,
	[HalfDayCompOff] [varchar](5) NULL,
	[FullDayCompOff] [varchar](50) NULL,
	[LateEntry] [bit] NULL,
	[EarlyEntry] [bit] NULL,
	[EarlyExit] [bit] NULL,
	[LateExit] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[TimeStamp1] [datetime] NULL,
	[IsLunchDeduction] [bit] NULL,
	[LunchDeductionHours] [nvarchar](10) NULL,
	[MaxWorkPlaceInHours] [nvarchar](5) NULL,
	[Flexi_AfterShiftTime] [bit] NULL,
	[Flexi_BeforeShiftTime] [bit] NULL,
	[Flexi_DefinedWorkhrs] [bit] NULL,
	[MaxHoursBeforeShift_24HrsShift] [nvarchar](50) NULL,
	[WeeklyOffStartHours_24HrsShift] [nvarchar](50) NULL,
	[CumulativeWeekStartDay] [nvarchar](10) NULL,
	[CumulativeWeekEndDay] [nvarchar](10) NULL,
	[MonthStartDay] [int] NULL,
	[MonthEndDay] [int] NULL,
	[isRequestingforCompOff] [bit] NULL,
	[FirstAndLast] [bit] NULL,
	[Carry_Forward_COff_Year] [int] NULL,
	[MapKey] [varchar](max) NULL,
	[SpecialOverTime1] [int] NULL,
	[SpecialOverTime2] [int] NULL,
	[LateMinsPerDay] [int] NOT NULL,
	[LateDaysPerMonth] [int] NOT NULL,
	[EarlyExitMinsPerDay] [int] NULL,
	[EarlyExitDaysPerMonth] [int] NULL,
	[EnableAbsent] [int] NOT NULL,
	[isLOPDisplayed] [bit] NULL,
	[isRemindRrd_Pas_Vis] [bit] NULL,
	[reminderDays] [int] NULL,
	[mon] [int] NULL,
	[tues] [int] NULL,
	[wed] [int] NULL,
	[thurs] [int] NULL,
	[fri] [int] NULL,
	[satur] [int] NULL,
	[sun] [int] NULL,
	[NightShiftEndTime_Autoshift] [nvarchar](10) NULL,
 CONSTRAINT [PK_TA_Tbl_ShiftSettings] PRIMARY KEY CLUSTERED 
(
	[ShiftSettingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSGateway]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_SMSGateway](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ServiceUrl] [varchar](max) NULL,
	[DestinationKey] [varchar](100) NULL,
	[MessageKey] [varchar](100) NULL,
	[TimeStamp] [datetime] NULL,
	[PhNo] [varchar](20) NULL,
	[EmployeeID] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogChild]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_SMSLogChild](
	[logchildid] [int] IDENTITY(1,1) NOT NULL,
	[logid] [int] NULL,
	[Employeesids] [varchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_SMSLogDetails](
	[logid] [int] IDENTITY(1,1) NOT NULL,
	[TemplateID] [int] NULL,
	[TriggeredDate] [datetime] NULL,
	[Receivers] [varchar](50) NULL,
	[NextTriggeringTime] [datetime] NULL,
	[Status] [bit] NULL,
	[StatusMessage] [varchar](max) NULL,
	[ShiftId] [int] NULL,
	[Message] [varchar](max) NULL,
	[TriggeredTimings] [datetime] NULL,
 CONSTRAINT [PK__TA_Tbl_S__7838F2653B5D1C78] PRIMARY KEY CLUSTERED 
(
	[logid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSReceivers]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_SMSReceivers](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Usergroupid] [int] NULL,
	[TemplateId] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[CreatedBy] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTags]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_SMSTags](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Tags] [varchar](50) NULL,
	[TemplateName] [varchar](50) NULL,
	[Timestamp] [datetime] NULL,
 CONSTRAINT [PK__Ta_Tbl_S__3213E83FEB774D5C] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplateFilters]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_SMSTemplateFilters](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[TemplateId] [int] NULL,
	[Filters] [varchar](max) NULL,
	[ReportType] [varchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplates]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_SMSTemplates](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[TemplateName] [varchar](50) NULL,
	[Message] [varchar](max) NULL,
	[Status] [bit] NULL,
	[LastModified] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[First_TriggeringTime] [varchar](5) NULL,
	[Second_TriggeringTime] [varchar](5) NULL,
	[ToEmployee] [bit] NULL,
	[LessHrsLimitation] [varchar](5) NULL,
	[Continue_AbsentDays] [int] NULL,
	[Tags] [varchar](max) NULL,
 CONSTRAINT [PK__Ta_Tbl_S__3213E83F141C6E29] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_specialOvertimeDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_specialOvertimeDetails](
	[Employee_code_id] [varchar](50) NULL,
	[Date] [datetime] NULL,
	[Modified_Spec_NormOTMins1] [int] NULL,
	[Modified_Spec_NormOTMins2] [int] NULL,
	[Modified_Spec_OffOTMins1] [int] NULL,
	[Modified_Spec_OffOTMins2] [int] NULL,
	[Modified_Spec_HolOTMins1] [int] NULL,
	[Modified_Spec_HolOTMins2] [int] NULL,
	[Modified_Spec_NormOTHrs1] [varchar](10) NULL,
	[Modified_Spec_NormOTHrs2] [varchar](10) NULL,
	[Modified_Spec_OffOTHrs1] [varchar](10) NULL,
	[Modified_Spec_OffOTHrs2] [varchar](10) NULL,
	[Modified_Spec_HolOTHrs1] [varchar](10) NULL,
	[Modified_Spec_HolOTHrs2] [varchar](10) NULL,
	[Inserted_By] [bigint] NULL,
	[Inserted_Date] [datetime] NULL,
	[Modified_By] [bigint] NULL,
	[Modified_Date] [datetime] NULL,
	[Rec_ID] [bigint] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_TaskProgressDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_TaskProgressDetails](
	[TaskDetailID] [bigint] IDENTITY(1,1) NOT NULL,
	[TaskID] [int] NULL,
	[ProjectID] [bigint] NULL,
	[ShiftDate] [datetime] NULL,
	[TaskHours] [varchar](10) NULL,
	[TaskDescription] [varchar](5000) NULL,
	[SpentHours] [varchar](10) NULL,
	[TaskSubmittedDate] [datetime] NULL,
	[TaskSubmittedBy] [bigint] NULL,
	[TaskModifiedDate] [datetime] NULL,
	[TaskModifiedBy] [bigint] NULL,
	[ModificationReason] [varchar](5000) NULL,
	[ApprovedHours] [varchar](10) NULL,
	[ApprovedBy1] [bigint] NULL,
	[ApprovedDate1] [datetime] NULL,
	[ApprovedBy2] [bigint] NULL,
	[ApprovedDate2] [datetime] NULL,
	[Status] [varchar](10) NULL,
	[isSubmitted_Completely] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_taskprogressStatus]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_taskprogressStatus](
	[ProgressAutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[TaskDetailID] [bigint] NULL,
	[ApprovedHours] [varchar](10) NULL,
	[ApprovedBy] [bigint] NULL,
	[ApprovedDate] [datetime] NULL,
	[Comments] [varchar](500) NULL,
	[Status] [varchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TaxMasterDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TaxMasterDetails](
	[TaxPolicy_Id] [int] IDENTITY(1,1) NOT NULL,
	[TaxPolicyName] [nvarchar](50) NULL,
	[CompanyId] [int] NULL,
	[EmployeeCategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](10) NULL,
	[isDeleted] [bit] NULL,
	[Created_By] [int] NULL,
	[Created_DateTime] [date] NULL,
	[Modify_DateTime] [date] NULL,
	[isTdsflag] [bit] NULL,
	[isProfessflag] [bit] NULL,
	[TdsSlabCount] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[TaxPolicy_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TDSSlab]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TDSSlab](
	[TdsId] [int] IDENTITY(1,1) NOT NULL,
	[Tds_SlabNo] [nchar](20) NULL,
	[Tds_RangeFrom] [bigint] NULL,
	[Tds_RangeTo] [bigint] NULL,
	[Tds_Percentage] [bigint] NULL,
	[Tds_CessPercentage] [float] NULL,
	[Tax_PolicyId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[TdsId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_Id] [int] NULL,
	[Temp_WeeklyOff_Levels] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Temp_WeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempGroupPolicyAllocation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TempGroupPolicyAllocation](
	[EmpID] [int] NOT NULL,
	[EmployeeId] [nvarchar](50) NOT NULL,
	[EmployeeName] [nvarchar](50) NOT NULL,
	[LoginEmployeeId] [int] NOT NULL,
	[DateOfJoining] [datetime] NOT NULL,
	[LevelID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempInsertEmployee]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TempInsertEmployee](
	[employee_code] [bigint] NOT NULL,
	[first_name] [nvarchar](50) NULL,
	[last_name] [nvarchar](50) NULL,
	[birth_date] [datetime] NULL,
	[local_addr1] [nvarchar](50) NULL,
	[local_addr2] [nvarchar](50) NULL,
	[local_addr3] [nvarchar](50) NULL,
	[join_date] [datetime] NULL,
	[section_name] [nvarchar](50) NULL,
	[desg_name] [nvarchar](50) NULL,
	[category_name] [nvarchar](50) NULL,
	[basic] [numeric](16, 3) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_Id] [int] NULL,
	[LevelId] [int] NULL,
 CONSTRAINT [PK_Ta_Tbl_Temporary_WeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocationbkup]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocationbkup](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempPayrollProcessDetails]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails](
	[PayrollProcess_Id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[HrsWork] [nvarchar](25) NULL,
	[HrsOT] [nvarchar](25) NULL,
	[NormOT] [nvarchar](25) NULL,
	[OffOT] [nvarchar](25) NULL,
	[HolOT] [nvarchar](25) NULL,
	[EarlyOut] [nvarchar](25) NULL,
	[LateIn] [nvarchar](25) NULL,
	[WorkHrs] [nvarchar](25) NULL,
	[HrsLess] [nvarchar](25) NULL,
	[HrsExtra] [nvarchar](25) NULL,
	[LeaveDays] [numeric](18, 1) NULL,
	[AbsentDays] [numeric](18, 1) NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[Holidays] [numeric](18, 1) NULL,
	[LOPDays] [numeric](18, 1) NULL,
	[Emp_Id] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[TotalPermissionHours] [varchar](100) NULL,
	[WeekOffDays] [decimal](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_TempPayrollProcessDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcess_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempShiftAllocation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TempShiftAllocation](
	[EmpID] [int] NOT NULL,
	[EmployeeId] [nvarchar](50) NOT NULL,
	[EmployeeName] [nvarchar](50) NOT NULL,
	[LoginEmployeeId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempUpdateEmployee]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TempUpdateEmployee](
	[employee_code] [bigint] NOT NULL,
	[first_name] [nvarchar](50) NULL,
	[last_name] [nvarchar](50) NULL,
	[birth_date] [datetime] NULL,
	[local_addr1] [nvarchar](50) NULL,
	[local_addr2] [nvarchar](50) NULL,
	[local_addr3] [nvarchar](50) NULL,
	[join_date] [datetime] NULL,
	[section_name] [nvarchar](50) NULL,
	[desg_name] [nvarchar](50) NULL,
	[category_name] [nvarchar](50) NULL,
	[basic] [numeric](16, 3) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemWeekday]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TemWeekday](
	[TempWeekday_Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_FromDate] [datetime] NOT NULL,
	[TempWeekday_ToDate] [datetime] NOT NULL,
	[ClosingTime] [nvarchar](50) NULL,
	[Reason] [nvarchar](255) NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[ShiftId] [nvarchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_TemWeekday] PRIMARY KEY CLUSTERED 
(
	[TempWeekday_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalBrand]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TerminalBrand](
	[BrandID] [int] IDENTITY(1,1) NOT NULL,
	[DisplayName] [nvarchar](500) NULL,
	[KeyValue] [varchar](500) NULL,
 CONSTRAINT [PK_TA_Tbl_TerminalBrand] PRIMARY KEY CLUSTERED 
(
	[BrandID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_TerminalDatatype]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_TerminalDatatype](
	[TerminalDatatype_ID] [int] IDENTITY(1,1) NOT NULL,
	[Raw_Data_Format] [nvarchar](25) NOT NULL,
	[FileType] [nvarchar](15) NOT NULL,
	[File_SourcePath] [nvarchar](2000) NULL,
	[File_BackupPath] [nvarchar](2000) NULL,
	[File_BackupType] [nvarchar](10) NULL,
	[Delimiter_NoOfFields] [int] NULL,
	[Delimiter_Delimiter] [char](5) NULL,
	[Delimiter_StringEnclosedBy] [nvarchar](5) NULL,
	[Delimiter_ReaderNo] [nvarchar](10) NULL,
	[Delimiter_CardNo] [nvarchar](10) NULL,
	[Delimiter_DateTimeBit] [bit] NULL,
	[Delimiter_Date] [nvarchar](10) NULL,
	[Delimiter_Time] [nvarchar](10) NULL,
	[Delimiter_DateTime] [nvarchar](10) NULL,
	[Delimiter_Type] [nvarchar](10) NULL,
	[Delimiter_TransactionIdentifier] [nvarchar](10) NULL,
	[FixedLength_ReaderNoFrom] [int] NULL,
	[FixedLength_ReaderNoTo] [int] NULL,
	[FixedLength_CardNoFrom] [int] NULL,
	[FixedLength_CardNoTo] [int] NULL,
	[FixedLength_DateTimeBit] [bit] NULL,
	[FixedLength_DateFrom] [int] NULL,
	[FixedLength_DateTo] [int] NULL,
	[FixedLength_TimeFrom] [int] NULL,
	[FixedLength_TimeTo] [int] NULL,
	[FixedLength_DateTimeFrom] [int] NULL,
	[FixedLength_DateTimeTo] [int] NULL,
	[FixedLength_TypeFrom] [int] NULL,
	[FixedLength_TypeTo] [int] NULL,
	[FixedLength_TransactionIdentifierFrom] [int] NULL,
	[FixedLength_TransactionIdentifierTo] [int] NULL,
	[ConnectionString] [nvarchar](2000) NULL,
	[TableName] [nvarchar](50) NULL,
	[MDB_ReaderNo] [nvarchar](25) NULL,
	[MDB_CardNo] [nvarchar](25) NULL,
	[MDB_DateTimeBit] [bit] NULL,
	[MDB_Date] [nvarchar](25) NULL,
	[MDB_Time] [nvarchar](25) NULL,
	[MDB_DateTime] [nvarchar](25) NULL,
	[MDB_Type] [nvarchar](25) NULL,
	[MDB_TransactionIdentifier] [nvarchar](25) NULL,
	[RDBMS_ReaderNo] [nvarchar](25) NULL,
	[RDBMS_CardNo] [nvarchar](25) NULL,
	[RDBMS_DateTimeBit] [bit] NULL,
	[RDBMS_Date] [nvarchar](25) NULL,
	[RDBMS_Time] [nvarchar](25) NULL,
	[RDBMS_DateTime] [nvarchar](25) NULL,
	[RDBMS_Type] [nvarchar](25) NULL,
	[RDBMS_TransactionIdentifier] [nvarchar](25) NULL,
	[RDBMS_MDB_Flag] [nvarchar](25) NULL,
	[IsEmployeeId] [bit] NULL,
	[DateTimeFormat] [nvarchar](40) NULL,
	[DateFormat] [nvarchar](15) NULL,
	[TimeFormat] [nvarchar](15) NULL,
	[IsEncrypted] [bit] NULL,
	[TransactionIdentifierBit] [bit] NULL,
	[TransactionIdentifierValue] [nvarchar](50) NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[BrandId] [int] NULL,
	[IsFreeScan] [int] NULL,
	[ISUTCTime] [int] NULL,
 CONSTRAINT [PK_TA_tbl_TerminalDatatype] PRIMARY KEY CLUSTERED 
(
	[TerminalDatatype_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalMapping]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TerminalMapping](
	[TerMap_Id] [int] IDENTITY(1,1) NOT NULL,
	[EntranceName] [nvarchar](50) NOT NULL,
	[EntranceDescription] [nvarchar](50) NULL,
	[InTerminalID] [int] NULL,
	[OutTerminalID] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_TerminalMapping] PRIMARY KEY CLUSTERED 
(
	[TerMap_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_TimeZones]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_TimeZones](
	[TimeZoneID] [int] NOT NULL,
	[TimeZoneName] [varchar](100) NOT NULL,
	[TimeZoneDesc] [varchar](10) NULL,
	[HoursToBeAdded] [int] NOT NULL,
	[MinToBeAdded] [int] NOT NULL,
 CONSTRAINT [PK_Ta_tbl_TimeZones] PRIMARY KEY CLUSTERED 
(
	[TimeZoneID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_TimeZonesList]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_TimeZonesList](
	[TimezoneID] [int] IDENTITY(1,1) NOT NULL,
	[CountryCode] [nvarchar](10) NULL,
	[TimezoneName] [nvarchar](max) NULL,
	[TimezoneDesc] [nvarchar](max) NULL,
	[TimeZoneValue] [nvarchar](max) NULL,
	[HoursToBeAdded] [int] NULL,
	[MinToBeAdded] [int] NULL,
	[ServerDefault] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Title]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Title](
	[TitleId] [int] IDENTITY(1,1) NOT NULL,
	[TitleName] [nvarchar](50) NOT NULL,
	[TitleDescription] [nvarchar](250) NULL,
	[LevelID] [int] NULL,
	[LeavePolicyID] [int] NULL,
	[GradeID] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[Time_Stamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_Title] PRIMARY KEY CLUSTERED 
(
	[TitleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_TitleMapping]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_TitleMapping](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[Department_Id] [int] NOT NULL,
	[Section_Id] [int] NOT NULL,
	[TitleId] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_TotalBreakHours]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ta_tbl_TotalBreakHours](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ShiftDate] [datetime] NULL,
	[Employee_Code_Id] [nvarchar](10) NOT NULL,
	[TotalBreakmin] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Trace]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_Tbl_Trace](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[PageName] [nvarchar](200) NULL,
	[ErrDescription] [nvarchar](2000) NULL,
	[DateOfError] [datetime] NULL,
 CONSTRAINT [PK_Ta_Tbl_Trace] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ta_tbl_Transfer]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ta_tbl_Transfer](
	[TrnsfrID] [bigint] IDENTITY(1,1) NOT NULL,
	[Emp_AutoID] [bigint] NULL,
	[Trnsfr_frm] [int] NULL,
	[Trnsfr_To] [int] NULL,
	[Trnsfr_EtyDteTme] [datetime] NULL,
	[Trnsfr_Dte] [datetime] NULL,
	[Etry_RsdBy] [int] NULL,
	[NwDsgtonID] [int] NULL,
	[NwReprtngTo] [int] NULL,
	[NwApprvlAuthrty] [int] NULL,
	[Remarks] [varchar](500) NULL,
	[IsImprtd] [int] NULL,
	[Trnsfr_status] [varchar](10) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Transportation](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[VehicleNo] [int] NOT NULL,
	[RouteName] [nvarchar](50) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Mapping]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Transportation_Mapping](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[VehicleId] [int] NOT NULL,
	[RouteId] [int] NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Route]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Transportation_Route](
	[RouteId] [int] IDENTITY(1,1) NOT NULL,
	[VehicleId] [int] NULL,
	[RouteName] [nvarchar](20) NULL,
	[RouteDescription] [nvarchar](250) NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Vehicle]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Transportation_Vehicle](
	[VehicleId] [int] IDENTITY(1,1) NOT NULL,
	[VehicleNo] [nvarchar](20) NOT NULL,
	[VehicleDescription] [nvarchar](250) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Emp_Id] [int] NULL,
	[Time_stamp] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_Transportation_Vehicle] PRIMARY KEY CLUSTERED 
(
	[VehicleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Type]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Type](
	[TypeId] [bigint] IDENTITY(1,1) NOT NULL,
	[TypeName] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[EmpId] [bigint] NULL,
	[IsFlexible] [bit] NULL,
	[Isdisply_MyProf] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Usergroup]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Usergroup](
	[groupId] [int] IDENTITY(1,1) NOT NULL,
	[groupName] [nvarchar](50) NULL,
	[IndividualUsers] [bit] NULL,
	[hasSpecialRights] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[isDeleted] [bit] NULL,
	[Emp_Id] [nchar](10) NULL,
	[ReportsBasedOn] [bit] NULL,
	[AllowLeaveApprovalPastEntry] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_userRights]    Script Date: 10-30-2024 09:39:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_userRights](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[groupName] [nvarchar](50) NULL,
	[groupId] [int] NULL,
	[pageId] [float] NULL,
	[pageGroupId] [int] NULL,
	[addPrv] [bit] NULL,
	[modifyPrv] [bit] NULL,
	[deletePrv] [bit] NULL,
	[viewPrv] [bit] NULL,
	[isDeleted] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[employeeId] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_UTCEmployeeLoginDetails]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_UTCEmployeeLoginDetails](
	[UTC_Auto_ID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeCode] [int] NULL,
	[UTC_TimeZone_ID] [int] NULL,
	[LogInDate] [datetime] NULL,
	[Flag] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_UTCTimeZonesCountryDetails]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_UTCTimeZonesCountryDetails](
	[TimezoneID] [int] IDENTITY(1,1) NOT NULL,
	[CountryCode] [char](5) NULL,
	[TimezoneName] [varchar](200) NULL,
	[TimezoneDesc] [varchar](200) NULL,
	[TimeZoneValue] [nvarchar](300) NULL,
	[HoursToBeAdded] [int] NULL,
	[MinToBeAdded] [int] NULL,
	[ServerDefault] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Version]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_Version](
	[VersionId] [bigint] IDENTITY(1,1) NOT NULL,
	[DatabaseVersionNo] [float] NULL,
	[DatabaseVersionName] [nvarchar](250) NULL,
	[ApplicationVersionNo] [float] NULL,
	[ApplicationVersionName] [nvarchar](250) NULL,
	[DatabaseVersionDate] [datetime] NULL,
	[ApplicationVersionDate] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_Version] PRIMARY KEY CLUSTERED 
(
	[VersionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_WhatsAppIdsForTriggering]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_WhatsAppIdsForTriggering](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[MobileNumber] [varchar](250) NOT NULL,
 CONSTRAINT [PK_TA_tbl_WhatsAppIdsForTriggering] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_WhatsAppNumberForTriggeringMessage]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_WhatsAppNumberForTriggeringMessage](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[WhatsAppType] [varchar](5) NOT NULL,
	[MobileNum] [varchar](250) NOT NULL,
 CONSTRAINT [PK_TA_tbl_WhatsAppNumberForTriggeringMessage] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_WhatsAppSchedule]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_WhatsAppSchedule](
	[ScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleName] [varchar](250) NOT NULL,
	[ReportId] [int] NOT NULL,
	[Frequency] [varchar](20) NOT NULL,
	[DayToSend] [varchar](10) NOT NULL,
	[DayFrom] [varchar](10) NOT NULL,
	[DayTo] [varchar](10) NOT NULL,
	[DateToSend] [int] NOT NULL,
	[DateFrom] [int] NOT NULL,
	[DateTo] [int] NOT NULL,
	[TimeToSend] [varchar](20) NOT NULL,
	[EmployeeId] [int] NOT NULL,
	[WhatsAppSendType] [bit] NOT NULL,
	[FileType] [varchar](20) NOT NULL,
	[Enabled] [bit] NOT NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[ReportName] [varchar](50) NULL,
	[ToWhom] [int] NULL,
	[TimeSendOption] [int] NULL,
	[Reminder_afterDays] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_WhatsAppSchedule] PRIMARY KEY CLUSTERED 
(
	[ScheduleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_WhatsAppScheduled_Employees]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_WhatsAppScheduled_Employees](
	[ScheduleId] [bigint] NULL,
	[Employee_id] [bigint] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_WhatsAppScheduleFilters]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_WhatsAppScheduleFilters](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Filters] [varchar](max) NULL,
	[ReportType] [varchar](25) NULL,
	[CompanyId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_WhatsAppScheduleFilters] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_tbl_WhatsAppScheduleStatus]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_tbl_WhatsAppScheduleStatus](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[DurationFrom] [datetime] NOT NULL,
	[DurationTo] [datetime] NOT NULL,
	[SentDate] [datetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[To_EmpID] [varchar](50) NULL,
	[MobileNumber] [varchar](max) NULL,
	[ErrorMessage] [nvarchar](max) NULL,
 CONSTRAINT [PK_TA_tbl_WhatsAppScheduleStatus] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_WhatsAppTemplate]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_WhatsAppTemplate](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Subject] [varchar](300) NOT NULL,
	[WhatsAppContent] [varchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_WhatsAppoContent] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_WindowsServiceFlag]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_WindowsServiceFlag](
	[WindowsServiceFlag] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_YearClosure]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_YearClosure](
	[YearClosureId] [int] IDENTITY(1,1) NOT NULL,
	[Year_SettingID] [int] NOT NULL,
	[OrgLevelId] [int] NULL,
	[YearClosed] [nvarchar](50) NULL,
	[DateClosed] [datetime] NULL,
	[Employee_Id] [int] NOT NULL,
	[LeaveTypeID] [int] NOT NULL,
	[Carry_PrevYear] [decimal](18, 1) NOT NULL,
	[Current_Quota] [decimal](18, 1) NOT NULL,
	[Borrow_NextYear] [decimal](18, 1) NOT NULL,
	[Leave_Taken] [decimal](18, 1) NOT NULL,
	[Available_Leaves] [decimal](18, 1) NOT NULL,
	[Encashment] [decimal](18, 1) NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Emp_ID] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_YearClosure] PRIMARY KEY CLUSTERED 
(
	[YearClosureId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_YearSetting]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TA_Tbl_YearSetting](
	[YearSettings_Id] [int] IDENTITY(1,1) NOT NULL,
	[StartMonth] [nvarchar](50) NOT NULL,
	[StartYear] [int] NOT NULL,
	[EndMonth] [nvarchar](50) NOT NULL,
	[EndYear] [int] NOT NULL,
	[FromDate] [smalldatetime] NULL,
	[ToDate] [smalldatetime] NULL,
	[TimeStamp] [datetime] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[IsActive] [bit] NOT NULL,
	[isTimezoneEnable] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_YearSetting] PRIMARY KEY CLUSTERED 
(
	[YearSettings_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[tb_reportslist]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tb_reportslist](
	[nIndex] [int] IDENTITY(1,1) NOT NULL,
	[dtDateTime] [datetime] NULL,
	[m_Date] [int] NULL,
	[m_Time] [int] NULL,
	[nDeviceID] [int] NULL,
	[nEvent] [int] NULL,
	[nUserID] [int] NULL,
	[sUserName] [varchar](255) NULL,
	[nSource] [int] NULL,
	[bAdminCheck] [int] NULL,
	[nTNAEvent] [int] NULL,
	[strUniqueKey] [char](38) NOT NULL,
	[ipAddress] [varchar](30) NULL,
	[LogUID] [bigint] NULL,
 CONSTRAINT [PK__tb_repor__ACB000332B754518] PRIMARY KEY CLUSTERED 
(
	[nIndex] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[tbl_realtime_glog]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_realtime_glog](
	[update_time] [datetime] NOT NULL,
	[device_id] [varchar](24) NULL,
	[user_id] [varchar](24) NULL,
	[verify_mode] [varchar](64) NULL,
	[io_mode] [varchar](32) NULL,
	[io_time] [datetime] NULL,
	[log_image] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Tbl_Sample]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tbl_Sample](
	[id] [int] NULL,
	[_name] [varchar](10) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Tbl_TempEmployeeShiftTime]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tbl_TempEmployeeShiftTime](
	[Employee_Code_Id] [varchar](10) NULL,
	[Employee_Name] [varchar](250) NULL,
	[Shift_Date] [datetime] NULL,
	[Shift_InTime] [varchar](10) NULL,
	[Shift_OutTime] [varchar](10) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TblAnalysisReport]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TblAnalysisReport](
	[Level] [varchar](max) NULL,
	[AbsentDate] [varchar](max) NULL,
	[LeaveDate] [varchar](max) NULL,
	[PermiDate] [varchar](max) NULL,
	[Employee Id] [int] NULL,
	[Employee Name] [varchar](max) NULL,
	[Total Late Days] [int] NULL,
	[Total Late Hours] [int] NULL,
	[PermissionHours] [int] NULL,
	[LeaveType] [varchar](100) NULL,
	[LeaveTypeTotalDays] [decimal](18, 1) NULL,
	[IntimationType] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TempApprovalSettings]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempApprovalSettings](
	[CompanyId] [int] NOT NULL,
	[OTApproval] [bit] NOT NULL,
	[LeaveSanction] [bit] NOT NULL,
	[PermissionSanction] [bit] NOT NULL,
	[ManualEntry] [bit] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[Roster] [bit] NULL,
	[Pattern] [bit] NOT NULL,
	[ODEntry] [bit] NULL,
	[Approval] [int] NULL,
	[shiftRequitionSaction] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TempEmployee]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempEmployee](
	[Employee_Id] [int] NULL,
	[Leave_Sanc_Authority] [int] NULL,
	[Reporting_To] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TempTitle]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempTitle](
	[TitleName] [nvarchar](50) NOT NULL,
	[TitleDescription] [nvarchar](250) NULL,
	[LevelID] [int] NULL,
	[LeavePolicyID] [int] NULL,
	[GradeID] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[Time_Stamp] [datetime] NULL,
	[TitleId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TempValues]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempValues](
	[Flag] [char](4) NULL,
	[FROMDate] [datetime] NULL,
	[Todate] [datetime] NULL,
	[empAutoID] [bigint] NULL,
	[UserGroupName] [nvarchar](250) NULL,
	[EmployeeCardNo] [varchar](max) NULL,
	[DailyChkbox] [int] NULL,
	[PresentChkbox] [int] NULL,
	[Weekly] [int] NULL,
	[Quarterly] [int] NULL,
	[absent] [int] NULL,
	[isExport] [int] NULL,
	[Years] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TestingOndutyImport]    Script Date: 10-30-2024 09:39:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestingOndutyImport](
	[OndutyImportData] [xml] NULL,
	[EmpAutoID] [bigint] NULL,
	[UserGroup] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-150414]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-150414] ON [dbo].[TA_Tbl_Category]
(
	[CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_TA_Tbl_Clk_RawData_CLK_FLAG]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IX_TA_Tbl_Clk_RawData_CLK_FLAG] ON [dbo].[TA_Tbl_Clk_RawData]
(
	[CLK_FLAG] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20161125-130854]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-130854] ON [dbo].[TA_Tbl_Clk_RawData]
(
	[CLK_DEVICEID] ASC
)
INCLUDE([CLK_ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_Clk_Date]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_Clk_Date] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_Date] ASC
)
INCLUDE([Clk_EmpId],[Clk_InDate],[Clk_InTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ClockDetails_Clk_Date]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ClockDetails_Clk_Date] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ClockDetails_Clk_EmpId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ClockDetails_Clk_EmpId] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_EmpId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ClockDetails_InPunches]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ClockDetails_InPunches] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_InDeviceId] ASC,
	[Clk_InPunchType] ASC,
	[Clk_Process] ASC
)
INCLUDE([Clk_EmpId],[Clk_InDate],[Clk_InTime],[Clk_Date]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ClockDetails_InPunchesDiff]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ClockDetails_InPunchesDiff] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_EmpId] ASC,
	[Clk_InPunchType] ASC,
	[Clk_Process] ASC,
	[Clk_Date] ASC
)
INCLUDE([Clk_InDeviceId],[Clk_InDate],[Clk_InTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_TA_Tbl_ClockDetails_1]    Script Date: 10-30-2024 09:39:56 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_TA_Tbl_ClockDetails_1] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_CompId] ASC,
	[Clk_EmpId] ASC,
	[Clk_Date] ASC,
	[Clk_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20161125-142109]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-142109] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_InDeviceId] ASC,
	[Clk_InPunchType] ASC,
	[Clk_OutDeviceId] ASC,
	[Clk_OutPunchType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-FirstAndLastMovements]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-FirstAndLastMovements] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_Date] ASC
)
INCLUDE([Clk_EmpId],[Clk_OutDate],[Clk_OutTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-FirstAndLastMovements2]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-FirstAndLastMovements2] ON [dbo].[TA_Tbl_ClockDetails]
(
	[Clk_Date] ASC
)
INCLUDE([Clk_EmpId],[Clk_InDeviceId],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutTime],[Clk_OutPunchType]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161201-175015]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161201-175015] ON [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]
(
	[LevelId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161201-174728]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161201-174728] ON [dbo].[TA_Tbl_DataProcessTemp]
(
	[ProcessDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20161128-112019]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161128-112019] ON [dbo].[TA_Tbl_Demo]
(
	[DemoType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_EmailScripts_ScriptType]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_EmailScripts_ScriptType] ON [dbo].[TA_TBL_EmailScripts]
(
	[ScriptType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_Employee_Status_Isdeleted_Employee_FirstName]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Status_Isdeleted_Employee_FirstName] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_Status] ASC,
	[Isdeleted] ASC,
	[Employee_FirstName] ASC
)
INCLUDE([Employee_Id],[Employee_LastName],[Employee_Code_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_EmployeeFirstName]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeFirstName] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_FirstName] ASC
)
INCLUDE([Employee_Code_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_MusterRoll_Employee_Status_InActiveDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_MusterRoll_Employee_Status_InActiveDate] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_Status] ASC,
	[InActiveDate] ASC
)
INCLUDE([SwipeCardNo]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_Employee_Code_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_Employee_Code_Id] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_Code_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_Employee_FirstName]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_Employee_FirstName] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_FirstName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_Employee_Status]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_Employee_Status] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_Isdeleted] ON [dbo].[TA_Tbl_Employee]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_Report_Exclude]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_Report_Exclude] ON [dbo].[TA_Tbl_Employee]
(
	[Report_Exclude] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Employee_SwipeCardNo]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Employee_SwipeCardNo] ON [dbo].[TA_Tbl_Employee]
(
	[SwipeCardNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20150526-184409]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150526-184409] ON [dbo].[TA_Tbl_Employee]
(
	[Employee_FirstName] ASC,
	[Employee_MiddleName] ASC,
	[Employee_LastName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-EmployeeDetailsForSearch]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-EmployeeDetailsForSearch] ON [dbo].[TA_Tbl_Employee]
(
	[Gender] ASC,
	[CompOff_Eligible] ASC,
	[OT_Eligible] ASC
)
INCLUDE([Employee_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-MonthlyAttendance]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-MonthlyAttendance] ON [dbo].[TA_Tbl_Employee]
(
	[Isdeleted] ASC,
	[SwipeCardNo] ASC
)
INCLUDE([Employee_Id],[Employee_Code_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_CategoryId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[TA_Tbl_EmployeeCategory]
(
	[CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EffectiveDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EffectiveDate] ON [dbo].[TA_Tbl_EmployeeCategory]
(
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[TA_Tbl_EmployeeCategory]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20150605-152819]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-152819] ON [dbo].[TA_Tbl_EmployeeCategory]
(
	[EmployeeId] ASC,
	[CategoryId] ASC,
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_DesignationId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[TA_Tbl_EmployeeDesignation]
(
	[DesignationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EffectiveDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EffectiveDate] ON [dbo].[TA_Tbl_EmployeeDesignation]
(
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[TA_Tbl_EmployeeDesignation]
(
	[EmployeeID] ASC
)
INCLUDE([DesignationID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20150605-152538]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-152538] ON [dbo].[TA_Tbl_EmployeeDesignation]
(
	[EmployeeID] ASC,
	[DesignationID] ASC,
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EffectiveDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EffectiveDate] ON [dbo].[TA_Tbl_EmployeeLevel]
(
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[TA_Tbl_EmployeeLevel]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_LevelId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[TA_Tbl_EmployeeLevel]
(
	[LevelId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20150605-151315]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-151315] ON [dbo].[TA_Tbl_EmployeeLevel]
(
	[EmployeeId] ASC,
	[EffectiveDate] ASC
)
INCLUDE([LevelId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_EmployeeLingual_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_EmployeeLingual_EmployeeId] ON [dbo].[TA_Tbl_EmployeeLingual]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_BasicPay]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_BasicPay] ON [dbo].[TA_Tbl_EmployeePay]
(
	[BasicPay] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EffectiveDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EffectiveDate] ON [dbo].[TA_Tbl_EmployeePay]
(
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[TA_Tbl_EmployeePay]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_Effective]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[TA_Tbl_EmployeeType]
(
	[EffectiveDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[TA_Tbl_EmployeeType]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TypeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[TA_Tbl_EmployeeType]
(
	[TypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Encashment_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Encashment_EmployeeId] ON [dbo].[TA_Tbl_Encashment]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Encashment_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Encashment_Isdeleted] ON [dbo].[TA_Tbl_Encashment]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Entrance_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Entrance_IsDeleted] ON [dbo].[TA_Tbl_Entrance]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Entrance_OrgLevel_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Entrance_OrgLevel_Id] ON [dbo].[TA_Tbl_Entrance]
(
	[OrgLevel_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161122-162652]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161122-162652] ON [dbo].[TA_Tbl_Entrance_INOUTDetails]
(
	[Entrance_Id] ASC
)
INCLUDE([Reader_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161122-162704]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161122-162704] ON [dbo].[TA_Tbl_Entrance_INOUTDetails]
(
	[Reader_Id] ASC
)
INCLUDE([Entrance_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-123204]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-123204] ON [dbo].[TA_Tbl_Entrance_INOUTDetails]
(
	[Reader_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Grade_Grade_Level]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Grade_Grade_Level] ON [dbo].[TA_Tbl_Grade]
(
	[Grade_Level] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Grade_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Grade_Isdeleted] ON [dbo].[TA_Tbl_Grade]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Holiday_Holiday_FromDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Holiday_Holiday_FromDate] ON [dbo].[TA_Tbl_Holiday]
(
	[Holiday_FromDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Holiday_Holiday_ToDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Holiday_Holiday_ToDate] ON [dbo].[TA_Tbl_Holiday]
(
	[Holiday_ToDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Holiday_Holiday_Type]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Holiday_Holiday_Type] ON [dbo].[TA_Tbl_Holiday]
(
	[Holiday_Type] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Holiday_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Holiday_Isdeleted] ON [dbo].[TA_Tbl_Holiday]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-113943]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-113943] ON [dbo].[TA_Tbl_HolidayChildTable]
(
	[LevelId] ASC,
	[Holiday_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_HolidaySettings_YearSettingId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_HolidaySettings_YearSettingId] ON [dbo].[TA_Tbl_HolidaySettings]
(
	[YearSettingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [ID_LeaveApplicationID]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [ID_LeaveApplicationID] ON [dbo].[TA_Tbl_LeaveApplicationExists]
(
	[LeaveApplicationId] ASC,
	[Employee_Id] ASC,
	[Leave_ApplicationDate] ASC,
	[Leave_FromDate] ASC,
	[Leave_ToDate] ASC,
	[Leave_SessionFrom] ASC,
	[Leave_SessionTo] ASC,
	[Status] ASC,
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LeavePolicy_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LeavePolicy_IsDeleted] ON [dbo].[TA_Tbl_LeavePolicy]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LeavePolicyDetails_LeaveType_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LeavePolicyDetails_LeaveType_Id] ON [dbo].[TA_Tbl_LeavePolicyDetails]
(
	[LeaveType_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LeavePolicyDetails_Policy_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LeavePolicyDetails_Policy_Id] ON [dbo].[TA_Tbl_LeavePolicyDetails]
(
	[Policy_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LeaveType_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LeaveType_IsDeleted] ON [dbo].[TA_Tbl_LeaveType]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Level_isDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Level_isDeleted] ON [dbo].[TA_Tbl_Level]
(
	[isDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Level_parenLevelID]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Level_parenLevelID] ON [dbo].[TA_Tbl_Level]
(
	[parentLevelID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LevelDetails_isDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LevelDetails_isDeleted] ON [dbo].[Ta_Tbl_levelDetails]
(
	[isDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_LevelDetails_ParentId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LevelDetails_ParentId] ON [dbo].[Ta_Tbl_levelDetails]
(
	[parentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_LevelRights_LevelId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_LevelRights_LevelId] ON [dbo].[TA_Tbl_LevelRights]
(
	[LevelId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20150605-160521]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-160521] ON [dbo].[TA_Tbl_LevelRights]
(
	[GroupId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-Levelid-Groupid]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-Levelid-Groupid] ON [dbo].[TA_Tbl_LevelRights]
(
	[LevelId] ASC,
	[GroupId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Lookup_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Lookup_Isdeleted] ON [dbo].[TA_Tbl_Lookup]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate] ON [dbo].[TA_Tbl_ManualTimeEntry]
(
	[ManualTimeEntry_InDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InTime] ON [dbo].[TA_Tbl_ManualTimeEntry]
(
	[ManualTimeEntry_InTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate] ON [dbo].[TA_Tbl_ManualTimeEntry]
(
	[ManualTimeEntry_OutDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutTime] ON [dbo].[TA_Tbl_ManualTimeEntry]
(
	[ManualTimeEntry_OutTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20161125-132515]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-132515] ON [dbo].[TA_Tbl_ManualTimeEntry]
(
	[ManualTimeEntry_InPunchType] ASC,
	[ManualTimeEntry_OutPunchType] ASC,
	[ManualTimeEntry_InReaderID] ASC,
	[ManualTimeEntry_OutReaderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Monthclosure_OrgLevel_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Monthclosure_OrgLevel_Id] ON [dbo].[TA_Tbl_MonthClosure]
(
	[OrgLevel_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_NewsEvents_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_NewsEvents_IsDeleted] ON [dbo].[TA_Tbl_NewsEvents]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_NewsEvents_NewsEventActive]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_NewsEvents_NewsEventActive] ON [dbo].[TA_Tbl_NewsEvents]
(
	[NewsEventActive] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_NewsEvents_NewsEventFromDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_NewsEvents_NewsEventFromDate] ON [dbo].[TA_Tbl_NewsEvents]
(
	[NewsEventFromDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_NewsEvents_NewsEventToDate]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_NewsEvents_NewsEventToDate] ON [dbo].[TA_Tbl_NewsEvents]
(
	[NewsEventToDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_parentId_ParentIdForSubMenu]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_parentId_ParentIdForSubMenu] ON [dbo].[TA_Tbl_Page]
(
	[parentId] ASC,
	[ParentIdForSubMenu] ASC
)
INCLUDE([pageId],[displayName],[path],[orderBy]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_PayrollProcessDetails_Employee_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PayrollProcessDetails_Employee_Id] ON [dbo].[TA_Tbl_PayrollProcessDetails]
(
	[Employee_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_PayrollProcessLeaveDetails_Employee_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PayrollProcessLeaveDetails_Employee_Id] ON [dbo].[TA_Tbl_PayrollProcessLeaveDetails]
(
	[Employee_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_PermanentShiftAllocation_DateShift]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PermanentShiftAllocation_DateShift] ON [dbo].[TA_Tbl_PermanentShiftAllocation]
(
	[DateShift] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_PermanentShiftAllocation_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PermanentShiftAllocation_EmployeeId] ON [dbo].[TA_Tbl_PermanentShiftAllocation]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_PermanentShiftAllocation_Month]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PermanentShiftAllocation_Month] ON [dbo].[TA_Tbl_PermanentShiftAllocation]
(
	[Month] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_PermanentShiftAllocation_Year]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PermanentShiftAllocation_Year] ON [dbo].[TA_Tbl_PermanentShiftAllocation]
(
	[Year] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [DailyDeviation]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [DailyDeviation] ON [dbo].[TA_Tbl_Permission]
(
	[IsDeleted] ASC,
	[Permission_Date] ASC
)
INCLUDE([Employee_Id],[Permission_Status],[Permission_Hours]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Permission_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Permission_IsDeleted] ON [dbo].[TA_Tbl_Permission]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Permission_Permission_FromTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Permission_Permission_FromTime] ON [dbo].[TA_Tbl_Permission]
(
	[Permission_FromTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Permission_Permission_Status]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Permission_Permission_Status] ON [dbo].[TA_Tbl_Permission]
(
	[Permission_Status] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Permission_Permission_ToTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Permission_Permission_ToTime] ON [dbo].[TA_Tbl_Permission]
(
	[Permission_ToTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_Date]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Date] ASC
)
INCLUDE([Employee_Code_Id],[Shift_Id],[InTime],[OutTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_MusterRoll_Date]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_MusterRoll_Date] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Date] ASC
)
INCLUDE([Employee_Code_Id],[Shift_Id],[InTime],[OutTime],[HrsWork],[Attendance],[LateInMins],[EarlyOutMins],[OtMins],[TotalDays],[FNAttendanceCode],[ANAttendanceCode],[InNotation],[OutNotation]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ProcessedData_Date]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ProcessedData_Date] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Date] ASC
)
INCLUDE([Employee_Code_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_ProcessedData_Employee_Code_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ProcessedData_Employee_Code_Id] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Employee_Code_Id] ASC
)
INCLUDE([Date]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-154218]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-154218] ON [dbo].[TA_Tbl_ProcessedData]
(
	[ProcessFlag] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-FirstAndLastMovements]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-FirstAndLastMovements] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Date] ASC
)
INCLUDE([Employee_Code_Id],[Shift_Id],[InTime],[OutTime]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-MonthlyAttendance]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-MonthlyAttendance] ON [dbo].[TA_Tbl_ProcessedData]
(
	[ProcessFlag] ASC,
	[Date] ASC
)
INCLUDE([Process_Rec_ID],[Employee_Code_Id],[Shift_Id],[InTime],[OutTime],[HrsWork],[NormOT],[OffOT],[HolOT],[EarlyOut],[LateIn],[Attendance],[WorkHrs],[LateInMins],[EarlyOutMins],[OtMins],[OvertimeStatus],[Status],[FNAttendanceCode],[ANAttendanceCode],[BreakHrs],[LunchHrs],[BreakHrsInMins],[LunchHrsInMins],[InNotation],[OutNotation]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-MonthlyAttendance1]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-MonthlyAttendance1] ON [dbo].[TA_Tbl_ProcessedData]
(
	[FNAttendanceCode] ASC
)
INCLUDE([Process_Rec_ID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-MonthlyAttendance2]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-MonthlyAttendance2] ON [dbo].[TA_Tbl_ProcessedData]
(
	[Date] ASC
)
INCLUDE([Employee_Code_Id],[Shift_Id]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_PunchTypes_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_PunchTypes_Isdeleted] ON [dbo].[TA_Tbl_PunchTypes]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_TA_Tbl_PunchTypes_Value]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IX_TA_Tbl_PunchTypes_Value] ON [dbo].[TA_Tbl_PunchTypes]
(
	[Value] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-141659]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-141659] ON [dbo].[TA_Tbl_PunchTypes]
(
	[Terminal_Id] ASC,
	[PunchType_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Shift_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Shift_Isdeleted] ON [dbo].[TA_Tbl_Shift]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Shift_Shift_EndTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Shift_Shift_EndTime] ON [dbo].[TA_Tbl_Shift]
(
	[Shift_EndTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_Shift_Shift_StartTime]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Shift_Shift_StartTime] ON [dbo].[TA_Tbl_Shift]
(
	[Shift_StartTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ShiftPattern_Isdeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ShiftPattern_Isdeleted] ON [dbo].[TA_Tbl_ShiftPattern]
(
	[Isdeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_ShiftRoaster_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_ShiftRoaster_IsDeleted] ON [dbo].[TA_Tbl_ShiftRoaster]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TemporaryShiftAllocation_DateShift]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TemporaryShiftAllocation_DateShift] ON [dbo].[TA_Tbl_TemporaryShiftAllocation]
(
	[DateShift] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TemporaryShiftAllocation_EmployeeId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TemporaryShiftAllocation_EmployeeId] ON [dbo].[TA_Tbl_TemporaryShiftAllocation]
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TemporaryShiftAllocation_Month]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TemporaryShiftAllocation_Month] ON [dbo].[TA_Tbl_TemporaryShiftAllocation]
(
	[Month] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TemporaryShiftAllocation_Year]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TemporaryShiftAllocation_Year] ON [dbo].[TA_Tbl_TemporaryShiftAllocation]
(
	[Year] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IDX_TA_Tbl_TempPayrollProcessDetails_Employee_Id]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TempPayrollProcessDetails_Employee_Id] ON [dbo].[TA_Tbl_TempPayrollProcessDetails]
(
	[Employee_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161128-111728]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161128-111728] ON [dbo].[TA_Tbl_TempShiftAllocation]
(
	[LoginEmployeeId] ASC
)
INCLUDE([EmpID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TemWeekday_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TemWeekday_IsDeleted] ON [dbo].[TA_Tbl_TemWeekday]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Terminal_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Terminal_IsDeleted] ON [dbo].[TA_Tbl_Terminal]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IX_TA_Tbl_Terminal]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IX_TA_Tbl_Terminal] ON [dbo].[TA_Tbl_Terminal]
(
	[Terminal_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [IX_TA_Tbl_Terminal_ReaderId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IX_TA_Tbl_Terminal_ReaderId] ON [dbo].[TA_Tbl_Terminal]
(
	[Terminal_ReaderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TerminalDatatype_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TerminalDatatype_IsDeleted] ON [dbo].[TA_tbl_TerminalDatatype]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_TerminalMapping_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_TerminalMapping_IsDeleted] ON [dbo].[TA_Tbl_TerminalMapping]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_Title_IsDeleted]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_Title_IsDeleted] ON [dbo].[TA_Tbl_Title]
(
	[IsDeleted] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20150605-155148]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-155148] ON [dbo].[TA_Tbl_Title]
(
	[TitleId] ASC,
	[TitleName] ASC,
	[GradeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161125-150933]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161125-150933] ON [dbo].[TA_Tbl_Type]
(
	[TypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex_Groupid]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex_Groupid] ON [dbo].[TA_Tbl_Usergroup]
(
	[groupId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  Index [NonClusteredIndex-20150605-153313]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20150605-153313] ON [dbo].[TA_Tbl_Usergroup]
(
	[isDeleted] ASC,
	[groupName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [NonClusteredIndex-20161128-103818]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [NonClusteredIndex-20161128-103818] ON [dbo].[TA_Tbl_userRights]
(
	[pageGroupId] ASC
)
INCLUDE([groupId],[addPrv],[modifyPrv],[deletePrv],[viewPrv]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_YearClosure_OrgLevelId]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_YearClosure_OrgLevelId] ON [dbo].[TA_Tbl_YearClosure]
(
	[OrgLevelId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_YearClosure_Year_SettingID]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_YearClosure_Year_SettingID] ON [dbo].[TA_Tbl_YearClosure]
(
	[Year_SettingID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
/****** Object:  Index [IDX_TA_Tbl_YearSetting_IsActive]    Script Date: 10-30-2024 09:39:56 ******/
CREATE NONCLUSTERED INDEX [IDX_TA_Tbl_YearSetting_IsActive] ON [dbo].[TA_Tbl_YearSetting]
(
	[IsActive] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TA_Tbl_ApprovalSettings] ADD  DEFAULT ((0)) FOR [webClockInOut]
GO
ALTER TABLE [dbo].[TA_Tbl_AttandanceCode] ADD  CONSTRAINT [DF_TA_Tbl_AttandanceCode_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] ADD  CONSTRAINT [DF_TA_Tbl_AuditOpr_OprDate]  DEFAULT (getdate()) FOR [OprDate]
GO
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] ADD  CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_CreatedDate]  DEFAULT (getdate()) FOR [CreatedDate]
GO
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] ADD  CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] ADD  CONSTRAINT [Defaultconstraints5]  DEFAULT ((0)) FOR [IsImport]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployees] ADD  DEFAULT ((0)) FOR [Daily]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployees] ADD  DEFAULT ((0)) FOR [DayWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployees] ADD  DEFAULT ((0)) FOR [WeekWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployees] ADD  DEFAULT ((0)) FOR [QuarterWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployees] ADD  DEFAULT ((0)) FOR [ContinuousDayWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory] ADD  DEFAULT ((0)) FOR [Daily]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory] ADD  DEFAULT ((0)) FOR [DayWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory] ADD  DEFAULT ((0)) FOR [WeekWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory] ADD  DEFAULT ((0)) FOR [QuarterWise]
GO
ALTER TABLE [dbo].[Ta_tbl_BlockedEmployeesHistory] ADD  DEFAULT ((0)) FOR [ContinuousDayWise]
GO
ALTER TABLE [dbo].[TA_Tbl_Clk_RawData] ADD  CONSTRAINT [DF_TA_Tbl_Clk_RawData_CLK_PROCESS]  DEFAULT ((0)) FOR [CLK_PROCESS]
GO
ALTER TABLE [dbo].[TA_Tbl_Clk_RawData] ADD  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_ClockDetails] ADD  CONSTRAINT [DF_TA_Tbl_ClockDetails_IsVoid]  DEFAULT ((0)) FOR [IsVoid]
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation] ADD  CONSTRAINT [DF__TA_Tbl_Co__TimeS__5CEF0720]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmailSchedule] ADD  CONSTRAINT [DF_TA_Tbl_EmailSchedule_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmailSchedule] ADD  DEFAULT ((0)) FOR [TimeSendOption]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] ADD  CONSTRAINT [TA_Tbl_Emp_LeavePolicy_AutoCredit]  DEFAULT ((0)) FOR [AutoCredit]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] ADD  DEFAULT ((0)) FOR [MaxDays_Month]
GO
ALTER TABLE [dbo].[ta_tbl_emp_LeaveTypedetails] ADD  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] ADD  CONSTRAINT [DF_TA_Tbl_EmpChildrenDetails_Time_stamp]  DEFAULT (getdate()) FOR [Time_stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth]  DEFAULT (NULL) FOR [DateofBirth]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth_Record]  DEFAULT (NULL) FOR [DateofBirth_Record]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_Passport_expirydate]  DEFAULT (NULL) FOR [Passport_expirydate]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_Visa_expirydate]  DEFAULT (NULL) FOR [Visa_expirydate]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_Anniversary_Date]  DEFAULT (NULL) FOR [Anniversary_Date]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_DateOfJoining]  DEFAULT (NULL) FOR [DateOfJoining]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF_TA_Tbl_Employee_Time_Stamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [Defaultconstraint]  DEFAULT ((0)) FOR [MobileClockInOUt]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [Defaultconstraint2]  DEFAULT ((0)) FOR [SMSEnabled]
GO
ALTER TABLE [dbo].[TA_Tbl_Employee] ADD  CONSTRAINT [DF__TA_Tbl_Em__IsMyP__5C07668D]  DEFAULT ((0)) FOR [IsMyProfileRqrd]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] ADD  CONSTRAINT [DF_TA_Tbl_EmployeeBonusLeave_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeCategory] ADD  CONSTRAINT [DF_TA_Tbl_EmployeeCategory_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeDesignation] ADD  CONSTRAINT [DF_TA_Tbl_EmployeeDesignation_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeLevel] ADD  CONSTRAINT [DF_TA_Tbl_EmployeeLevel_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeePay] ADD  CONSTRAINT [DF_TA_Tbl_EmployeePay_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeType] ADD  CONSTRAINT [DF_TA_Tbl_EmployeeType_Timestamp]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Encashment] ADD  CONSTRAINT [DF_TA_Tbl_Encashment_DateOfEncashment]  DEFAULT (getdate()) FOR [DateOfEncashment]
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance] ADD  CONSTRAINT [DF_TA_Tbl_Entrance_Time_Stamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance] ADD  DEFAULT ((0)) FOR [Flag]
GO
ALTER TABLE [dbo].[TA_Tbl_ErrLog] ADD  CONSTRAINT [DF_TA_Tbl_ErrLog_TimestampRec]  DEFAULT (getdate()) FOR [TimestampRec]
GO
ALTER TABLE [dbo].[TA_Tbl_ErrorLog_ClockRawData] ADD  CONSTRAINT [DF_TA_Tbl_ErrorLog_ClockRawData_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_ErrorLog_ProcessedData] ADD  CONSTRAINT [DF_TA_Tbl_ErrorLog_ProcessedData_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Grade] ADD  CONSTRAINT [DF_TA_Tbl_Grade_Time_Stamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[Ta_Tbl_ImportMasterData] ADD  CONSTRAINT [DF_Ta_Tbl_ImportMasterData_Employee_Status]  DEFAULT ((1)) FOR [Employee_Status]
GO
ALTER TABLE [dbo].[Ta_Tbl_LastUpdationofFile_Samsung] ADD  CONSTRAINT [DF_Ta_Tbl_LastUpdationofFile_Samsung_UpdationDatetime]  DEFAULT (getdate()) FOR [UpdationDatetime]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes] ADD  CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_DateInserted_1]  DEFAULT (getdate()) FOR [DateInserted]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes] ADD  CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_IsDeleted_1]  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation] ADD  CONSTRAINT [DF_TA_Tbl_LeaveConversation_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicy] ADD  CONSTRAINT [DF_TA_Tbl_LeavePolicy_Time_Stamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] ADD  CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_ApplicableAfterDays]  DEFAULT ((0)) FOR [ApplicableAfterDays]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] ADD  CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_Time_stamp]  DEFAULT (getdate()) FOR [Time_stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] ADD  DEFAULT ((0)) FOR [AvailServicePeriod]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] ADD  CONSTRAINT [DF_TA_TA_Tbl_LeavePrivateNotes_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveType] ADD  CONSTRAINT [DF_TA_Tbl_LeaveType_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveType] ADD  DEFAULT ((0)) FOR [CountFactor]
GO
ALTER TABLE [dbo].[TA_Tbl_Level] ADD  CONSTRAINT [DF_TA_Tbl_Level_parentLevelID]  DEFAULT ((0)) FOR [parentLevelID]
GO
ALTER TABLE [dbo].[TA_Tbl_Level] ADD  DEFAULT ((0)) FOR [isDeleted]
GO
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] ADD  DEFAULT ((0)) FOR [isDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Lookup] ADD  CONSTRAINT [DF_TA_Tbl_Lookup_Time_stamp]  DEFAULT (getdate()) FOR [Time_stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_MailConfiguration] ADD  DEFAULT ((0)) FOR [isRequired]
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry] ADD  CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate]  DEFAULT (NULL) FOR [ManualTimeEntry_InDate]
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry] ADD  CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate]  DEFAULT (NULL) FOR [ManualTimeEntry_OutDate]
GO
ALTER TABLE [dbo].[TA_Tbl_NewsEvents] ADD  CONSTRAINT [DF_TA_Tbl_NewsEvents_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_OndutyEntry] ADD  DEFAULT ((0)) FOR [isImported]
GO
ALTER TABLE [dbo].[TA_Tbl_OtType] ADD  CONSTRAINT [DF_TA_Tbl_OtType_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_OverTimeStatus] ADD  DEFAULT (getdate()) FOR [Modified_On]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day1Shift]  DEFAULT ((0)) FOR [Day1Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day2Shift]  DEFAULT ((0)) FOR [Day2Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day3Shift]  DEFAULT ((0)) FOR [Day3Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day4Shift]  DEFAULT ((0)) FOR [Day4Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day5Shift]  DEFAULT ((0)) FOR [Day5Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day6Shift]  DEFAULT ((0)) FOR [Day6Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day7Shift]  DEFAULT ((0)) FOR [Day7Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day8Shift]  DEFAULT ((0)) FOR [Day8Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day9Shift]  DEFAULT ((0)) FOR [Day9Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day10Shift]  DEFAULT ((0)) FOR [Day10Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day11Shift]  DEFAULT ((0)) FOR [Day11Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day12Shift]  DEFAULT ((0)) FOR [Day12Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day13Shift]  DEFAULT ((0)) FOR [Day13Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day14Shift]  DEFAULT ((0)) FOR [Day14Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day15Shift]  DEFAULT ((0)) FOR [Day15Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day16Shift]  DEFAULT ((0)) FOR [Day16Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day17Shift]  DEFAULT ((0)) FOR [Day17Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day18Shift]  DEFAULT ((0)) FOR [Day18Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day19Shift]  DEFAULT ((0)) FOR [Day19Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day20Shift]  DEFAULT ((0)) FOR [Day20Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day21Shift]  DEFAULT ((0)) FOR [Day21Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day22Shift]  DEFAULT ((0)) FOR [Day22Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day23Shift]  DEFAULT ((0)) FOR [Day23Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day24Shift]  DEFAULT ((0)) FOR [Day24Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day25Shift]  DEFAULT ((0)) FOR [Day25Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day26Shift]  DEFAULT ((0)) FOR [Day26Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day27Shift]  DEFAULT ((0)) FOR [Day27Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day28Shift]  DEFAULT ((0)) FOR [Day28Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day29Shift]  DEFAULT ((0)) FOR [Day29Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day30Shift]  DEFAULT ((0)) FOR [Day30Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day31Shift]  DEFAULT ((0)) FOR [Day31Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Permission] ADD  CONSTRAINT [DF_TA_Tbl_Permission_Permission_AppliedDate]  DEFAULT (getdate()) FOR [Permission_AppliedDate]
GO
ALTER TABLE [dbo].[TA_Tbl_Permission] ADD  DEFAULT ((0)) FOR [UnPlanned]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Daily_Rrd]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Daily_Hrs]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Day_Rqrd]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Weekly_Rqrd]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Quarterly_Rqrd]
GO
ALTER TABLE [dbo].[Ta_tbl_PolicyConfiguration] ADD  DEFAULT ((1)) FOR [Cont_Absent]
GO
ALTER TABLE [dbo].[ta_tbl_PrevPermissionDetails_EastMan] ADD  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_ProcessedData] ADD  CONSTRAINT [DF_TA_Tbl_ProcessedData_ProcessFlag]  DEFAULT ((0)) FOR [ProcessFlag]
GO
ALTER TABLE [dbo].[TA_Tbl_Project] ADD  CONSTRAINT [DF_TA_Tbl_Project_IsDeleted]  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[ta_tbl_PunchtypeRemarks] ADD  CONSTRAINT [DF__ta_tbl_Pu__Times__403C232B]  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] ADD  DEFAULT ((0)) FOR [Flag]
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] ADD  DEFAULT ((0)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] ADD  CONSTRAINT [DF_TA_Tbl_RouteMaster_IsMapped]  DEFAULT ((1)) FOR [IsMapped]
GO
ALTER TABLE [dbo].[TA_Tbl_Shift] ADD  DEFAULT ((1)) FOR [empCategory]
GO
ALTER TABLE [dbo].[TA_Tbl_Shift] ADD  CONSTRAINT [Defaultconstraint_WorkHours]  DEFAULT ('00:00') FOR [MaxShiftWorkHours]
GO
ALTER TABLE [dbo].[TA_tbl_ShiftAdd_Location] ADD  CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_CreatedOn]  DEFAULT (getdate()) FOR [CreatedOn]
GO
ALTER TABLE [dbo].[TA_tbl_ShiftAdd_Location] ADD  CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_ModifiedOn]  DEFAULT (getdate()) FOR [ModifiedOn]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftExchange] ADD  CONSTRAINT [DF_TA_Tbl_ShiftExchange_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  DEFAULT ('00:03') FOR [MaxWorkPlaceInHours]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [DF__TA_Tbl_Sh__Flexi__28ED12D1]  DEFAULT ((0)) FOR [Flexi_AfterShiftTime]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [DF__TA_Tbl_Sh__Flexi__29E1370A]  DEFAULT ((0)) FOR [Flexi_BeforeShiftTime]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [DF__TA_Tbl_Sh__Flexi__2AD55B43]  DEFAULT ((0)) FOR [Flexi_DefinedWorkhrs]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  DEFAULT ((0)) FOR [FirstAndLast]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  DEFAULT ((0)) FOR [Carry_Forward_COff_Year]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [Defaultconstraint1]  DEFAULT ((0)) FOR [LateMinsPerDay]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [Defaultconstraints2]  DEFAULT ((0)) FOR [LateDaysPerMonth]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitMinsPerDay]  DEFAULT ((0)) FOR [EarlyExitMinsPerDay]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitDaysPerMonth]  DEFAULT ((0)) FOR [EarlyExitDaysPerMonth]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  CONSTRAINT [Defaultconstraints1]  DEFAULT ((0)) FOR [EnableAbsent]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  DEFAULT ((0)) FOR [isRemindRrd_Pas_Vis]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] ADD  DEFAULT ((60)) FOR [reminderDays]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSGateway] ADD  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] ADD  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSTags] ADD  DEFAULT (getdate()) FOR [Timestamp]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplates] ADD  DEFAULT (getdate()) FOR [LastModified]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplates] ADD  DEFAULT ((0)) FOR [ToEmployee]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day1Shift]  DEFAULT ((0)) FOR [Day1Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day2Shift]  DEFAULT ((0)) FOR [Day2Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day3Shift]  DEFAULT ((0)) FOR [Day3Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day4Shift]  DEFAULT ((0)) FOR [Day4Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day5Shift]  DEFAULT ((0)) FOR [Day5Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day6Shift]  DEFAULT ((0)) FOR [Day6Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day7Shift]  DEFAULT ((0)) FOR [Day7Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day8Shift]  DEFAULT ((0)) FOR [Day8Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day9Shift]  DEFAULT ((0)) FOR [Day9Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day10Shift]  DEFAULT ((0)) FOR [Day10Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day11Shift]  DEFAULT ((0)) FOR [Day11Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day12Shift]  DEFAULT ((0)) FOR [Day12Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day13Shift]  DEFAULT ((0)) FOR [Day13Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day14Shift]  DEFAULT ((0)) FOR [Day14Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day15Shift]  DEFAULT ((0)) FOR [Day15Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day16Shift]  DEFAULT ((0)) FOR [Day16Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day17Shift]  DEFAULT ((0)) FOR [Day17Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day18Shift]  DEFAULT ((0)) FOR [Day18Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day19Shift]  DEFAULT ((0)) FOR [Day19Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day20Shift]  DEFAULT ((0)) FOR [Day20Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day21Shift]  DEFAULT ((0)) FOR [Day21Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day22Shift]  DEFAULT ((0)) FOR [Day22Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day23Shift]  DEFAULT ((0)) FOR [Day23Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day24Shift]  DEFAULT ((0)) FOR [Day24Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day25Shift]  DEFAULT ((0)) FOR [Day25Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day26Shift]  DEFAULT ((0)) FOR [Day26Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day27Shift]  DEFAULT ((0)) FOR [Day27Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day28Shift]  DEFAULT ((0)) FOR [Day28Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day29Shift]  DEFAULT ((0)) FOR [Day29Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day30Shift]  DEFAULT ((0)) FOR [Day30Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] ADD  CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day31Shift]  DEFAULT ((0)) FOR [Day31Shift]
GO
ALTER TABLE [dbo].[TA_Tbl_TemWeekday] ADD  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Terminal] ADD  CONSTRAINT [DF_TA_Tbl_Terminal_TimeStamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Title] ADD  CONSTRAINT [DF_TA_Tbl_Title_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Title] ADD  CONSTRAINT [DF_TA_Tbl_Title_Time_Stamp]  DEFAULT (getdate()) FOR [Time_Stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_TitleMapping] ADD  CONSTRAINT [DF_TA_Tbl_TitleMapping_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[Ta_tbl_Transfer] ADD  DEFAULT (getdate()) FOR [Trnsfr_EtyDteTme]
GO
ALTER TABLE [dbo].[Ta_tbl_Transfer] ADD  DEFAULT ('') FOR [Remarks]
GO
ALTER TABLE [dbo].[Ta_tbl_Transfer] ADD  DEFAULT ((0)) FOR [IsImprtd]
GO
ALTER TABLE [dbo].[Ta_tbl_Transfer] ADD  DEFAULT ('Approved') FOR [Trnsfr_status]
GO
ALTER TABLE [dbo].[TA_Tbl_Transportation_Mapping] ADD  CONSTRAINT [DF_TA_Tbl_Transportation_Mapping_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Transportation_Route] ADD  CONSTRAINT [DF_TA_Tbl_Transportation_Route_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Transportation_Vehicle] ADD  CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_IsDeleted]  DEFAULT ((1)) FOR [IsDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Transportation_Vehicle] ADD  CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_Time_stamp]  DEFAULT (getdate()) FOR [Time_stamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Type] ADD  DEFAULT ((0)) FOR [Isdisply_MyProf]
GO
ALTER TABLE [dbo].[TA_Tbl_Usergroup] ADD  CONSTRAINT [DF_TA_Tbl_Usergroup_timeStamp_2]  DEFAULT (getdate()) FOR [timeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Usergroup] ADD  CONSTRAINT [DF_TA_Tbl_Usergroup_isDeleted_1]  DEFAULT ((0)) FOR [isDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_Usergroup] ADD  CONSTRAINT [DF_TA_Tbl_Usergroup_ReportsBasedOn]  DEFAULT ((0)) FOR [ReportsBasedOn]
GO
ALTER TABLE [dbo].[TA_Tbl_userRights] ADD  CONSTRAINT [DF_TA_Tbl_userGroup_isDeleted]  DEFAULT ((0)) FOR [isDeleted]
GO
ALTER TABLE [dbo].[TA_Tbl_userRights] ADD  CONSTRAINT [DF_TA_Tbl_userGroup_timeStamp_1]  DEFAULT (getdate()) FOR [timeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppSchedule] ADD  CONSTRAINT [DF_TA_Tbl_WhatsAppSchedule_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppSchedule] ADD  DEFAULT ((0)) FOR [TimeSendOption]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Carry_PrevYear]  DEFAULT ((0)) FOR [Carry_PrevYear]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Current_Quota]  DEFAULT ((0)) FOR [Current_Quota]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Borrow_NextYear]  DEFAULT ((0)) FOR [Borrow_NextYear]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Leave_Taken]  DEFAULT ((0)) FOR [Leave_Taken]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Available_Leaves]  DEFAULT ((0)) FOR [Available_Leaves]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] ADD  CONSTRAINT [DF_TA_Tbl_YearClosure_Encashment]  DEFAULT ((0)) FOR [Encashment]
GO
ALTER TABLE [dbo].[TA_Tbl_YearSetting] ADD  CONSTRAINT [DF_TA_Tbl_YearSetting_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff] FOREIGN KEY([Addl_WeeklyOff_Id])
REFERENCES [dbo].[TA_Tbl_Additional_WeeklyOff] ([Addl_WeeklyOff_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels] CHECK CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]
GO
ALTER TABLE [dbo].[TA_Tbl_AuditField]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable] FOREIGN KEY([TableID])
REFERENCES [dbo].[TA_Tbl_AuditTable] ([TableID])
GO
ALTER TABLE [dbo].[TA_Tbl_AuditField] CHECK CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]
GO
ALTER TABLE [dbo].[TA_Tbl_AuditOperation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField] FOREIGN KEY([FieldID])
REFERENCES [dbo].[TA_Tbl_AuditField] ([FieldID])
GO
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] CHECK CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]
GO
ALTER TABLE [dbo].[TA_Tbl_AuditOperation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable] FOREIGN KEY([TableID])
REFERENCES [dbo].[TA_Tbl_AuditTable] ([TableID])
GO
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] CHECK CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup] FOREIGN KEY([CCGroupId])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned] FOREIGN KEY([CCGroupID])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup] FOREIGN KEY([CCGroupID])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]
GO
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails] FOREIGN KEY([LevelID])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] CHECK CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title] FOREIGN KEY([DesignationID])
REFERENCES [dbo].[TA_Tbl_Title] ([TitleId])
GO
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] CHECK CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75] FOREIGN KEY([ApprovedBy])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75]
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE] FOREIGN KEY([empid])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE]
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7] FOREIGN KEY([RejectedBy])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7]
GO
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters] CHECK CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate] CHECK CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy] FOREIGN KEY([LeavePolicy_Id])
REFERENCES [dbo].[TA_Tbl_LeavePolicy] ([Policy_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting] FOREIGN KEY([YearSettingId])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy] FOREIGN KEY([Emp_LeavePolicyId])
REFERENCES [dbo].[TA_Tbl_Emp_LeavePolicy] ([Emp_LeavePolicyId])
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType] FOREIGN KEY([LeaveType_Id])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1] FOREIGN KEY([Emp_ID])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] CHECK CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1] FOREIGN KEY([EmpId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting] FOREIGN KEY([YearSettingId])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]
GO
ALTER TABLE [dbo].[TA_Tbl_Encashment]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType] FOREIGN KEY([LeaveTypeId])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Encashment] CHECK CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance] FOREIGN KEY([Entrance_Id])
REFERENCES [dbo].[TA_Tbl_Entrance] ([Entrance_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] CHECK CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal] FOREIGN KEY([Reader_Id])
REFERENCES [dbo].[TA_Tbl_Terminal] ([Terminal_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] CHECK CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]
GO
ALTER TABLE [dbo].[TA_Tbl_Holiday]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting] FOREIGN KEY([YearSettings_Id])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Holiday] CHECK CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]
GO
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827] FOREIGN KEY([Holiday_Id])
REFERENCES [dbo].[TA_Tbl_Holiday] ([Holiday_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable] CHECK CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Le__Emplo__78199556] FOREIGN KEY([Employee_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication] CHECK CONSTRAINT [FK__TA_Tbl_Le__Emplo__78199556]
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveApplication_FileUpload]  WITH CHECK ADD FOREIGN KEY([LeaveApplication_Id])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation]  WITH CHECK ADD FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplication] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy] FOREIGN KEY([Policy_Id])
REFERENCES [dbo].[TA_Tbl_LeavePolicy] ([Policy_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType] FOREIGN KEY([LeaveType_Id])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster] FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplicationMaster] ([LeaveApplication_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] CHECK CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]
GO
ALTER TABLE [dbo].[Ta_Tbl_levelDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level] FOREIGN KEY([levelId])
REFERENCES [dbo].[TA_Tbl_Level] ([levelID])
GO
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] CHECK CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]
GO
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail] CHECK CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry]  WITH CHECK ADD FOREIGN KEY([OnDuty_ID])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_MonthClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails] FOREIGN KEY([OrgLevel_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_MonthClosure] CHECK CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_OnDutyConversation]  WITH CHECK ADD FOREIGN KEY([OnDutyApplicationId])
REFERENCES [dbo].[TA_Tbl_OndutyEntry] ([Onduty_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails] CHECK CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]
GO
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails] CHECK CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] CHECK CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] CHECK CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]
GO
ALTER TABLE [dbo].[TA_Tbl_Permission]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Pe__Emplo__2B99395C] FOREIGN KEY([Employee_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Permission] CHECK CONSTRAINT [FK__TA_Tbl_Pe__Emplo__2B99395C]
GO
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission] FOREIGN KEY([PermissionId])
REFERENCES [dbo].[TA_Tbl_Permission] ([Permission_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation] CHECK CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]
GO
ALTER TABLE [dbo].[TA_Tbl_PunchTypes]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal] FOREIGN KEY([Terminal_Id])
REFERENCES [dbo].[TA_Tbl_Terminal] ([Terminal_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] CHECK CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] CHECK CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle] FOREIGN KEY([VehicleID])
REFERENCES [dbo].[TA_Tbl_Transportation_Vehicle] ([VehicleId])
GO
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] CHECK CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] CHECK CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] CHECK CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster] CHECK CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C] FOREIGN KEY([logid])
REFERENCES [dbo].[TA_Tbl_SMSLogDetails] ([logid])
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild] CHECK CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C]
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75] FOREIGN KEY([TemplateID])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] CHECK CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75]
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE] FOREIGN KEY([TemplateID])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] CHECK CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers]  WITH CHECK ADD  CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7] FOREIGN KEY([TemplateId])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] CHECK CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7]
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters]  WITH CHECK ADD  CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20] FOREIGN KEY([TemplateId])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters] CHECK CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20]
GO
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday] FOREIGN KEY([TempWeekday_Id])
REFERENCES [dbo].[TA_Tbl_TemWeekday] ([TempWeekday_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels] CHECK CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday] FOREIGN KEY([TempWeekday_Id])
REFERENCES [dbo].[TA_Tbl_TemWeekday] ([TempWeekday_Id])
GO
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels] CHECK CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails] CHECK CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]
GO
ALTER TABLE [dbo].[TA_Tbl_Title]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade] FOREIGN KEY([GradeID])
REFERENCES [dbo].[TA_Tbl_Grade] ([Grade_ID])
GO
ALTER TABLE [dbo].[TA_Tbl_Title] CHECK CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade]
GO
ALTER TABLE [dbo].[TA_Tbl_Title]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails] FOREIGN KEY([LevelID])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_Title] CHECK CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_tbl_WhatsAppIdsForTriggering]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_tbl_WhatsAppIdsForTriggering_TA_Tbl_WhatsAppSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_WhatsAppSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_tbl_WhatsAppIdsForTriggering] CHECK CONSTRAINT [FK_TA_tbl_WhatsAppIdsForTriggering_TA_Tbl_WhatsAppSchedule]
GO
ALTER TABLE [dbo].[TA_tbl_WhatsAppNumberForTriggeringMessage]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_tbl_WhatsAppNumberForTriggeringMessage_TA_Tbl_WhatsAppSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_WhatsAppSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_tbl_WhatsAppNumberForTriggeringMessage] CHECK CONSTRAINT [FK_TA_tbl_WhatsAppNumberForTriggeringMessage_TA_Tbl_WhatsAppSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppScheduleFilters]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_WhatsAppScheduleFilters_TA_Tbl_WhatsAppSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_WhatsAppSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppScheduleFilters] CHECK CONSTRAINT [FK_TA_Tbl_WhatsAppScheduleFilters_TA_Tbl_WhatsAppSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppTemplate]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_WhatsAppTemplate_TA_Tbl_WhatsAppSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_WhatsAppSchedule] ([ScheduleId])
GO
ALTER TABLE [dbo].[TA_Tbl_WhatsAppTemplate] CHECK CONSTRAINT [FK_TA_Tbl_WhatsAppTemplate_TA_Tbl_WhatsAppSchedule]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType] FOREIGN KEY([LeaveTypeID])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails] FOREIGN KEY([OrgLevelId])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting] FOREIGN KEY([Year_SettingID])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]
GO
/****** Object:  StoredProcedure [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [CalculateSpecialOvertimeOnWeeklyAndHolidays_09Sep2019] '2019-09-08 08:18:00.000','2019-09-08 17:30:00.000',5722,132,'',64
-- =============================================
CREATE PROCEDURE [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]	
	@FirstInDateTime DATETIME,
	@LastOutDateTime DATETIME,
	@CompanyID INT,
	@TotalOTMins INT,
	@flag char(2),
	@ShiftID int,
	@ShiftDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	IF(@TotalOTMins>0)
	BEGIN
		DECLARE @ConfigSpecialOverTime1 INT
		DECLARE @ConfigSpecialOverTime2 INT
		SET @ConfigSpecialOverTime1 =0
		SET @ConfigSpecialOverTime2 =0
		DECLARE @SpecialOverTime1_StartTime DATETIME
		DECLARE @SpecialOverTime1_EndTime DATETIME
		DECLARE @SpecialOvertime1Mins INT
		DECLARE @SpecialOvertime2Mins INT
		DECLARE @NormalOvertimeMins INT
		IF(@flag='WH')
		BEGIN
			SELECT @ConfigSpecialOverTime1=SpecialOverTime1*60,@ConfigSpecialOverTime2=SpecialOverTime2*60 FROM TA_Tbl_ShiftSETtings WHERE CompanyId=@CompanyID
			SET @ConfigSpecialOverTime1=ISNULL(@ConfigSpecialOverTime1,0)
			SET @ConfigSpecialOverTime2=ISNULL(@ConfigSpecialOverTime2,0)
			IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2>0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@SpecialOverTime1_EndTime)
					SET	@SpecialOvertime2Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_EndTime,@LastOutDateTime)
				END
				ELSE
				BEGIN
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@LastOutDateTime)
					SET	@SpecialOvertime2Mins		=0
				END
			END
			ELSE IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2=0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN
					--SELECT '2 Loop 1'
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@LastOutDateTime)
					SET	@SpecialOvertime2Mins		=0
				END
				ELSE
				BEGIN
					--SELECT '2 Loop 2'
					SET	@NormalOvertimeMins			=@TotalOTMins
					SET @SpecialOvertime1Mins		=0
					SET	@SpecialOvertime2Mins		=0
				END
			END
			else
			BEGIN
				SET	@NormalOvertimeMins			=@TotalOTMins
				SET @SpecialOvertime1Mins		=0
				SET	@SpecialOvertime2Mins		=0
			END
		END
		ELSE
		BEGIN		
			SELECT @ConfigSpecialOverTime1=specialOvertime_start1,@ConfigSpecialOverTime2=specialOvertime_start2 
			FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID and Level_Id=@CompanyID
		
			SET @ConfigSpecialOverTime1=ISNULL(@ConfigSpecialOverTime1,0)
			SET @ConfigSpecialOverTime2=ISNULL(@ConfigSpecialOverTime2,0)					
			IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2>0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN					
					--6>=5
					--SPECIAL OT2=1
					--SPECILA OT1=2
					--NORMAL  OT =3
					--5>=5
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3										
					SET	@SpecialOvertime2Mins		=@TotalOTMins-(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2)
					SET @SpecialOvertime1Mins		=@ConfigSpecialOverTime2
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins-@SpecialOvertime2Mins
				END
				ELSE IF(@TotalOTMins>=@ConfigSpecialOverTime1)
				BEGIN					
					SET	@SpecialOvertime2Mins		=0
					SET @SpecialOvertime1Mins		=@TotalOTMins-(@ConfigSpecialOverTime1)
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins-@SpecialOvertime2Mins
				END
				ELSE
				BEGIN
					--4>=5
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3
					SET	@SpecialOvertime2Mins		=0
					SET @SpecialOvertime1Mins		=0
					SET	@NormalOvertimeMins			=@TotalOTMins
				END
			END
			ELSE IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2=0)
			BEGIN
				IF(@TotalOTMins>=@ConfigSpecialOverTime1)
				BEGIN
					--5>=3
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3
					--4>=3
					--SPECIAL OT2=0
					--SPECILA OT1=1
					--NORMAL  OT =3				
					SET @SpecialOvertime1Mins		=@TotalOTMins-@ConfigSpecialOverTime1
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins
					SET	@SpecialOvertime2Mins		=0
				END
				ELSE
				BEGIN
					SET @SpecialOvertime1Mins		=0
					SET	@NormalOvertimeMins			=@TotalOTMins
					SET	@SpecialOvertime2Mins		=0
				END
			END
			ELSE
			BEGIN
				--5>=3
				--SPECIAL OT2=0
				--SPECILA OT1=0
				--NORMAL  OT =5
				--4>=3
				--SPECIAL OT2=0
				--SPECILA OT1=0
				--NORMAL  OT =4	
				SET	@NormalOvertimeMins			=@TotalOTMins
				SET @SpecialOvertime1Mins		=0
				SET	@SpecialOvertime2Mins		=0
			END
		END
		select	Normal	=case when @NormalOvertimeMins<0	then 0 else @NormalOvertimeMins end,
				Special1=case when @SpecialOvertime1Mins<0	then 0 else @SpecialOvertime1Mins end,
				Special2=case when @SpecialOvertime2Mins<0	then 0 else @SpecialOvertime2Mins end
	END
END

GO
/****** Object:  StoredProcedure [dbo].[CheckApplicationDateExistsinYearsettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- CheckApplicationDateExistsinYearsettings '10/Apr/2012','10/Apr/2012',2
-- =============================================
CREATE PROCEDURE [dbo].[CheckApplicationDateExistsinYearsettings]  
	-- Add the parameters for the stored procedure here
	@Fromdate datetime,
	@ToDate datetime,
	@YearsettingId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if exists(select * from ta_tbl_yearsetting where Yearsettings_Id=@YearsettingId and FromDate <= @Fromdate and FromDate <= @ToDate 
		and ToDate >= @Fromdate and ToDate >= @ToDate )
			begin
				select 'OK'
			end
	else
	 select 'wrong'
END
GO
/****** Object:  StoredProcedure [dbo].[CheckLeaveBeforeAfterWithPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	CheckLeaveBeforeAfterWithPermission '02/19/2008','02/20/2008','PermissionOnLeave',5
Description		:	Check Permission Count for Before or After Leave Dates
Tables Included	:	TA_Tbl_Permission
Created By		:	Kumuthini
Created On		:	04-Sep-08
Modified By		:	
Modified On		:	
*/
-- [CheckLeaveBeforeAfterWithPermission] '09/03/2016','09/03/2016','LeaveAfterPermission',''
CREATE PROCEDURE [dbo].[CheckLeaveBeforeAfterWithPermission] 
	@LeaveFromDate datetime,
	@LeaveToDate datetime,
	@LeaveType nvarchar(50),
	@EmployeeId int
as
begin
	SET NOCOUNT ON;
	declare @Count as int
	if(@LeaveType='LeaveAfterPermission')
	-- Check Leave falls After Permission
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission 
			where Permission_Date=DATEADD( day ,1,@LeaveToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END
	else if(@LeaveType='LeaveBeforePermission')
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,-1,@LeaveFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END 
	else if(@LeaveType='LeaveOnPermission')
	-- Check Permission and Leave on same day
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission 
			where ((@LeaveFromDate between Permission_FromTime and Permission_ToTime) or (@LeaveToDate between Permission_FromTime and Permission_ToTime)) 
			and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END 
	select @Count as PermissionCount
End
GO
/****** Object:  StoredProcedure [dbo].[CheckVehicleNoExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : CheckVehicleNoExists
Description : check vehicle no is exist or not  
Tables Included : TA_Tbl_Transportation  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE procedure [dbo].[CheckVehicleNoExists](@VehicleNo INT) as 
     SELECT * FROM TA_Tbl_Transportation
                         WHERE VehicleNo=@VehicleNo
GO
/****** Object:  StoredProcedure [dbo].[CrossTab]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[CrossTab]
  @table       AS sysname,        -- Table to crosstab
  @onrows      AS nvarchar(128),  -- Grouping key values (on rows)
  @onrowsalias AS sysname = NULL, -- Alias for grouping column
  @oncols      AS nvarchar(128),  -- Destination columns (on columns)
  @avgcol      AS sysname = NULL  -- Data cells
AS
DECLARE
  @sql AS varchar(8000),
  @NEWLINE AS char(1)
SET @NEWLINE = CHAR(10)
-- step 1: beginning of SQL string
SET @sql =
  'SELECT' + @NEWLINE + 
  '  ' + @onrows +
  CASE
    WHEN @onrowsalias IS NOT NULL THEN ' AS ' + @onrowsalias
    ELSE ''
  END
CREATE TABLE #keys(keyvalue nvarchar(100) NOT NULL PRIMARY KEY)
DECLARE @keyssql AS varchar(1000)
SET @keyssql = 
  'INSERT INTO #keys ' +
  'SELECT DISTINCT CAST(' + @oncols + ' AS nvarchar(100)) ' +
  'FROM ' + @table
EXEC (@keyssql)
DECLARE @key AS nvarchar(100)
SELECT @key = MIN(keyvalue) FROM #keys
WHILE @key IS NOT NULL
BEGIN
  SET @sql = @sql + ','                   + @NEWLINE +
    '  AVG(CASE CAST(' + @oncols +
                     ' AS nvarchar(100))' + @NEWLINE +
    '        WHEN N''' + @key +
           ''' THEN ' + CASE
                          WHEN @avgcol IS NULL THEN '1'
                          ELSE @avgcol
                        END + @NEWLINE +
    '        ELSE 0'                      + @NEWLINE +
    '      END) AS AvgRespons' 
  SELECT @key = MIN(keyvalue) FROM #keys
  WHERE keyvalue > @key
END
SET @sql = @sql         + @NEWLINE +
  'FROM ' + @table      + @NEWLINE +
  'WHERE NOT ' + @avgcol + ' = -1 ' +@NEWLINE +
  'AND NOT ' + @onrows + '= 1' +@NEWLINE +
  'GROUP BY ' + @onrows + @NEWLINE +
  'ORDER BY ' + @onrows
EXEC (@sql)
GO
/****** Object:  StoredProcedure [dbo].[DeleteCustomDataBasedOnOptionType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name : DeleteCustomDataBasedOnOptionType  
Description : delete custom datas based on the option type.  
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[DeleteCustomDataBasedOnOptionType]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int	
)
AS
BEGIN
  delete from TA_ExportData_FieldData where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID
END
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : DeleteWeekday  
Description : delete the weekday 
Tables Included : TA_Tbl_TemWeekday  
Created By : Janakaraj.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[DeleteWeekday](@WeedayId varchar(100)) 
AS	
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET NOCOUNT ON;
	SET @Query='DELETE FROM TA_Tbl_TemWeekday WHERE TempWeekday_Id in (' + @WeedayId + ')'
	EXEC (@Query) 
END
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : DeleteWeekOff  
Description : delete additional week off  
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[DeleteWeekOff](@WeedayId varchar(100)) 
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SET @Query='UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=0 WHERE Addl_WeeklyOff_Id in (' + @WeedayId + ')'
EXEC (@Query) 
END
GO
/****** Object:  StoredProcedure [dbo].[DEVICEENR_TEMP_DELETE]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[DEVICEENR_TEMP_DELETE]   (@EMPID  varchar(15),   @TermID           int)  AS  BEGIN   DELETE FROM TBLDEVICEENRUSERS WHERE EMPCODE=@EMPID AND STATUS='N' and DeviceID=@TermID     RETURN (@@ROWCOUNT)  END  
GO
/****** Object:  StoredProcedure [dbo].[DEVICEMASTER_INSERT]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[DEVICEMASTER_INSERT]   ( @v_DEVICE_ADDRESS   nvarchar(50),    @v_DEVICE_NO   nvarchar(50),    @v_DEVICE_NAME  nvarchar(50),    @v_DEVICE_GROUP  nvarchar(50),    @v_DEVICE_TYPE  nvarchar(50),    @v_DEVICE_PORT  nvarchar(50),    @v_DEVICE_NETWORKNAME nvarchar(50),    @v_DEVICE_ACTIVE   bit ,    @v_SCHEDULER_RULE nvarchar(50),   @v_remark nvarchar(30),   @v_D_INOUT nvarchar(20))  AS    Declare @idVAl  int    BEGIN      SELECT @idVAl=isnull(MAX(Device_ID + 1),1)   FROM tblDevice_Mast        INSERT INTO tblDevice_Mast  (Device_ID,Device_Group,Device_Name,Device_Address,Device_No,Device_Type,Device_Port,  Device_Networkname,Device_Active,Schedule_Rule,remark,D_INOUT    )      VALUES      (@idVAl, @v_DEVICE_GROUP,  @v_DEVICE_NAME,@v_DEVICE_ADDRESS, @v_DEVICE_NO, @v_DEVICE_TYPE,    @v_DEVICE_PORT,    @v_DEVICE_NETWORKNAME,    @v_DEVICE_ACTIVE,    @v_SCHEDULER_RULE,@v_remark,@v_D_INOUT)  RETURN (@@ROWCOUNT)     END  
GO
/****** Object:  StoredProcedure [dbo].[EmpINReEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[EmpINReEntry] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
set @timeVal=15
declare emp_ReEntry cursor for 
--select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime from TA_Tbl_ClockDetails WHERE
  --    Clk_outTime IS NULL AND Clk_inTime IS NOT NULL and clk_indate< dateadd(d,-1,getdate())
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime from TA_Tbl_ClockDetails WHERE
Clk_outTime IS NULL AND isvoid=0 and Clk_inTime IS NOT NULL and 
clk_indate< dateadd(d,-1,getdate()) and clk_indate> dateadd(m,-2,getdate())  order by clk_empid,clk_indate,clk_intime desc
open emp_ReEntry
fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
--set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and clk_indate=@CLK_DATE and clk_inTime>dateadd(mi,-5,@CLK_TIME) and clk_inTime<dateadd(mi,5,@CLK_TIME) )
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_DATE  AND clk_inTime>=dateadd(mi,- @timeVal,@CLK_TIME) and isvoid=0 and clk_inTime<=dateadd(mi,@timeVal,@CLK_TIME) )
if (@eCount>0)
	begin 
--		delete from  dbo.TA_Tbl_ClockDetails where  CLK_ID=@CLK_ID
update dbo.TA_Tbl_ClockDetails set isvoid=1 where  CLK_ID=@CLK_ID
	end
--else
--begin
--end
  fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_ReEntry
GO
/****** Object:  StoredProcedure [dbo].[EmpOUTReEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[EmpOUTReEntry] 
as
declare @timeVal int
declare @CLK_ID int
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
set @timeVal=15
declare emp_OuTReEntry cursor for 
select Clk_Id,Clk_EmpId,Clk_outDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails WHERE
      Clk_inTime IS NULL AND Clk_outTime IS NOT NULL and clk_outdate< dateadd(d,-1,getdate()) and isvoid=0 and clk_outdate> dateadd(m,-2,getdate()) 
order by clk_empid,clk_outdate,clk_outtime
open emp_OuTReEntry
fetch emp_OuTReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
--set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and clk_indate=@CLK_DATE and clk_inTime>dateadd(mi,-5,@CLK_TIME) and clk_inTime<dateadd(mi,5,@CLK_TIME) )
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and Clk_OutDate=@CLK_DATE and Clk_OutTime>=dateadd(mi,- @timeVal,@CLK_TIME) and isvoid=0 and Clk_OutTime<=dateadd(mi,@timeVal,@CLK_TIME))
if @eCount>0
	begin 
--		delete from  dbo.TA_Tbl_ClockDetails where  CLK_ID=@CLK_ID
update dbo.TA_Tbl_ClockDetails set isvoid='1' where  CLK_ID=@CLK_ID
--  and clk_EmpID=@CLK_CARDID and Clk_OutDate=@CLK_DATE
	end
--else
--begin
--end
  fetch emp_OuTReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_OuTReEntry
GO
/****** Object:  StoredProcedure [dbo].[EmpProcessStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[EmpProcessStatus] 
as
declare @Process_Rec_ID varchar(20)
declare @Employee_Code varchar(20)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @HrsWork varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @eHours int
update dbo.TA_Tbl_ProcessedData set processflag=0  where left(HrsWork,2) >12
declare emp_ReProcess cursor for 
select  Process_Rec_ID,Employee_Code_Id,Date,Shift_Id,HrsWork,NormOT,OffOT,HolOT  from dbo.TA_Tbl_ProcessedData WHERE
      Attendance='Present'and FNAttendanceCode='Absent' and InTime is not null and OutTime is not null and left(HrsWork,2)<24 and date >dateadd(d,-60,getdate())  order by Process_Rec_ID
open emp_ReProcess
fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@HrsWork,@NormOT,@OffOT,@HolOT
while (@@fetch_status = 0 )
begin
		update dbo.TA_Tbl_ProcessedData set FNAttendanceCode='Present',ANAttendanceCode='Present' where Process_Rec_ID=@Process_Rec_ID 
--set @eHours =datediff(hour,'00:00',@HrsWork)
--if @eHours>7
--begin
		--update dbo.TA_Tbl_ProcessedData set ANAttendanceCode='Present' where Process_Rec_ID=@Process_Rec_ID
--end
  fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@HrsWork,@NormOT,@OffOT,@HolOT
end   
deallocate emp_ReProcess
GO
/****** Object:  StoredProcedure [dbo].[EmpReEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[EmpReEntry] 
as
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
	insert into dbo.TA_Tbl_Clk_BackupRawData (CLK_ID,CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME )(select Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails WHERE
      Clk_InTime IS NULL AND Clk_OutTime IS NOT NULL and clk_outdate<> getdate())
delete from TA_Tbl_ClockDetails WHERE
      Clk_InTime IS NULL AND Clk_OutTime IS NOT NULL and clk_outdate<> getdate()
--exec EmpINReEntry -- Remove the In Entrys Below 5 minutes
declare emp_ReEntry cursor for 
select CLK_ID,CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME from TA_Tbl_Clk_BackupRawData order by  CLK_ID
open emp_ReEntry
fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
set @CardNo=''
--set @CardNo=(select SwipeCardNo from dbo.TA_Tbl_Employee where Employee_Code_Id=@CLK_CARDID)
set @CardNo=@CLK_CARDID
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where clk_EmpID=@CLK_CARDID and clk_outdate=@CLK_DATE and clk_outTime>dateadd(mi,-5,@CLK_TIME) and clk_outTime<dateadd(mi,5,@CLK_TIME) )
--set @eCount=(select  count(Clk_EmpId) from dbo.TA_Tbl_ClockDetails WHERE
		--	Clk_EmpId= @CLK_CARDID AND Clk_OutDate =@CLK_DATE and Clk_OutTime=@CLK_TIME  )
if (@eCount=0)
begin
	if len(@CardNo)>0
	begin
			set @eCount=(select  count(CLK_CARDID) from dbo.TA_Tbl_Clk_RawData WHERE
				CLK_CARDID = @CLK_CARDID AND CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=1  )
	if (@eCount>0)
		begin
				update dbo.TA_Tbl_Clk_RawData set CLK_FLAG=0,CLK_PROCESS=0 WHERE
					CLK_CARDID = @CLK_CARDID AND CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=1 
		end
		else
		begin
				insert into dbo.TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS)
											values(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,1,0,0)
		end
	end
end
delete from TA_Tbl_Clk_BackupRawData where @CLK_ID=CLK_ID
  fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_ReEntry
GO
/****** Object:  StoredProcedure [dbo].[EmpReProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[EmpReProcess] 
as
declare @Process_Rec_ID varchar(20)
declare @Employee_Code varchar(20)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare emp_ReProcess cursor for 
select  Process_Rec_ID,Employee_Code_Id,Date,Shift_Id,NormOT,OffOT,HolOT  from dbo.TA_Tbl_ProcessedData WHERE
      Attendance='Present' and InTime is not null and OutTime is not null order by Process_Rec_ID
open emp_ReProcess
fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@NormOT,@OffOT,@HolOT
while (@@fetch_status = 0 )
begin
 set @OTtype='N'
if @HolOT<>'00:00'
begin 
 set @OTtype='H'
end
if @OffOT<>'00:00'
begin 
 set @OTtype='O'
end
set @eCount=(select  count(Clk_EmpId ) from TA_Tbl_ClockDetails WHERE
       Clk_EmpId = @Employee_Code AND Clk_InTime IS NOT NULL AND Clk_OutTime IS NOT NULL  AND Clk_InDate =@Emp_Date )
if @eCount>0
begin
		exec ReProcess_EmpLogs  @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@OTtype
		select @val='T'
 end
  fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@NormOT,@OffOT,@HolOT
end   
deallocate emp_ReProcess
GO
/****** Object:  StoredProcedure [dbo].[GetActiveLanguage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetActiveLanguage]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Language_Name from TA_Tbl_MultiLingual where IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFieldNameForExportData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name : GetCustomFieldNameForExportData  
Description : Gets the custom field name based on the option type.  
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 04-Apr-2011
*/  
CREATE PROCEDURE [dbo].[GetCustomFieldNameForExportData]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int		
)
AS
	BEGIN
	if(@OptionType = 'All')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name from  TA_ExportData_FieldData where OptionType='All' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = 'OT')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name from  TA_ExportData_FieldData where OptionType='OT' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = 'Attendance')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name from  TA_ExportData_FieldData where OptionType='Attendance' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = 'Leave')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name from  TA_ExportData_FieldData where OptionType='Leave' and DataType=@DataType and CompanyId=@CompanyID
		END
END
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFormatForExportData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name : GetCustomFormatForExportData  
Description : Gets the custom formats based on the option type.  
Tables Included : TA_ExportData_CustomFormat  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[GetCustomFormatForExportData]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int	
)
AS
	BEGIN
	if(@OptionType = 'All')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType='All' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = 'OT')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType='OT' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = 'Attendance')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType='Attendance' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = 'Leave')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType='Leave' and DataType=@DataType and CompanyID=@CompanyID
		END
END
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.r,,Name>
-- Create date: <06-05-2015,,>
-- Description:	<Get date month year using for the EmailSchedular,,>
-- GetDateMonth '2014-05-01','2014-05-31'
-- =============================================
Create PROCEDURE [dbo].[GetDateMonth]
	-- Add the parameters for the stored procedure here
	@FromDate varchar(25),
	@ToDate varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @Month varchar(10)
    declare @Year varchar(10)
    declare @TS varchar(10)
    declare @frmDate varchar(20)
    declare @frmDate1 varchar(20)
    --set @Month=(MONTH(convert(datetime,@FromDate)))
    set @Month=RIGHT('0'+CAST(MONTH(convert(datetime,@FromDate)) AS varchar(2)),2)
    set @Year=(year(convert(datetime,@FromDate)))
    set @frmDate = @FromDate
    set @TS=(DATEDIFF(day,@FromDate,@ToDate) + 1)
    DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
		if(@TS > 31)
			begin
				set @frmDate1=DATEADD(day,@TS - 31,@FromDate)
			end
		IF(@date='dd/MM/yyyy')
			BEGIN
				SET @frmDate1 = CONVERT(varchar, @frmDate, 103)
			END
		ELSE IF(@date='MM/dd/yyyy')
			BEGIN
				SET @frmDate1 = CONVERT(VARCHAR, @frmDate, 101)
			END
		ELSE
			BEGIN
				SET @frmDate1 = CONVERT(VARCHAR, @frmDate, 106)
			END
    select @Month as Month,@Year as Year,@TS as TS,@frmDate1 as Fromdate
END
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonthYear]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--GetDateMonthYear'2015-04-01','2015-05-01'
-- =============================================
Create PROCEDURE [dbo].[GetDateMonthYear] 
	-- Add the parameters for the stored procedure here
	@From varchar(20),
	@To varchar(20)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @year varchar(20)
	declare @Date varchar(20)
	declare @MOnth varchar(20)
	declare @year1 varchar(20)
	declare @Date1 varchar(20)
	declare @MOnth1 varchar(20)
    -- Insert statements for procedure here
    set @year=DATEPART(year,CONVERT(datetime,@From))
    set @Date=DATEPART(DAY,CONVERT(datetime,@From))
    set @MOnth=DATEPART(MONTH,CONVERT(datetime,@From))
    set @year1=DATEPART(year,CONVERT(datetime,@To))
    set @Date1=DATEPART(DAY,CONVERT(datetime,@To))
    set @MOnth1=DATEPART(MONTH,CONVERT(datetime,@To))
    select @year as Year,@MOnth as Month,@Date as Date union all select @year1 as Year,@MOnth1 as Month,@Date1 as Date
END
GO
/****** Object:  StoredProcedure [dbo].[GetDatetime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery6.sql|15|0|C:\Users\karthikeyan.r\AppData\Local\Temp\~vsE8C2.sql
-- =============================================
-- Author:		<Author,,Karthikeyan.R>
-- Create date: <28-04-2015,3.45 PM,>
-- Description:	<Description,,>
-- GetDatetime 'Daily',0,0
-- =============================================
CREATE PROCEDURE [dbo].[GetDatetime] 
	-- Add the parameters for the stored procedure here
	@ScheduleBasis varchar(20),
	@DateFrom int=null,
	@DateTo int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Month varchar(20)
	declare @Year varchar(20)
	set	@Month = MONTH(getdate())
	set @Year=YEAR(getdate())
    -- Insert statements for procedure here
    declare @FromDate varchar(20)
    declare @ToDate varchar(20)
    if(@ScheduleBasis='Monthly')
		begin
			if (@Month != 1)
			begin
				declare @preMonth varchar(20)
				declare @PreYear varchar(20)
				set @preMonth=(select dateadd(month, -1,GETDATE()))
				set @Month= MONTH(@preMonth)
				if (@DateFrom <= 28)
				begin
					set	@FromDate = @Month + '/' + CONVERT(varchar(10),@DateFrom) + '/' + @Year
				end
				else
				begin
					if (@Month = 4 or @Month = 6 or @Month  = 9 or @Month  = 11)
						begin
							if (@DateFrom = 31)
								begin
                                       set @FromDate = @Month + '/' + '30' + '/' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 = 0)
						begin
							if (@DateFrom > 29)
								begin
									set @FromDate = @Month + '/' + '29' + '/' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 != 0)
						begin
							set @FromDate = @Month + '/' + '28' + '/' + @Year
						End
					else
						begin
							set	@FromDate = @Month + '/' + CONVERT(varchar(10),@DateFrom) + '/' + @Year
						end
				end
			--To Date
			if (@DateTo <= 28)
				begin
					set @ToDate = @Month + '/' + CONVERT(varchar(10),@DateTo) + '/' + @Year
				end
			else
				begin
					if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
						begin
                            if (@DateTo = 31)
								begin
									set @ToDate = @Month + '/' + '30' + '/' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 = 0)
                        begin
                            if (@DateTo > 29)
								begin
									set @ToDate = @Month + '/' + '29' + '/' + @Year
								end
                        end
					else if (@Month = 2 and @Month % 4 != 0)
                        begin
                           set @ToDate = @Month + '/' + '28' + '/' + @Year
                        end
					else
						begin
                            set @ToDate = @Month + '/' + CONVERT(varchar(10),@DateTo) + '/' + @Year
                        end
				end
		end                            
		else
			begin
				set @preMonth=(select dateadd(month, -1,GETDATE()))
				set @PreYear=(select dateadd(YEAR, -1,GETDATE()))
				set @Month= MONTH(@preMonth)
				set @Year= YEAR(@PreYear)
			--From Date
				if (@DateFrom <= 28)
					begin
						set @FromDate = @Month + '/' + CONVERT(varchar(10),@DateFrom) + '/' + @Year
					end
				else
					begin
						if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
							begin
                                if (@DateFrom = 31)
									begin
										set @FromDate = @Month + '/' + '30' + '/' + @Year
									end
                            end
						else if (@Month = 2 and @Month % 4 = 0)
							begin
                                if (@DateFrom > 29)
									begin
										set @FromDate = @Month + '/' + '29' + '/' + @Year
									end
                            end
						else if (@Month = 2 and @Month % 4 != 0)
                            begin
                                set @FromDate = @Month + '/' + '28' + '/' + @Year
                            end
						else
							begin	
                               set @FromDate = @Month + '/' + CONVERT(varchar(10),@DateFrom) + '/' + @Year
                            end
					end
						--To Date
                        if (@DateTo <= 28)
							begin
								set @ToDate = @Month + '/' + CONVERT(varchar(10),@DateTo) + '/' + @Year
							end
                        else
							begin
								if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
									begin
										if (@DateTo = 31)
											begin
												set @ToDate = @Month + '/' + '30' + '/' + @Year
											end
									end
								else if (@Month = 2 and @Month % 4 = 0)
									begin
										if (@DateTo > 29)
											begin
												set @ToDate = @Month + '/' + '29' + '/' + @Year
											end
									end
								else if (@Month = 2 and @Month % 4 != 0)
									begin
										set @ToDate = @Month + '/' + '28' + '/' + @Year
									end
								else
									begin
										set  @ToDate = @Month + '/' + CONVERT(varchar(10),@DateTo) + '/' + @Year
									end
							end
			end
		end
	else if(@ScheduleBasis='Daily')
		begin
			--updated previous day logic on 10-July-2019 02:06 PM by Manikandan.R
			declare @Date1 varchar(20)
			set @Month=RIGHT('0'+CAST(MONTH(DATEADD(d,-1,GETDATE())) AS varchar(2)),2)
			set @Year=(YEAR(DATEADD(d,-1,GETDATE())))
			set @Date1=RIGHT('0'+CAST(DAY(DATEADD(d,-1,GETDATE())) AS varchar(2)),2)
			set @FromDate=@Year + '-' + @Month + '-' + @Date1
			set @ToDate=@Year + '-' + @Month + '-' + @Date1
		end
	else
		begin
			select 1
		end
			DECLARE @dateFormat as int
			DECLARE @date as nvarchar(25)
			declare @FromDate1 varchar(25)
			declare @ToDate1 varchar(25)
			SET @FromDate1=@FromDate
			set @ToDate1=@ToDate
			SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
			IF(@date='dd/MM/yyyy')
				BEGIN
					SET @FromDate = CONVERT(varchar, @FromDate1, 103)
					SET @ToDate = CONVERT(varchar, @ToDate1, 103)
				END
			ELSE IF(@date='MM/dd/yyyy')
				BEGIN
					SET @FromDate = CONVERT(VARCHAR, @FromDate1, 101)
					SET @ToDate = CONVERT(VARCHAR, @ToDate1, 101)
				END
			ELSE
				BEGIN
					SET @FromDate = CONVERT(VARCHAR, @FromDate1, 106)
					SET @ToDate = CONVERT(VARCHAR, @ToDate1, 106)
				END
			select @FromDate as FromDate,@ToDate as ToDate
END
GO
/****** Object:  StoredProcedure [dbo].[GetPreviousLeaveApplicationDaysValues]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-Apr-2019>
-- Description:	<Get the previously availe leave total count value details>
-- [GetPreviousLeaveApplicationDaysValues] 4
-- =============================================
CREATE PROCEDURE [dbo].[GetPreviousLeaveApplicationDaysValues]
	@LeaveAppID bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @YearSettingId INT
	SELECT @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where IsActive=1
	Declare @EarnedLeave decimal(18,1)
	Declare @LOP decimal(18,1)
	Declare @LeaveBal decimal(18,1)
	Declare @WaiveOff decimal(18,1)
	CREATE TABLE #Temp(Employee_id bigint,EarnedLeave decimal(18,1),LOP decimal(18,1),LeaveBal decimal(18,1),WaiveOff decimal(18,1))
	Declare @Employee_id bigint
	select @Employee_id=Employee_Id from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveAppID
	Insert into #Temp(Employee_id)values(@Employee_id)
	--select * from #Temp
	update T set LeaveBal=a.NumberOfDays from #Temp T inner join
	(
		select	yc.Employee_id,NumberOfDays=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))
		from TA_tbl_Yearclosure yc  
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
		inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
		left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
		and la.Status  not in ('Rejected') and la.Type not in ('Restricted Holiday','Comp Off','ESI')
		and la.LeaveApplication_Id<@LeaveAppID  
		and la.IsBorrow=0 group by yc.Employee_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
	)as a on a.Employee_Id=T.Employee_id
	update T set EarnedLeave=b.ELNumberOfDays,LOP=b.LOPNumberOfDays,WaiveOff=b.WONumberOfDays from #Temp T inner join
	(
		select ELNumberOfDays=sum(ELNumberOfDays),WONumberOfDays=sum(WONumberOfDays),LOPNumberOfDays=sum(LOPNumberOfDays),Employee_Id from
		( 
			select  ELNumberOfDays=case when lt.LeaveType='EL' and la.Type!='LOP' then la.NumberOfDays else 0 end,
					WONumberOfDays=case when lt.LeaveType='WO' then la.NumberOfDays else 0 end,
					LOPNumberOfDays=case when la.Type='LOP' then la.NumberOfDays else 0 end,
					Employee_Id from TA_Tbl_LeaveApplication la
			inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
			where la.Status  not in ('Rejected') and la.IsDeleted=0
			and la.LeaveApplication_Id<@LeaveAppID
		)as a group by Employee_Id
	)as b on b.Employee_Id=T.Employee_id
	select	@EarnedLeave=EarnedLeave,@LOP=LOP,@LeaveBal=LeaveBal,@WaiveOff=WaiveOff from #Temp
	Declare @ConcernName varchar(500)
	--select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id
	select top 1 @ConcernName=name from Ta_Tbl_levelDetails where description in(select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id)
	select	LeaveTaken=(isnull(@EarnedLeave,0)+isnull(@LOP,0)+isnull(@WaiveOff,0)),
			EarnedLeave=isnull(@EarnedLeave,0),
			LOP=isnull(@LOP,0),
			LeaveBal=isnull(@LeaveBal,0),
			WaiveOff=isnull(@WaiveOff,0),
			ConcernName=isnull(@ConcernName,'')
END
GO
/****** Object:  StoredProcedure [dbo].[ImportOvertTimeData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-June-2019 12:58 PM>
-- Description:	<Import OverTime data>
/*
ImportOvertTimeData
'<dsOverTime>  
  <dtOvertime>
    <Sl.no>3</Sl.no>
    <Employee_Code_Id>22028636</Employee_Code_Id>
    <Employee_FirstName>Ishmila Bahadoor</Employee_FirstName>
    <LevelName>Human Resources-Plastics</LevelName>
    <date>7/1/2019</date>
    <HrsOT>1:52</HrsOT>
    <ActHrsOT>2:00</ActHrsOT>
    <OffOT>0:00</OffOT>
    <ActOffOT>0:00</ActOffOT>
    <HolOT>0:00</HolOT>
    <ActHolOT>0:00</ActHolOT>
    <SPEC_NormOT1>0:00</SPEC_NormOT1>
    <Modified_Spec_NormOTHrs1>0:00</Modified_Spec_NormOTHrs1>
    <SPEC_NormOT2>0:00</SPEC_NormOT2>
    <Modified_Spec_NormOTHrs2>0:00</Modified_Spec_NormOTHrs2>
    <SPEC_OffOT1>0:00</SPEC_OffOT1>
    <Modified_Spec_OffOTHrs1>0:00</Modified_Spec_OffOTHrs1>
    <SPEC_OffOT2>0:00</SPEC_OffOT2>
    <Modified_Spec_OffOTHrs2>0:00</Modified_Spec_OffOTHrs2>
    <SPEC_HOLOT1>0:00</SPEC_HOLOT1>
    <Modified_Spec_HolOTHrs1>0:00</Modified_Spec_HolOTHrs1>
    <SPEC_HOLOT2>0:00</SPEC_HOLOT2>
    <Modified_Spec_HolOTHrs2>0:00</Modified_Spec_HolOTHrs2>
    <OverTimeStatus>Pending</OverTimeStatus>
  </dtOvertime>  
</dsOverTime>',1,'superadmin'
*/
-- =============================================
CREATE PROCEDURE [dbo].[ImportOvertTimeData]
	@OverTimeData XML = NULL,
	@EmpAutoID bigInt,
	@UserGroup VARCHAR(max)
AS
BEGIN
	Declare @OverTimeData1 XML = @OverTimeData
	Declare	@EmpAutoID1 bigInt=@EmpAutoID
	Declare @UserGroup1 VARCHAR(max)=@UserGroup
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)
	BEGIN TRY
		BEGIN TRAN ImportOverTimeData
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @OverTimeData1	
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@UserGroup1,0) AS LEVELID			
			DECLARE @SQLEMPLEVEL			NVARCHAR(4000)			
			SET @SQLEMPLEVEL=
			'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
			SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'
			EXECUTE(@SQLEMPLEVEL)			
			INSERT INTO Proc_ImportOvertime
			SELECT Tbl.*, case	when isnull(tbl.Employee_Code_Id,'')='' then 1 
								when isnull(e.Employee_Code_Id,'')='' then 2
								when E.CompOff_Eligible=1 then 3
								when (isnull(HrsOT,'')='' or 
								isnull(ActHrsOT,'')='' or 
								isnull(OffOT,'')='' or 
								isnull(ActOffOT,'')='' or 
								isnull(HolOT,'')='' or 
								isnull(ActHolOT,'')='' or 
								isnull(SPEC_NormOT1,'')='' or 
								isnull(Modified_Spec_NormOTHrs1,'')='' or 
								isnull(SPEC_NormOT2,'')='' or 
								isnull(Modified_Spec_NormOTHrs2,'')='' or 
								isnull(SPEC_OffOT1,'')='' or 
								isnull(Modified_Spec_OffOTHrs1,'')='' or 
								isnull(SPEC_OffOT2,'')='' or 
								isnull(Modified_Spec_OffOTHrs2,'')='' or 
								isnull(SPEC_HOLOT1,'')='' or 
								isnull(Modified_Spec_HolOTHrs1,'')='' or 
								isnull(SPEC_HOLOT2,'')='' or 
								isnull(Modified_Spec_HolOTHrs2,'')='') then 4
								when (CHARINDEX(':',HrsOT)=0 or 
								CHARINDEX(':',ActHrsOT)=0 or 
								CHARINDEX(':',OffOT)=0 or 
								CHARINDEX(':',ActOffOT)=0 or 
								CHARINDEX(':',HolOT)=0 or 
								CHARINDEX(':',ActHolOT)=0 or 
								CHARINDEX(':',SPEC_NormOT1)=0 or 
								CHARINDEX(':',Modified_Spec_NormOTHrs1)=0 or 
								CHARINDEX(':',SPEC_NormOT2)=0 or 
								CHARINDEX(':',Modified_Spec_NormOTHrs2)=0 or 
								CHARINDEX(':',SPEC_OffOT1)=0 or 
								CHARINDEX(':',Modified_Spec_OffOTHrs1)=0 or 
								CHARINDEX(':',SPEC_OffOT2)=0 or 
								CHARINDEX(':',Modified_Spec_OffOTHrs2)=0 or 
								CHARINDEX(':',SPEC_HOLOT1)=0 or 
								CHARINDEX(':',Modified_Spec_HolOTHrs1)=0 or 
								CHARINDEX(':',SPEC_HOLOT2)=0 or 
								CHARINDEX(':',Modified_Spec_HolOTHrs2)=0) then 5
								when (CONVERT(DATETIME,ActHrsOT)>CONVERT(DATETIME,HrsOT)	or
									  CONVERT(DATETIME,ActOffOT)>CONVERT(DATETIME,OffOT) or
									  CONVERT(DATETIME,ActHolOT)>CONVERT(DATETIME,HolOT) or 
									  CONVERT(DATETIME,Modified_Spec_NormOTHrs1)>CONVERT(DATETIME,SPEC_NormOT1) or 
									  CONVERT(DATETIME,Modified_Spec_NormOTHrs2)>CONVERT(DATETIME,SPEC_NormOT2) or 
									  CONVERT(DATETIME,Modified_Spec_OffOTHrs1)>CONVERT(DATETIME,SPEC_OffOT1) or 
									  CONVERT(DATETIME,Modified_Spec_OffOTHrs2)>CONVERT(DATETIME,SPEC_OffOT2) or 
									  CONVERT(DATETIME,Modified_Spec_HolOTHrs1)>CONVERT(DATETIME,SPEC_HOLOT1) or 
									  CONVERT(DATETIME,Modified_Spec_HolOTHrs2)>CONVERT(DATETIME,SPEC_HOLOT2)) then 6
							end			
			FROM OPENXML (@XMLParams, '/dsOverTime/dtOvertime', 2) WITH 
			(
				[Sl.no] VARCHAR(20), 
				Employee_Code_Id VARCHAR(20), 
				Employee_FirstName VARCHAR(max), 
				LevelName VARCHAR(max), 
				date VARCHAR(20), 
				HrsOT VARCHAR(20), 
				ActHrsOT VARCHAR(20), 
				OffOT VARCHAR(20), 
				ActOffOT VARCHAR(20), 
				HolOT VARCHAR(20), 
				ActHolOT VARCHAR(20), 
				SPEC_NormOT1 VARCHAR(20), 
				Modified_Spec_NormOTHrs1 VARCHAR(20), 
				SPEC_NormOT2 VARCHAR(20), 
				Modified_Spec_NormOTHrs2 VARCHAR(20), 
				SPEC_OffOT1 VARCHAR(20), 
				Modified_Spec_OffOTHrs1 VARCHAR(20), 
				SPEC_OffOT2 VARCHAR(20), 
				Modified_Spec_OffOTHrs2 VARCHAR(20), 
				SPEC_HOLOT1 VARCHAR(20), 
				Modified_Spec_HolOTHrs1 VARCHAR(20), 
				SPEC_HOLOT2 VARCHAR(20), 
				Modified_Spec_HolOTHrs2 VARCHAR(20), 
				OverTimeStatus VARCHAR(20)
			) Tbl			
			LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			AND E.IsDeleted = 0 AND E.Employee_Status = 1
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Code_Id FROM Proc_ImportOvertime)
			BEGIN
				SET @ErrMsg = 'There is no record in the file;<br />'
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END
			--select * from Proc_ImportOvertime
			IF NOT EXISTS(select Employee_Code_Id from Proc_ImportOvertime where Error!=0)
			BEGIN
				Insert into @ErrorMsg
				select [Sl.no], Employee_Code_Id,'',0,date from Proc_ImportOvertime where error=0
				IF EXISTS(SELECT t.Employee_Code_Id FROM Proc_ImportOvertime t INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (isnull(EL.EMPLOYEEID,'')=''))
				BEGIN
					set @alertMsg='Employee is not available or you are not having an previlege to import overtime data for this employee;<br />'				
					UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
															Else @alertMsg
													END,
					flag=0 FROM @ErrorMsg EM
					INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid				
					INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
					LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (isnull(EL.EMPLOYEEID,'')='')
				END
				IF NOT EXISTS(SELECT top 1 [Employee_Id] FROM @ErrorMsg WHERE flag=0)
				BEGIN						
					create table #tempEmployeeid(autoid int identity(1,1),Employee_Code_Id varchar(50))
					insert into #tempEmployeeid
					select distinct Employee_Code_Id from Proc_ImportOvertime where ISNULL(Employee_Code_Id, '') != ''
					Declare @count int
					Declare @start int
					set @start=1
					select @count=count(Employee_Code_Id) from #tempEmployeeid 
					while @start<=@count
					begin
							Declare @filterEmpid varchar(50)
							select @filterEmpid=Employee_Code_Id from #tempEmployeeid where autoid=@start
							Declare @Error int
							set @Error=0
							IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (TOT.Employee_Code_Id=@filterEmpid and @Error=0) and OtMins=0 AND tot.HrsOT!='00:00' AND TOT.HrsOT!='0:00')
							BEGIN
								SET @alertMsg='Normal day - Overtime hours is not calculated by system for this date, but mentioned in excel sheet;<br />'				
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		ELSE @alertMsg
																END,
								flag=0 
								--select * 
								FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (t.Employee_Code_Id=@filterEmpid and @Error=0) and OtMins=0 AND t.HrsOT!='00:00' AND t.HrsOT!='0:00'
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_NormOTMins1=0 AND TOT.SPEC_NormOT1!='00:00' AND TOT.SPEC_NormOT1!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg='Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />'			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)				
								WHERE (pd.SPEC_NormOTMins1=0 AND t.SPEC_NormOT1!='00:00' AND t.SPEC_NormOT1!='0:00')and  t.Employee_Code_Id=@filterEmpid								
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_NormOTMins2=0 AND TOT.SPEC_NormOT2!='00:00' AND TOT.SPEC_NormOT2!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg='Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />'	
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)				
								WHERE (pd.SPEC_NormOTMins2=0 AND t.SPEC_NormOT2!='00:00' AND t.SPEC_NormOT2!='0:00') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_OffOTMins1=0 AND TOT.SPEC_OffOT1!='00:00' AND TOT.SPEC_OffOT1!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg='Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />'			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_OffOTMins1=0 AND t.SPEC_OffOT1!='00:00' AND t.SPEC_OffOT1!='0:00') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_OffOTMins2=0 AND TOT.SPEC_OffOT2!='00:00' AND TOT.SPEC_OffOT2!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)							
							BEGIN
								SET @alertMsg='Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />'			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_OffOTMins2=0 AND t.SPEC_OffOT2!='00:00' AND t.SPEC_OffOT2!='0:00') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_HOLOTMins1=0 AND TOT.SPEC_HOLOT1!='00:00' AND TOT.SPEC_HOLOT1!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)
							--WHERE ((ISNULL(PD.SPEC_HOLOT1,'')='' OR PD.SPEC_HOLOT1='00:00') AND TOT.SPEC_HOLOT1!='00:00' AND TOT.SPEC_HOLOT1!='0:00')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
							BEGIN
								SET @alertMsg='Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />'			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_HOLOTMins1=0 AND t.SPEC_HOLOT1!='00:00' AND t.SPEC_HOLOT1!='0:00') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_HOLOTMins2=0 AND TOT.SPEC_HOLOT2!='00:00' AND TOT.SPEC_HOLOT2!='0:00') and  TOT.Employee_Code_Id=@filterEmpid)
							--WHERE ((ISNULL(PD.SPEC_HOLOT2,'')='' OR PD.SPEC_HOLOT2='00:00') AND TOT.SPEC_HOLOT2!='00:00' AND TOT.SPEC_HOLOT2!='0:00')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
							BEGIN
								SET @alertMsg='Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />'			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_HOLOTMins2=0 AND t.SPEC_HOLOT2!='00:00' AND t.SPEC_HOLOT2!='0:00') and  t.Employee_Code_Id=@filterEmpid
							END									
							ELSE if(@UserGroup1!='Superadmin')
							BEGIN
								IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
								INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
								WHERE (PD.OvertimeStatus='Approved')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
								BEGIN
									SET @alertMsg='Approved Overtime hours can''t be modified;<br />'
									UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																	END,
									flag=0 FROM @ErrorMsg EM
									INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
									INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
									WHERE (PD.OvertimeStatus='Approved') and  t.Employee_Code_Id=@filterEmpid
									and ISNULL(t.Employee_Code_Id, '') != ''
									set @Error=1
								END
							END
							set @start=@start+1
						end				
				end
			END
			ELSE
			BEGIN				
				insert into @ErrorMsg 
				select [Sl.no], Employee_Code_Id,
				case when error=1 then 'Employee ID is missing'
					 when error=2 then 'Employee is not available in Timecheck'
					 when error=3 then 'Overtime is not eligible'
					 when error=4 then 'Overtime is not specified in this row'
					 when error=5 then 'Time format is not correct'
					 when error=6 then 'Modified hours should not be greater than actual hours'
				end,0,date from Proc_ImportOvertime where error!=0
			END
			IF NOT EXISTS(SELECT top 1 [Employee_Id] FROM @ErrorMsg WHERE flag=0)
			BEGIN
				UPDATE TA_Tbl_ProcessedData SET 
				--select 
				ActHrsOT='00:00',
				ActNormOT=CASE WHEN LEN(tot.HrsOT)<5 THEN RIGHT('00' + tot.HrsOT,5) else tot.HrsOT end,
				ActNormOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.HrsOT)))*60+
							  SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.HrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.HrsOT))),
				ActOffOT=CASE WHEN LEN(tot.OffOT)<5 THEN RIGHT('00' + tot.OffOT,5) else tot.OffOT end,				
				ActOffOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.OffOT)))*60+
							 SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.OffOT))+1,LEN(CONVERT(VARCHAR(20),tot.OffOT))),
				ActHolOT=CASE WHEN LEN(tot.HolOT)<5 THEN RIGHT('00' + tot.HolOT,5) else tot.HolOT end,
				ActHolOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.HolOT)))*60+
							 SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.HolOT))+1,LEN(CONVERT(VARCHAR(20),tot.HolOT))),
				NormOT=CASE WHEN LEN(tot.ActHrsOT)<5 THEN RIGHT('00' + tot.ActHrsOT,5) else tot.ActHrsOT end,
				OffOT=CASE WHEN LEN(tot.ActOffOT)<5 THEN RIGHT('00' + tot.ActOffOT,5) else tot.ActOffOT end,
				HolOT=CASE WHEN LEN(tot.ActHolOT)<5 THEN RIGHT('00' + tot.ActHolOT,5) else tot.ActHolOT end,
				OtMins=SUBSTRING(CONVERT(VARCHAR(20),tot.ActHrsOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActHrsOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHrsOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActHrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActHrsOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActOffOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActOffOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActOffOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActOffOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActOffOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHolOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActHolOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHolOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.ActHolOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActHolOT))),
				ActOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.HrsOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.HrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.HrsOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.OffOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.OffOT))+1,LEN(CONVERT(VARCHAR(20),tot.OffOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.HolOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),CHARINDEX(':',CONVERT(VARCHAR(20),tot.HolOT))+1,LEN(CONVERT(VARCHAR(20),tot.HolOT)))
				FROM TA_Tbl_ProcessedData pd
				inner join Proc_ImportOvertime tot on (pd.Employee_code_id=tot.Employee_Code_Id and pd.Date=tot.date)
				-- Data is available
				UPDATE Ta_tbl_specialOvertimeDetails SET
				Modified_Spec_NormOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))),
				Modified_Spec_NormOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))),
				Modified_Spec_OffOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))),
				Modified_Spec_OffOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))),
				Modified_Spec_HolOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))),
				Modified_Spec_HolOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))),
				Modified_Spec_NormOTHrs1	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs1)<5 THEN RIGHT('00' + tot.Modified_Spec_NormOTHrs1,5) else tot.Modified_Spec_NormOTHrs1 end,
				Modified_Spec_NormOTHrs2	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_NormOTHrs2,5) else tot.Modified_Spec_NormOTHrs2 end,
				Modified_Spec_OffOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs1)<5 THEN RIGHT('00' +tot.Modified_Spec_OffOTHrs1,5) else tot.Modified_Spec_OffOTHrs1 end,
				Modified_Spec_OffOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_OffOTHrs2,5) else tot.Modified_Spec_OffOTHrs2 end,
				Modified_Spec_HolOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs1)<5 THEN RIGHT('00' +tot.Modified_Spec_HolOTHrs1,5) else tot.Modified_Spec_HolOTHrs1 end,
				Modified_Spec_HolOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_HolOTHrs2,5) else tot.Modified_Spec_HolOTHrs2 end,
				Modified_By=@EmpAutoID1,
				Modified_Date=GETDATE()
				FROM Ta_tbl_specialOvertimeDetails sot
				inner join Proc_ImportOvertime tot on (sot.Employee_code_id=tot.Employee_Code_Id and sot.Date=tot.date)				
				-- Data is not available
				INSERT INTO Ta_tbl_specialOvertimeDetails
				(Employee_code_id,Date,Modified_Spec_NormOTMins1,Modified_Spec_NormOTMins2,Modified_Spec_OffOTMins1,Modified_Spec_OffOTMins2,
				Modified_Spec_HolOTMins1,Modified_Spec_HolOTMins2,Modified_Spec_NormOTHrs1,
				Modified_Spec_NormOTHrs2,Modified_Spec_OffOTHrs1,Modified_Spec_OffOTHrs2,Modified_Spec_HolOTHrs1,Modified_Spec_HolOTHrs2,
				Inserted_By,Inserted_Date)
				select 	
				tot.Employee_Code_Id,
				tot.date,
				Modified_Spec_NormOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))),
				Modified_Spec_NormOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))),
				Modified_Spec_OffOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))),
				Modified_Spec_OffOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))),
				Modified_Spec_HolOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))),
				Modified_Spec_HolOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),0,CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),CHARINDEX(':',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))),
				Modified_Spec_NormOTHrs1	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs1)<5 THEN RIGHT('00' + tot.Modified_Spec_NormOTHrs1,5) else tot.Modified_Spec_NormOTHrs1 end,
				Modified_Spec_NormOTHrs2	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_NormOTHrs2,5) else tot.Modified_Spec_NormOTHrs2 end,
				Modified_Spec_OffOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs1)<5 THEN RIGHT('00' +tot.Modified_Spec_OffOTHrs1,5) else tot.Modified_Spec_OffOTHrs1 end,
				Modified_Spec_OffOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_OffOTHrs2,5) else tot.Modified_Spec_OffOTHrs2 end,
				Modified_Spec_HolOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs1)<5 THEN RIGHT('00' +tot.Modified_Spec_HolOTHrs1,5) else tot.Modified_Spec_HolOTHrs1 end,
				Modified_Spec_HolOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs2)<5 THEN RIGHT('00' +tot.Modified_Spec_HolOTHrs2,5) else tot.Modified_Spec_HolOTHrs2 end,
				@EmpAutoID1,GETDATE()
				
				FROM Proc_ImportOvertime tot
				LEFT OUTER JOIN Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=tot.Employee_Code_Id and sot.Date=tot.date)
				WHERE sot.Employee_code_id IS NULL

				
			END
			ELSE 
			BEGIN
				SELECT	RecordID,
						Employee_Id, 
						Error_Msg,
						date
				FROM @ErrorMsg where flag=0
			END
			delete from Proc_ImportOvertime
		COMMIT TRAN ImportOverTimeData
			SELECT 'Msg:DataImportedSuccessfully' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportOverTimeData
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
	END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Insert_Update_CustomFormatForExportData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name : Insert_Update_CustomFormatForExportData  
Description : inserts or updates the custom format for export data
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[Insert_Update_CustomFormatForExportData]
(
 @OptionType varchar(50),
 @DateFomat varchar(50),
 @TimeFormat varchar(50),	
 @DateTimeFormat varchar(50),
 @XMLRootTag varchar(50),
 @XMLFirstChildTag varchar(50),
 @DataType varchar(50),
 @CompanyID int
)
AS
BEGIN
  --Checks whether the custom format for the particular option type exists or not.
  --If exists inserts the custom format else updates the custom format based on option type.
  if exists(select OptionType from TA_ExportData_CustomFormat where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID)
	  BEGIN
		 update TA_ExportData_CustomFormat set 
		 DateFormat=@DateFomat,TimeFormat=@TimeFormat,DateTimeFormat=@DateTimeFormat,XML_RootTag=@XMLRootTag,XML_FirstChildTag=@XMLFirstChildTag
		 where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID
	  END
  else
	  BEGIN 
	     insert into TA_ExportData_CustomFormat values(@OptionType,@DateFomat,@TimeFormat,@DateTimeFormat,@XMLRootTag,@XMLFirstChildTag,@DataType,@CompanyID)
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDevice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertIrisLogsFromDevice]
	@LogData XML = NULL,
	@ipAddress varchar(30),
	@TerminalID varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @local_LogData XML = @LogData
	DECLARE @XMLParams INT
	
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LogData	
			Create table #TempIrisLogs
			(
				AdditionalData varchar(max),
				EventType  varchar(max),
				Info varchar(max),
				LogUID int,
				SubjectUID varchar(max),
				Timestamp datetime
			)
			insert into #TempIrisLogs
			SELECT	AdditionalData,
					EventType,
					Info,
					LogUID,
					SubjectUID,
					Timestamp
					FROM OPENXML (@XMLParams, '/DocumentElement/IrisLog_Table', 2) WITH 
					(
						AdditionalData varchar(max),
						EventType  varchar(max),
						Info varchar(max),
						LogUID int,
						SubjectUID varchar(max),
						Timestamp datetime
					) Tbl where SubjectUID is not null and AdditionalData='Allowed' and EventType='Recognition'
			--select * from tb_reportslist
			insert into tb_reportslist (dtDateTime,nDeviceID,nEvent,nUserID,nTNAEvent,strUniqueKey,ipAddress,LogUID)
			select	convert(datetime,t1.Timestamp)+CONVERT(datetime,'05:30'),
					@TerminalID,
					case when t1.EventType='Recognition' and t1.AdditionalData='Allowed' then 55 else 0 end,  
					t1.SubjectUID,
					CASE WHEN SUBSTRING(Info,0,CHARINDEX('/',Info))='In' then 1
						 WHEN SUBSTRING(Info,0,CHARINDEX('/',Info))='Out' then 2
						 WHEN SUBSTRING(Info,0,CHARINDEX('/',Info))='Leave' then 3
						 WHEN SUBSTRING(Info,0,CHARINDEX('/',Info))='Return' then 4
						 else 0
					END,
					RTRIM(lTrim(Info +'-'+ AdditionalData)),
					@ipAddress,
					t1.LogUID
			FROM #TempIrisLogs t1 
			LEFT JOIN tb_reportslist t2 on convert(datetime,t1.Timestamp)+CONVERT(datetime,'05:30') = t2.dtDateTime and t1.SubjectUID = t2.nUserID 
			WHERE t2.dtDateTime is null and convert(datetime,t1.Timestamp)+CONVERT(datetime,'05:30') <= getdate()
			and t1.AdditionalData='Allowed'
			--SELECT * FROM tb_reportslist
		
END
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDeviceTesting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertIrisLogsFromDeviceTesting]
	@LogData XML = NULL
AS
BEGIN
	SET NOCOUNT ON;
	Declare @local_LogData XML = @LogData
	DECLARE @XMLParams INT
	
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LogData	
			
			SELECT	AdditionalData,
					EventType,
					Info,
					LogUID,
					SubjectUID,
					Timestamp
					FROM OPENXML (@XMLParams, '/DocumentElement/IrisLog_Table', 2) WITH 
					(
						AdditionalData varchar(max),
						EventType  varchar(max),
						Info varchar(max),
						LogUID int,
						SubjectUID varchar(max),
						Timestamp datetime
					) Tbl			where SubjectUID is not null and AdditionalData='Allowed'
			
		
END
GO
/****** Object:  StoredProcedure [dbo].[InsertMariaLogsInToReportsList]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[InsertMariaLogsInToReportsList]
	@cDate numeric(18,0),
	@CLK_ID varchar(20),
	@IO varchar(20),
	@nReaderIdn varchar(20),
	@nEventIdn varchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @ORGDATE DATETIME 
	DECLARE @strUniqueKey NVARCHAR(255)
	set @ORGDATE=dateadd(SS,@cDate,'01/01/1970 05:30')
	set @strUniqueKey=@CLK_ID+@IO
	--4098	VERIFY_SUCCESS_ID_FINGERPRINT
	--4100	VERIFY_SUCCESS_ID_FACE
	--4865	IDENTIFY_SUCCESS_FINGERPRINT
	--4867	IDENTIFY_SUCCESS_FACE	
	if(@nEventIdn in(4100,4865,4867,4865,4098))
	begin
		IF NOT EXISTS(SELECT nIndex FROM tb_reportslist where dtDateTime=@ORGDATE and nDeviceID=@nReaderIdn and nEvent=@nEventIdn and nUserID=@CLK_ID and nTNAEvent=@IO and strUniqueKey=@strUniqueKey)
		BEGIN
			INSERT INTO dbo.tb_reportslist(dtDateTime,nDeviceID,nEvent,nUserID,nTNAEvent,strUniqueKey) 
			SELECT @ORGDATE,@nReaderIdn,@nEventIdn,@CLK_ID,@IO, @strUniqueKey 					
		END
	end
END
GO
/****** Object:  StoredProcedure [dbo].[InsertUpdateShiftRequstion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[InsertUpdateShiftRequstion]

@EmployeeID nvarchar(MAX), @RequisitionDate Datetime,@Status nvarchar(MAX), @Timestamp datetime, @EMP_ID nvarchar(MAX) ,
@DAY1 nvarchar(MAX) , @DAY2 nvarchar(MAX), @DAY3 nvarchar(MAX), 
@DAY4 nvarchar(MAX), @DAY5 nvarchar(MAX), @DAY6 nvarchar(MAX), 
@DAY7 nvarchar(MAX), @DAY8 nvarchar(MAX), @DAY9 nvarchar(MAX),
@DAY10 nvarchar(MAX), @DAY11 nvarchar(MAX), @DAY12 nvarchar(MAX),
@DAY13 nvarchar(MAX), @DAY14 nvarchar(MAX), @DAY15 nvarchar(MAX), 
@DAY16 nvarchar(MAX), @DAY17 nvarchar(MAX), @DAY18 nvarchar(MAX),
@DAY19 nvarchar(MAX), @DAY20 nvarchar(MAX), @DAY21 nvarchar(MAX), 
@DAY22 nvarchar(MAX), @DAY23 nvarchar(MAX), @DAY24 nvarchar(MAX),
@DAY25 nvarchar(MAX), @DAY26 nvarchar(MAX), @DAY27 nvarchar(MAX),
@DAY28 nvarchar(MAX), @DAY29 nvarchar(MAX), @DAY30 nvarchar(MAX),
@DAY31 nvarchar(MAX),@Tag int,@ShiftRequisitionID int,@CompanyID int

AS
BEGIN
declare @Stat Nvarchar(100) 
Declare @Approval Nvarchar(100)
declare @Report nvarchar(100)
declare @LeaveAuthority nvarchar(100)
set @Report = (Select Reporting_To from TA_Tbl_Employee where Employee_Code_Id = @EmployeeID)
set @LeaveAuthority=(Select Leave_Sanc_Authority from TA_Tbl_Employee where Employee_Code_Id = @EmployeeID)
set @Approval = (Select ShiftRequisition from TA_Tbl_ApprovalSettings where CompanyId = @CompanyID)


if (@Report = @LeaveAuthority)
begin
if(@Approval = '1')
begin
set @Stat = 'Forward'
end
else
set @Stat = 'Approval'
end


 if (@Report != @LeaveAuthority)
begin
if(@Approval = '1')
begin
set @Stat = 'Pending'
end
else
set @Stat = 'Approval'
end
end

--set @Stat = 'Approval'
--select * from TA_Tbl_ShiftRequisition

if(@Tag = 1)
BEGIN
insert into TA_Tbl_ShiftRequisition  ( EmployeeID, RequisitionDate,Status, Timestamp, EMP_ID, DAY1, DAY2, DAY3, DAY4, DAY5, DAY6, 
DAY7, DAY8, DAY9, DAY10, DAY11, DAY12, DAY13, DAY14, DAY15, DAY16, DAY17, DAY18, DAY19, 
DAY20, DAY21, DAY22, DAY23, DAY24, DAY25, DAY26, DAY27, DAY28, DAY29, DAY30, DAY31,CompanyID
) values
(@EmployeeID,@RequisitionDate,@Status,@Timestamp, @EMP_ID,case when @DAY1= '1' then '-1' else @DAY1 end,case when @DAY2= '1' then '-1' else @DAY2 end ,
case when @DAY3= '1' then '-1' else @DAY3 end ,case when @DAY4= '1' then '-1' else  @DAY4 end, case when @DAY5= '1' then '-1' else @DAY5 end , 
case when @DAY6= '1' then '-1' else @DAY6 end, case when @DAY7= '1' then '-1' else @DAY7 end , case when @DAY8= '1' then '-1' else @DAY8 end ,
case when @DAY9= '1' then '-1' else @DAY9 end,case when @DAY10= '1' then'-1' else @DAY10 end, case when @DAY11= '1' then '-1' else @DAY11 end ,
case when @DAY12= '1' then '-1' else @DAY12 end, case when @DAY13= '1' then '-1' else @DAY13 end,case when @DAY14= '1' then '-1'else @DAY14 end, 
case when @DAY15= '1' then '-1' else @DAY15 end,case when @DAY16= '1' then '-1' else @DAY16 end , case when @DAY17= '1' then '-1' else @DAY17 end, 
case when @DAY18= '1' then '-1' else @DAY18 end , case when @DAY19= '1' then '-1' else @DAY19 end, 
case when @DAY20= '1' then '-1' else @DAY20 end ,case when @DAY21= '1' then '-1' else @DAY21 end , case when @DAY22= '1' then '-1' else @DAY22 end ,
case when @DAY23= '1' then '-1' else @DAY23 end, case when @DAY24= '1' then '-1' else @DAY24 end, case when @DAY25= '1' then '-1'else @DAY25 end, 
case when @DAY26= '1' then '-1' else @DAY26 end , case when @DAY27= '1' then '-1' else @DAY27 end ,case when @DAY28= '1' then '-1' else @DAY28 end, 
case when @DAY29= '1' then '-1' else @DAY29 end , case when @DAY30= '1' then '-1' else @DAY30 end, case when @DAY31= '1' then '-1'  else @DAY31 end,
@CompanyID )


END
ELSE
BEGIN

UPDATE TA_Tbl_ShiftRequisition SET RequisitionDate=@RequisitionDate,Status=@Status,
Timestamp=@Timestamp, EMP_ID=@EMP_ID, DAY1=@DAY1, DAY2=@DAY2, DAY3=@DAY3, DAY4=@DAY4, DAY5=@DAY5, DAY6=@DAY6, DAY7=@DAY7, DAY8=@DAY8,
DAY9=@DAY9, DAY10=@DAY10, DAY11=@DAY11, DAY12=@DAY12, DAY13=@DAY13, DAY14=@DAY14, DAY15=@DAY15, DAY16=@DAY16, DAY17=@DAY17, DAY18=@DAY18, DAY19=@DAY19, 
DAY20=@DAY20, DAY21=@DAY21, DAY22=@DAY22, DAY23=@DAY23, DAY24=@DAY24, DAY25=@DAY25, DAY26=@DAY26, DAY27=@DAY27, DAY28=@DAY28, DAY29=@DAY29, DAY30=@DAY30,
DAY31=@DAY31 WHERE RequisitionDate = @RequisitionDate AND EmployeeID=@EmployeeID

END

	
	

GO
/****** Object:  StoredProcedure [dbo].[PermanentDeletePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure [dbo].[PermanentDeletePolicy]
(
	@Type CHAR(30),	
	@PolicyId NVARCHAR(500)
)
As 
Begin
	DECLARE @Query1 NVARCHAR(2000)
	SET @Query1=''

	if(@Type='PermanentDeletePFPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_PF_ESIDetails WHERE PFESI_Id IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End

End

Select * From TA_Tbl_PF_ESIDetails
GO
/****** Object:  StoredProcedure [dbo].[Pro_GetLeaveApplicationId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Pro_GetLeaveApplicationId] 
	-- Add the parameters for the stored procedure here
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    select LeaveApplicationID=IDENT_CURRENT('TA_Tbl_LeaveApplication')+1
END
GO
/****** Object:  StoredProcedure [dbo].[Pro_TA_ViewProjectbyProjectId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<View screen binding values procedure for Project>
-- =============================================
CREATE PROCEDURE [dbo].[Pro_TA_ViewProjectbyProjectId]
@ProjectId bigint, 
@userId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

IF EXISTS(select * from TA_Tbl_Project where project_Id = @ProjectId)
	Begin
		select isnull(Project_Name,'') as Project_Name,
		isnull(Project_Code,'') as Project_Code,
		isnull(Client_Name,'') as Client_Name,
		isnull(Project_Description,'') as Project_Description, 
		Project_StartTime,
		Project_EndTime,
		isnull(Project_Status,'') as Project_Status,
		LevelID,Mandays,ManHours,
		case when LevelID is not null and LevelID<>0 then (Select name from Ta_Tbl_levelDetails l where l.id=TA_Tbl_Project.LevelID) else '' end as LevelName
		from TA_Tbl_Project
		where project_Id = @ProjectId
	End

IF EXISTS(select ProjectID from TA_tbl_ProjectTaskList where ProjectID = @ProjectId)
	Begin
		Select TaskID,TaskName,TaskHours as Hours from TA_tbl_ProjectTaskList where ProjectID = @ProjectId
	End


END
GO
/****** Object:  StoredProcedure [dbo].[Pro_Update_RouteMaster_BYId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Pro_Update_RouteMaster_BYId  
Description : update route master by ID 
Tables Included : TA_Tbl_RouteMaster  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Pro_Update_RouteMaster_BYId] (@routeId int) As
 Update TA_Tbl_RouteMaster set IsMapped='1' where [id]=@routeId
GO
/****** Object:  StoredProcedure [dbo].[Proc_Approvaldatacount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gopinath.k, 19Jun15
-- Description:	To fetch data apprval count data for dashboard.
-- Proc_Approvaldatacount '','',0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Approvaldatacount]
	@FROMDATE datetime,
	@TODATE datetime,
	@ShiftID int,
	@ParentID int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @FromdateString varchar(20)
	Declare @Union varchar(max)
	set @Union=' Union All '
	Declare @Approveddata varchar(max)
		if @FROMDATE=''
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(varchar(20),DATEPART(month,getdate()))+'-'+
			case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(varchar(20),DATEPART(D,GETDATE()))
			else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
		end	
	else
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(varchar(20),DATEPART(month,@fromdate))+'-'+
			case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(varchar(20),DATEPART(D,@fromdate))
			else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild]('SuperAdmin',@ParentID) as LevelId
		Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
		'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
		 select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		 inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		 inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		 where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
		 inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		 inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
		 AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@TODATE as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	execute(@sqlEmpLevel)	
	-- OnDuty Data
	set @Approveddata ='SELECT DISTINCT ''Approved OnDuty'' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],1 AS HYPER, ''OnDuty'' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= '''+convert(varchar(max),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(varchar(max),@TODATE)+''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' ' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Forwarded OnDuty'' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],2 AS HYPER, ''OnDuty'' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= '''+convert(varchar(max),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(varchar(max),@TODATE)+''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''Forward'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Pending OnDuty'' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],3 AS HYPER, ''OnDuty'' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= '''+convert(varchar(max),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(varchar(max),@FromdateString)+''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''Pending'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
-- Permission Data
	set @Approveddata ='SELECT DISTINCT ''Approved Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],4 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' ' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Forwarded Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],5 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Forward'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Pending Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],6 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Pending'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
-- Leave Data
	set @Approveddata ='SELECT DISTINCT ''Approved Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],4 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' ' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Forwarded Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],5 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Forward'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Pending Permission'' AS TOPIC, COUNT(P.Permission_Date) [COUNT],6 AS HYPER, ''Permission'' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >='''+convert(varchar(max),@FromdateString)+''') AND (P.Permission_Date <='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''Pending'' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'SELECT DISTINCT ''Approved Leave'' AS TOPIC, COUNT(P.DATE) [COUNT],3 AS HYPER, ''Leave'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P
			Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			WHERE (P.DATE>='''+convert(varchar(max),@FromdateString)+''') AND (P.DATE<='''+convert(varchar(max),@FromdateString)+''') AND (ANATTENDANCECODE not in(''PRESENT'',''Absent'',''Weekly Off'',''RH'') AND FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''RH''))
			AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''18000000'' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+' '
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+' '
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_CheckNewsInYearSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- SELECT * FROM TA_Tbl_YearSettinG WHERE ISACTIVE=1
-- Proc_CheckNewsInYearSettings '2012-04-01','2013-04-01'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_CheckNewsInYearSettings]
	-- Add the parameters for the stored procedure here
	@Fromdate nvarchar(50),
	@ToDate nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @YSFromDate datetime
    select @YSFromDate=Fromdate from TA_Tbl_YearSetting where IsActive=1
    Declare @YSToDate datetime
    select @YSToDate=TODATE from TA_Tbl_YearSetting where IsActive=1
    Declare @result nvarchar(20)
    set @result=''
    Declare @result1 nvarchar(20)
    set @result1=''
     if(@Fromdate >= @YSFromDate and @Fromdate <= @YSToDate)
		begin
			set @result='True'
		end
	if(@ToDate >= @YSFromDate and @ToDate <= @YSToDate)
		begin
			set @result1='True'
		end
	if(@result='True' and @result1='True')
		begin
			select 1 as RESULT
		end
	else 
		begin
			select 0 as RESULT
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_CheckPassportExpiryDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Rajkumar.J
-- Create date: 06 Feb 2021
-- Description:	Procedure to check the Passport Expiry Date and Visa Expiry Date of a Employee
-- Exec Proc_CheckPassportExpiryDate 20
-- =============================================
Create PROCEDURE [dbo].[Proc_CheckPassportExpiryDate]
	-- Add the parameters for the stored procedure here
	@EmpID as varchar(50)null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @local_PassportExpiryDate as Datetime
	Declare @local_VisaExpiryDate as Datetime
	Declare @PassportExpiryCount as int
	Declare @VisaExpiryCount as int
	Declare @PassportExpireDate as Datetime
	Declare @VisaExpireDate as Datetime

	CREATE TABLE #TblEmpDetails (PassportDate datetime,VisaDate datetime)
	insert into #TblEmpDetails
	Select Passport_expirydate,Visa_expirydate from TA_Tbl_Employee where Employee_Id = @EmpID
	---------------------------
	Declare @count as Int
	Select @Count = count (*) from #TblEmpDetails

	If @Count <> 0
	BEGIN
    --select * from #TblEmpDetails
	set @local_PassportExpiryDate = (select PassportDate from #TblEmpDetails )
	set @local_VisaExpiryDate = (select VisaDate from #TblEmpDetails )

		IF(@local_PassportExpiryDate > GETDATE())
		BEGIN

		SELECT DATEDIFF(Day, GETDATE(), @local_PassportExpiryDate) AS PassportExpiresIn;
		SET	@PassportExpiryCount = 1
		END
		ELSE
		BEGIN
			SET	@PassportExpiryCount = 0
		END

		IF(@local_VisaExpiryDate > GETDATE())
		BEGIN

	        SET @PassportExpireDate = ( SELECT DATEDIFF(Day, GETDATE(), @local_VisaExpiryDate) AS VisaExpiresIn);
			SET	@VisaExpiryCount = 1
		END
		ELSE
		BEGIN
			SET	@VisaExpiryCount = 0
		END
	END
	select * from #TblEmpDetails

	----------------------
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_editLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_editLevel  
Description : edit level details  
Tables Included : ta_tbl_level, TA_Tbl_ParentIDs 
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_editLevel] 
(
	@lid int
)
AS
BEGIN
	SET NOCOUNT ON
	--DECLARE @lelid int, @lelName nvarchar(100)
	--SELECT @lelName = levelname FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
	--INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES (@lid,@lelName)
	--SELECT @lelid = parentlevelID FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
	--if (@lelid >0)
	--BEGIN
	--	EXEC dbo.proc_editLevel @lelid
	--END	
	--Commented by Manikandan.rr on 05-Feb-2020 due to performance issue.	
	;with cte
	as
	(
		SELECT levelid,parentLevelID as id, levelname name FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
		union all
		SELECT l.levelID,l.parentLevelID,l.levelName from cte c
		inner join ta_tbl_level  l on l.levelID=c.id 
	)
	INSERT INTO TA_Tbl_ParentIDs
	select levelID,name,id from cte
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Get_VehicleDetailsByRouteId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_Get_VehicleDetailsByRouteId  
Description : get vehicle details by route id  
Tables Included : TA_Tbl_Transportation_Vehicle, TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_Get_VehicleDetailsByRouteId] (@ID int) As  
Select A.VehicleNo,A.VehicleId from TA_Tbl_Transportation_Vehicle A, TA_Tbl_Transportation_Mapping B  
Where A.VehicleId = B.VehicleId AND B.RouteId = @Id 
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_GetEmployeeDetails]       
-- Proc_GetEmployeeDetails 'EIT02',1.2,1.2      
 -- Add the parameters for the stored procedure here      
 @EmpId nvarchar(100)=NULL,      
 @PresentDays NUMERIC(18,1)=NULL,      
 @Difference_Days NUMERIC(18,1)=NULL      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
    -- Insert statements for procedure here      
 IF @EmpId <> '0'      
  BEGIN      
    UPDATE TA_Tbl_AttendenceData SET PresentDays=@PresentDays,Difference_Days=@Difference_Days      
    WHERE EmpId=@EmpId      
   END      
  ELSE   
  BEGIN     
 SELECT EmpId,PresentDays,OD,EL,CL,SL,LOP_Absent,Difference_Days FROM TA_Tbl_AttendenceData      
 END  
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_GetProcessedDataDetailsForPayrollProcess  
Description : get process data detail for payroll process  
Tables Included : TA_Tbl_ProcessedData  
Created By : Kumuthini.L  
Created On : 05-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]
(
    @EmpId NVARCHAR(20),
    @StartDate DateTime,   
    @EndDate DateTime
)
 AS
SELECT * FROM TA_Tbl_ProcessedData P 
INNER JOIN TA_Tbl_Employee E  ON E.SwipeCardNo = P.Employee_Code_Id
where E.Swipecardno = @EmpId and P.Date between @StartDate and @EndDate
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetRouteDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_GetRouteDetails]  
AS  
BEGIN  
 SELECT [Id],Route_Name FROM TA_Tbl_RouteMaster WHERE Isdeleted=1
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingAutoShiftConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<P. Velumani>
-- Create date: <13/07/2019 16:44>
-- Description:	<Get All the shift details and Employee info for configuration>
-- Proc_GettingAutoShiftConfiguration '','',0,0,'superadmin','1',25,0,'both',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_GettingAutoShiftConfiguration]
	-- Add the parameters for the stored procedure here
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	Declare @Todate datetime
	set @Todate = getdate();
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))   
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @Todate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @Todate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @Todate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@Todate AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	'INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID ' 
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id '
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0'
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_Code_ID VARCHAR(25),
		EMPLOYEE_ID int,
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		--EMPLOYEE_STATUS int
	)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	E.EMPLOYEE_CODE_ID,E.Employee_Id,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&''),
	REPLACE(T.TITLENAME,''&AMP;'',''&'')'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     	
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId '
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 	
		(		
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)<=getdate()) 
		)'
	IF(@GENDER<>'BOTH')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND E.GENDER = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' '  
		END	
	if(@EmpAutoId>1)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	IF(@USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @GRADELEVEL + ''  
		END	
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME'
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
		DECLARE @AutoShiftSQL AS VARCHAR(MAX)    
		SET @AutoShiftSQL= ''    	
		SET @AutoShiftSQL = @AutoShiftSQL + 'Select Distinct
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,	
		EMPLOYEE_ID as EmployeeAutoID,
		EMPLOYEE_Code_ID as EMPLOYEE_Code_ID		
		from #TEMPMONTHLYATTENDANCE '
		Create table #AutoShiftConfig (AutoID int, EMPLOYEE_ID int,EMPNAME varchar(max), EmployeeAutoID int, EmployeeCodeId varchar(40)) 
		Insert into #AutoShiftConfig exec (@AutoShiftSQL)
		select AutoID,EmployeeCodeId as id,EMPNAME as Name, EmployeeAutoID, 
		isnull(b.ShiftId1,0) as ShiftID1,isnull(b.ShiftId2,0) as ShiftID2,isnull(b.ShiftId3,0) as ShiftID3
		, isnull(b.ShiftId4,0) as ShiftID4, isnull(b.ShiftId5,0) as ShiftID5
		from #AutoShiftConfig a
		left outer join TA_Tbl_AutoShiftConfiguration b on b.EmployeeId = a.EMPLOYEE_ID
		order by AutoID

		Select NightShiftEndTime_Autoshift From TA_Tbl_ShiftSettings where CompanyId=@PARENTID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_GettingNearShiftDetailsUsingInpunch '2019/07/01','2019/07/21','','',0,0,'superadmin',0,0,0,'both',0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]
	-- Add the parameters for the stored procedure here
	@FROMDAT DATETIME,
	@Todate  DATETIME,
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@SHIFT INT,	
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		CompanyId int,
		AllocatedShiftStartTime varchar(10)		
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_EMPLOYEE_CODE_ID] ON [DBO].[#TEMPPROCESSEDDATA]([DATE],[EMPLOYEE_CODE_ID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @Todate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @Todate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @Todate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@Todate AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	'INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID ' 
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id '
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0'
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	SET @SQLTEMPPROCESSEDDATA1=
	'INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	TE.EMPAUTOID,
			PD.DATE,
			PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			[dbo].[Func_TA_GetParentIds](TE.LEVELID),
			case when PD.Shift_ID=''-1'' then ''Off'' else S.SHIFT_STARTTIME end
	FROM TA_TBL_PROCESSEDDATA PD INNER JOIN #TEMPEMPLOYEE TE ON TE.EMPSWIPECARDNO=PD.EMPLOYEE_CODE_ID  	
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=PD.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (PD.DATE>= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102) and PD.DATE<= CONVERT(DATETIME,'''+CAST( @Todate AS NVARCHAR(50))+''', 102)) and intime is not null and intime<>''00:00'' ' 
	IF(@SHIFT<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + ' AND PD.SHIFT_ID= '+  CAST (@SHIFT AS NVARCHAR(50))
		END
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		AllocatedShiftStartTime varchar(10),
		CloseShifts varchar(max),
		CompanyId int,
		Gender varchar(10),
		ClosestShiftID int,
		EmployeeAutoID bigint
	)

	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	E.EMPLOYEE_CODE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&''),
	REPLACE(T.TITLENAME,''&AMP;'',''&''),
	CONVERT(VARCHAR(20),PD.DATE,101),
	PD.INTIME,PD.AllocatedShiftStartTime,
	[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,1,DATE),
	CompanyId,E.Gender,
	(select top 1 ShiftID from [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime](CompanyId,DATE+intime,1,DATE))
	,E.Employee_ID'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     	
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId '
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)
		AND(PD.DATE >= CONVERT(DATETIME, ''' + CAST(@FROMDAT AS NVARCHAR(11)) + ''', 102) and PD.DATE <= CONVERT(DATETIME, ''' + CAST(@Todate AS NVARCHAR(11)) + ''', 102))'
	IF(@GENDER<>'BOTH')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND E.GENDER = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' '  
		END	
	if(@EmpAutoId>1)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	IF(@USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @GRADELEVEL + ''  
		END	
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	 --Get current date time format.
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(20)
	DECLARE @TimeFormat as nvarchar(10)
	SELECT @date=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat() --TimeFormat FROM TA_Tbl_DateandTimeFormat
      IF(@date='dd/MM/yyyy')
            BEGIN
                  SET @dateFormat = 103
            END
      ELSE IF(@date='MM/dd/yyyy')
            BEGIN
                  SET @dateFormat = 101
            END
      ELSE
            BEGIN
                  SET @dateFormat = 106
            END 
	update TM set CloseShifts=
	case	when	([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)='') or 
					([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE) is null)then 
					CloseShifts
			else CloseShifts+';'+[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)
	end from #TEMPMONTHLYATTENDANCE TM
	select
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,
		BRANCHNAME Level,
		DESIGNATION Title,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		case when Intime<>'00:00' then
					CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
							ELSE SUBSTRING(InTime,13,5)+' ' + SUBSTRING(InTime,18,2)
					END
			else '' 
		end
		ActualShiftIn,		
		case	when AllocatedShiftStartTime!='Off' then 
			case	when (@TimeFormat)='hh:mm' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,AllocatedShiftStartTime,0)), 114)
					else	SUBSTRING(AllocatedShiftStartTime,13,5)+' ' + SUBSTRING(AllocatedShiftStartTime,18,2)
			end
				when AllocatedShiftStartTime='Off' then AllocatedShiftStartTime end
		AllocatedShift,
		CloseShifts NearestShift,Gender,CompanyId,DATE as Format,ClosestShiftID ShiftID,EmployeeAutoID
	from #TEMPMONTHLYATTENDANCE order by EMPLOYEE_ID,DATE
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_ImportOndutyEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		<R.MANIKANDAN>
-- CREATE DATE: <06-APRIL-2019>
-- DESCRIPTION:	<IMPORT THE ONDUTY RECORDS INTO DATABASE>
-- 
/*
PROC_IMPORTONDUTYENTRY @ONDUTYDATA ='<DocumentElement>
  <Data>
    <Sl.No>6</Sl.No>
    <EmployeeId>1003</EmployeeId>
    <Date>01-Apr-2019</Date>
    <Reason />
    <flag>1</flag>
    <Errormessage />
    <recordNumber>1</recordNumber>
    <ShiftID>3</ShiftID>
    <Userid>1</Userid>
    <Status>Approved</Status>
  </Data>
</DocumentElement>'
-- =============================================
*/
--drop PROCEDURE [dbo].[Proc_ImportOndutyEntry]
CREATE PROCEDURE [dbo].[Proc_ImportOndutyEntry]
	@ONDUTYDATA XML = NULL
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @XMLPARAMS INT,@YEARSETTINGID INT
	DECLARE @ERRMSG VARCHAR(MAX), @ERRIDS VARCHAR(MAX)	
			EXEC SP_XML_PREPAREDOCUMENT @XMLPARAMS OUTPUT, @ONDUTYDATA
			CREATE TABLE  #TA_TBL_IMPORTONDUTYRECORDS(AUTOID INT IDENTITY(1,1),EMPLOYEE_ID VARCHAR(100), DATE VARCHAR(20),
			REASON VARCHAR(MAX),SHIFTID INT,userid bigint,Status varchar(10))
			INSERT INTO #TA_TBL_IMPORTONDUTYRECORDS
				SELECT TBL.EmployeeId,TBL.Date,case when (TBL.Reason IS null or TBL.Reason='') then 'Onduty' else TBL.Reason end,TBL.ShiftID,TBL.Userid,TBL.Status
				FROM OPENXML (@XMLPARAMS, '/DocumentElement/Data', 2) WITH 
				  (EmployeeId VARCHAR(50),Date VARCHAR(20),Reason VARCHAR(MAX),ShiftID INT,Userid bigint,Status varchar(10)) TBL
				INNER JOIN TA_TBL_EMPLOYEE E ON E.EMPLOYEE_CODE_ID = TBL.EMPLOYEEID
				AND E.ISDELETED = 0 AND E.EMPLOYEE_STATUS = 1
			DECLARE @START INT
			SET @START=1
			DECLARE @TOTALREC INT
			SELECT @TOTALREC =COUNT(*) FROM #TA_TBL_IMPORTONDUTYRECORDS 
			SELECT @YEARSETTINGID = [YEARSETTINGS_ID] FROM [TA_TBL_YEARSETTING] WHERE [ISACTIVE] = 1 
			--SELECT * FROM #TA_TBL_IMPORTONDUTYRECORDS
			WHILE @START<=@TOTALREC
			BEGIN
				---ONDUTY ENTRY TABLE
				BEGIN
				DECLARE @TYPE NVARCHAR(2)
				DECLARE @ONDUTY_ID INT
				DECLARE @ONDUTY_EMPLOYEEID NVARCHAR(20)
				DECLARE @ONDUTY_ENTRYDATE	DATETIME
				DECLARE @ONDUTY_TYPE INT
				DECLARE @INCLUDEWEEKOFF INT
				DECLARE @ONDUTY_FROMDATE DATETIME
				DECLARE @ONDUTY_FROMTIME NVARCHAR(50)
				DECLARE @ONDUTY_TODATE DATETIME
				DECLARE @ONDUTY_TOTIME NVARCHAR(50)
				DECLARE @ONDUTY_REASON NVARCHAR(MAX)
				DECLARE @ONDUTY_STATUS NVARCHAR(25)
				DECLARE @EMP_ID INT
				DECLARE @FROM_SESSION NVARCHAR(25)
				SET @FROM_SESSION =''
				DECLARE @TO_SESSION NVARCHAR(25)
				SET @TO_SESSION =''
				DECLARE @MAXONDUTYID BIGINT
				SELECT @MAXONDUTYID=MAX(ONDUTY_ID) FROM TA_TBL_ONDUTYENTRY
				END
				---MANUAL ENTRY TABLE
				BEGIN
				DECLARE @MANUALENTRY_EMPLOYEEID NVARCHAR(20)
				DECLARE @MANUALENTRY_DATE DATETIME
				DECLARE @INDATE NVARCHAR(15)
				DECLARE @INTIME NVARCHAR(20)
				DECLARE @INPUNCHTYPE NVARCHAR(25)
				DECLARE @OUTDATE NVARCHAR(15)
				DECLARE @OUTTIME NVARCHAR(20)
				DECLARE @OUTPUNCHTYPE NVARCHAR(25)
				DECLARE @INREADER_ID INT
				DECLARE @OUTREADER_ID INT
				DECLARE @REASON NVARCHAR(MAX)
				DECLARE @ROUTEID INT
				DECLARE @STATUS NVARCHAR(25)
				DECLARE @USERID INT
				--DECLARE @YEARSETTINGS_ID NVARCHAR(25)
				DECLARE @ISONDUTY INT
				DECLARE @SHIFTID NVARCHAR(25)
				DECLARE @SHIFTDATE NVARCHAR(15)
				DECLARE @ONDUTYID INT
				END
				--GET VALUE FROM TEMP TABLE
				BEGIN
					SELECT	@TYPE='I',
							@ONDUTY_TYPE=1,
							@MANUALENTRY_EMPLOYEEID=EMPLOYEE_ID,
							@INCLUDEWEEKOFF=0,
							@MANUALENTRY_DATE=CONVERT(VARCHAR(11),GETDATE()),
							@INDATE=DATE,
							@INPUNCHTYPE='IN',
							@OUTDATE=DATE,
							@OUTPUNCHTYPE='OUT',
							@REASON=REASON,
							@ROUTEID=0,
							@STATUS=Status,
							@USERID=userid,
							@ISONDUTY=1,
							@SHIFTID=SHIFTID,
							@SHIFTDATE=DATE,
							@ONDUTYID=0
					FROM #TA_TBL_IMPORTONDUTYRECORDS WHERE AUTOID=@START
				END
				--SHIFT START TIME AND END TIME
				BEGIN
					SELECT @INTIME=SHIFT_STARTTIME,@OUTTIME=SHIFT_ENDTIME FROM TA_TBL_SHIFT WHERE SHIFT_ID=@SHIFTID AND ISDELETED=0
				END
				--IN READER ID
				BEGIN
					SELECT @INREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='787'
				END
				--OUT READER ID
				BEGIN
					SELECT @OUTREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='788'
				END
				--ASSIGN VALUES TO ONDUTY TABLE
				BEGIN
					SELECT @ONDUTY_ID=@ONDUTYID,@ONDUTY_EMPLOYEEID=@MANUALENTRY_EMPLOYEEID,@ONDUTY_ENTRYDATE=@MANUALENTRY_DATE,
					@ONDUTY_FROMDATE=@INDATE,@ONDUTY_FROMTIME=@INTIME,@ONDUTY_TODATE=@OUTDATE,@ONDUTY_TOTIME=@OUTTIME,
					@ONDUTY_REASON=@REASON,@ONDUTY_STATUS=@STATUS,@EMP_ID=@USERID
					--SELECT 
					--@TYPE,@ONDUTY_ID, @ONDUTY_EMPLOYEEID, @ONDUTY_ENTRYDATE, @ONDUTY_TYPE, @INCLUDEWEEKOFF,
					--@ONDUTY_FROMDATE,@ONDUTY_FROMTIME,@ONDUTY_TODATE,@ONDUTY_TOTIME,@ONDUTY_REASON,
					--@ONDUTY_STATUS,@EMP_ID,@FROM_SESSION, @TO_SESSION;					
				END
				--INSERT ONDUTY VALUES
				DECLARE	@RETURN_VALUE bigint
				BEGIN
					DECLARE @sql nvarchar(max)
					SET @sql = ''
					SET @sql = @sql + 'INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FromDate,Onduty_FromTime,Onduty_ToDate
					,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,From_Session,To_Session) 
					VALUES (N'''+ @Onduty_EmployeeID +''',N''' + cast(@Onduty_EntryDate as nvarchar(20)) + ''',N''' +CAST(@Onduty_Type as nvarchar(10)) +''',N''' +CAST(@IncludeweekOff as nvarchar(10)) +''',N''' + cast(@Onduty_FromDate as nvarchar(20) )+ ''',N''' + CAST(@Onduty_FromTime as nvarchar(50))+ ''',N''' + cast(@Onduty_ToDate as nvarchar(20)) + ''',N''' + CAST(@Onduty_ToTime as nvarchar(50)) + ''',N''' + CAST(@Onduty_Reason as nvarchar(max)) + ''',N''' +CAST(@Onduty_Status as nvarchar(25)) + ''',N''' + CAST(0 as nvarchar(2)) + ''',getdate(),N''' + CAST(@Emp_Id as nvarchar(10)) +''',N''' + CAST(@From_Session as nvarchar(25)) +''',N''' + CAST(@To_Session as nvarchar(25)) +''')'
					EXEC (@sql)	
					select @RETURN_VALUE=MAX(Onduty_ID) from TA_Tbl_OndutyEntry				
					--select @RETURN_VALUE
					--INSERT INTO MANUAL ENTRY TABLE
					BEGIN
						IF (@RETURN_VALUE IS NOT NULL AND @RETURN_VALUE<>'')
						BEGIN
							--SELECT 'ENTEREED'
							IF(@MAXONDUTYID!=@RETURN_VALUE)
							BEGIN
								--SELECT 'ENTEREED Main'
								EXEC [DBO].[PROC_TA_INSERTONDUTYENTRY] @MANUALENTRY_EMPLOYEEID,@MANUALENTRY_DATE,@INDATE,
								@INTIME,@INPUNCHTYPE,@OUTDATE,@OUTTIME,@OUTPUNCHTYPE,@INREADER_ID,@OUTREADER_ID,
								@REASON,@ROUTEID,@STATUS,@USERID,@YEARSETTINGID,@ISONDUTY,@SHIFTID,@SHIFTDATE,@RETURN_VALUE;
								Update TA_Tbl_ManualTimeEntry set IsImported=1 where OnDuty_ID=@RETURN_VALUE
							END
						END
					END
				END
				SET @START=@START+1
			END
			EXEC SP_XML_REMOVEDOCUMENT @XMLPARAMS
			DELETE FROM #TA_TBL_IMPORTONDUTYRECORDS
			SELECT 'MSG:SHIFTIMPORTSUCCESSFULLY' [MESSAGE]
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_ImportOndutyEntry_Eastman]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		<R.MANIKANDAN>
-- CREATE DATE: <06-APRIL-2019>
-- DESCRIPTION:	<IMPORT THE ONDUTY RECORDS INTO DATABASE>
-- 
/*
PROC_IMPORTONDUTYENTRY @ONDUTYDATA ='<DocumentElement>
  <Data>
    <Sl.No>6</Sl.No>
    <EmployeeId>1003</EmployeeId>
    <Date>01-Apr-2019</Date>
    <Reason />
    <flag>1</flag>
    <Errormessage />
    <recordNumber>1</recordNumber>
    <ShiftID>3</ShiftID>
    <Userid>1</Userid>
    <Status>Approved</Status>
  </Data>
</DocumentElement>'
-- =============================================
*/
--drop PROCEDURE [dbo].[Proc_ImportOndutyEntry]
Create PROCEDURE [dbo].[Proc_ImportOndutyEntry_Eastman]
	@ONDUTYDATA XML = NULL
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @XMLPARAMS INT,@YEARSETTINGID INT
	DECLARE @ERRMSG VARCHAR(MAX), @ERRIDS VARCHAR(MAX)	
			EXEC SP_XML_PREPAREDOCUMENT @XMLPARAMS OUTPUT, @ONDUTYDATA
			CREATE TABLE  #TA_TBL_IMPORTONDUTYRECORDS(AUTOID INT IDENTITY(1,1),EMPLOYEE_ID VARCHAR(100), DATE VARCHAR(20),
			REASON VARCHAR(MAX),SHIFTID INT,userid bigint,Status varchar(10))
			INSERT INTO #TA_TBL_IMPORTONDUTYRECORDS
				SELECT TBL.EmployeeId,TBL.Date,case when (TBL.Reason IS null or TBL.Reason='') then 'Onduty' else TBL.Reason end,TBL.ShiftID,TBL.Userid,TBL.Status
				FROM OPENXML (@XMLPARAMS, '/DocumentElement/Data', 2) WITH 
				  (EmployeeId VARCHAR(50),Date VARCHAR(20),Reason VARCHAR(MAX),ShiftID INT,Userid bigint,Status varchar(10)) TBL
				INNER JOIN TA_TBL_EMPLOYEE E ON E.EMPLOYEE_CODE_ID = TBL.EMPLOYEEID
				AND E.ISDELETED = 0 AND E.EMPLOYEE_STATUS = 1
			DECLARE @START INT
			SET @START=1
			DECLARE @TOTALREC INT
			SELECT @TOTALREC =COUNT(*) FROM #TA_TBL_IMPORTONDUTYRECORDS 
			SELECT @YEARSETTINGID = [YEARSETTINGS_ID] FROM [TA_TBL_YEARSETTING] WHERE [ISACTIVE] = 1 
			--SELECT * FROM #TA_TBL_IMPORTONDUTYRECORDS
			WHILE @START<=@TOTALREC
			BEGIN
				---ONDUTY ENTRY TABLE
				BEGIN
				DECLARE @TYPE NVARCHAR(2)
				DECLARE @ONDUTY_ID INT
				DECLARE @ONDUTY_EMPLOYEEID NVARCHAR(20)
				DECLARE @ONDUTY_ENTRYDATE	DATETIME
				DECLARE @ONDUTY_TYPE INT
				DECLARE @INCLUDEWEEKOFF INT
				DECLARE @ONDUTY_FROMDATE DATETIME
				DECLARE @ONDUTY_FROMTIME NVARCHAR(50)
				DECLARE @ONDUTY_TODATE DATETIME
				DECLARE @ONDUTY_TOTIME NVARCHAR(50)
				DECLARE @ONDUTY_REASON NVARCHAR(MAX)
				DECLARE @ONDUTY_STATUS NVARCHAR(25)
				DECLARE @EMP_ID INT
				DECLARE @FROM_SESSION NVARCHAR(25)
				SET @FROM_SESSION =''
				DECLARE @TO_SESSION NVARCHAR(25)
				SET @TO_SESSION =''
				DECLARE @MAXONDUTYID BIGINT
				SELECT @MAXONDUTYID=MAX(ONDUTY_ID) FROM TA_TBL_ONDUTYENTRY
				END
				---MANUAL ENTRY TABLE
				BEGIN
				DECLARE @MANUALENTRY_EMPLOYEEID NVARCHAR(20)
				DECLARE @MANUALENTRY_DATE DATETIME
				DECLARE @INDATE NVARCHAR(15)
				DECLARE @INTIME NVARCHAR(20)
				DECLARE @INPUNCHTYPE NVARCHAR(25)
				DECLARE @OUTDATE NVARCHAR(15)
				DECLARE @OUTTIME NVARCHAR(20)
				DECLARE @OUTPUNCHTYPE NVARCHAR(25)
				DECLARE @INREADER_ID INT
				DECLARE @OUTREADER_ID INT
				DECLARE @REASON NVARCHAR(MAX)
				DECLARE @ROUTEID INT
				DECLARE @STATUS NVARCHAR(25)
				DECLARE @USERID INT
				--DECLARE @YEARSETTINGS_ID NVARCHAR(25)
				DECLARE @ISONDUTY INT
				DECLARE @SHIFTID NVARCHAR(25)
				DECLARE @SHIFTDATE NVARCHAR(15)
				DECLARE @ONDUTYID INT
				END
				--GET VALUE FROM TEMP TABLE
				BEGIN
					SELECT	@TYPE='I',
							@ONDUTY_TYPE=1,
							@MANUALENTRY_EMPLOYEEID=EMPLOYEE_ID,
							@INCLUDEWEEKOFF=0,
							@MANUALENTRY_DATE=CONVERT(VARCHAR(11),GETDATE()),
							@INDATE=DATE,
							@INPUNCHTYPE='IN',
							@OUTDATE=DATE,
							@OUTPUNCHTYPE='OUT',
							@REASON=REASON,
							@ROUTEID=0,
							@STATUS=Status,
							@USERID=userid,
							@ISONDUTY=1,
							@SHIFTID=SHIFTID,
							@SHIFTDATE=DATE,
							@ONDUTYID=0
					FROM #TA_TBL_IMPORTONDUTYRECORDS WHERE AUTOID=@START
				END
				--SHIFT START TIME AND END TIME
				BEGIN
					SELECT @INTIME=SHIFT_STARTTIME,@OUTTIME=SHIFT_ENDTIME FROM TA_TBL_SHIFT WHERE SHIFT_ID=@SHIFTID AND ISDELETED=0
				END
				--IN READER ID
				BEGIN
					SELECT @INREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='787'
				END
				--OUT READER ID
				BEGIN
					SELECT @OUTREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='788'
				END
				--ASSIGN VALUES TO ONDUTY TABLE
				BEGIN
					SELECT @ONDUTY_ID=@ONDUTYID,@ONDUTY_EMPLOYEEID=@MANUALENTRY_EMPLOYEEID,@ONDUTY_ENTRYDATE=@MANUALENTRY_DATE,
					@ONDUTY_FROMDATE=@INDATE,@ONDUTY_FROMTIME=@INTIME,@ONDUTY_TODATE=@OUTDATE,@ONDUTY_TOTIME=@OUTTIME,
					@ONDUTY_REASON=@REASON,@ONDUTY_STATUS=@STATUS,@EMP_ID=@USERID
					--SELECT 
					--@TYPE,@ONDUTY_ID, @ONDUTY_EMPLOYEEID, @ONDUTY_ENTRYDATE, @ONDUTY_TYPE, @INCLUDEWEEKOFF,
					--@ONDUTY_FROMDATE,@ONDUTY_FROMTIME,@ONDUTY_TODATE,@ONDUTY_TOTIME,@ONDUTY_REASON,
					--@ONDUTY_STATUS,@EMP_ID,@FROM_SESSION, @TO_SESSION;					
				END
				--INSERT ONDUTY VALUES
				DECLARE	@RETURN_VALUE bigint
				BEGIN
					DECLARE @sql nvarchar(max)
					SET @sql = ''
					SET @sql = @sql + 'INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FromDate,Onduty_FromTime,Onduty_ToDate
					,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,From_Session,To_Session) 
					VALUES (N'''+ @Onduty_EmployeeID +''',N''' + cast(@Onduty_EntryDate as nvarchar(20)) + ''',N''' +CAST(@Onduty_Type as nvarchar(10)) +''',N''' +CAST(@IncludeweekOff as nvarchar(10)) +''',N''' + cast(@Onduty_FromDate as nvarchar(20) )+ ''',N''' + CAST(@Onduty_FromTime as nvarchar(50))+ ''',N''' + cast(@Onduty_ToDate as nvarchar(20)) + ''',N''' + CAST(@Onduty_ToTime as nvarchar(50)) + ''',N''' + CAST(@Onduty_Reason as nvarchar(max)) + ''',N''' +CAST(@Onduty_Status as nvarchar(25)) + ''',N''' + CAST(0 as nvarchar(2)) + ''',getdate(),N''' + CAST(@Emp_Id as nvarchar(10)) +''',N''' + CAST(@From_Session as nvarchar(25)) +''',N''' + CAST(@To_Session as nvarchar(25)) +''')'
					EXEC (@sql)	
					select @RETURN_VALUE=MAX(Onduty_ID) from TA_Tbl_OndutyEntry				
					--select @RETURN_VALUE
					--INSERT INTO MANUAL ENTRY TABLE
					BEGIN
						IF (@RETURN_VALUE IS NOT NULL AND @RETURN_VALUE<>'')
						BEGIN
							--SELECT 'ENTEREED'
							IF(@MAXONDUTYID!=@RETURN_VALUE)
							BEGIN
								--SELECT 'ENTEREED Main'
								EXEC [DBO].[PROC_TA_INSERTONDUTYENTRY] @MANUALENTRY_EMPLOYEEID,@MANUALENTRY_DATE,@INDATE,
								@INTIME,@INPUNCHTYPE,@OUTDATE,@OUTTIME,@OUTPUNCHTYPE,@INREADER_ID,@OUTREADER_ID,
								@REASON,@ROUTEID,@STATUS,@USERID,@YEARSETTINGID,@ISONDUTY,@SHIFTID,@SHIFTDATE,@RETURN_VALUE;
								Update TA_Tbl_ManualTimeEntry set IsImported=1 where OnDuty_ID=@RETURN_VALUE
							END
						END
					END
				END
				SET @START=@START+1
			END
			EXEC SP_XML_REMOVEDOCUMENT @XMLPARAMS
			DELETE FROM #TA_TBL_IMPORTONDUTYRECORDS
			SELECT 'MSG:SHIFTIMPORTSUCCESSFULLY' [MESSAGE]
END
GO
/****** Object:  StoredProcedure [dbo].[proc_lateEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : proc_lateEntry  
Description : get late entries  
Tables Included : ta_tbl_shift, ta_tbl_processedData, TA_Tbl_Employee
Created By : Kumuthini  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[proc_lateEntry]
	-- Add the parameters for the stored procedure here
(
	@fromDat datetime,
	@ToDat datetime,
	--@empId varchar(100),
	@shift int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	declare @shfTime as dateTime
	set @shfTime = (select Shift_StartTime from ta_tbl_shift where shift_id = @shift)	
	declare @graceTime as decimal
	set @graceTime = (select shift_graceInTime from ta_tbl_shift where shift_id=@shift)
	select @shfTime as shiftIn, dbo.TA_Tbl_Employee.Employee_Code_Id, dbo.TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.InTime,ta_tbl_processeddata.shift_id,
TA_Tbl_ProcessedData.lateIn,dbo.TA_Tbl_Employee.Employee_FirstName FROM  dbo.TA_Tbl_ProcessedData INNER JOIN
                      dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.Employee_Id
			where ta_tbl_processeddata.lateIn <> '00:00:00' and ta_tbl_processedData.lateIn is not null
And     (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, @fromDat, 102)) AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME, 
                      --@todat, 102)) AND (dbo.TA_Tbl_ProcessedData.Employee_Code_Id = @empid) AND 
@todat, 102))  AND 
                      (dbo.TA_Tbl_ProcessedData.InTime >= CONVERT(datetime, @shfTime, 101))and (DATEDIFF(mi, CONVERT(datetime, 
                      @shfTime, 101), dbo.TA_Tbl_ProcessedData.InTime)>@graceTime)
    -- Insert statements for procedure here
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseExpiryDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Gopinath
-- Create date: 7htJuly2014
-- Description:select expiry date from the license expiry table  
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseExpiryDate]
AS
BEGIN
	select expirydate from ta_tbl_lic_details 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Gopinath
-- Create date: <Create Date,,>
-- Description:	select Active and top 1 request ID 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestID]
AS
BEGIN
select top(1) RequestID from TA_Tbl_LicenseRequestDetail where Status=1 order by CreatedDate desc 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	Gopinath
-- Create date: <Create Date,,>
-- Description:	select Active and top 1 request ID 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]
AS
BEGIN
select top(1) RequestID from TA_Tbl_LicenseRequestDetail order by CreatedDate desc 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_OtCalculation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_leveldetails where parentid=0
-- proc_OtCalculation '2015/01/01','2015/12/08','',0,'','1',0,0,'SuperAdmin','','All','',0,0,'Both','OverTime'
-- Modified by : Gopinath
-- Modified Date : 11-Jan-2014
-- Description    :     SQL Query Optimazation & Emp name filtering
-- proc_OtCalculation @fromDat='2022-01-01 00:00:00',@ToDat='2025-05-06 00:00:00',@empId=N'',@shift=0,@EmployeeName=N'',@LevelID=N'1',@employeeCategory=0,@employeeType=0,@UserGroupName=N'Superadmin',@GradeLevel=N'1',@Status=N'All',@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',@SanctionType=N'Overtime',@EmpAutoId=1
CREATE PROCEDURE [dbo].[proc_OtCalculation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)     ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@SanctionType varchar(25),
	@EmpAutoId bigint
)
AS
	BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	SET NOCOUNT ON;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Get Current date time format
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)             
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END   
	--End
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--select * from #LevelRights
	CREATE TABLE #TempProcessedData
	(
		[Process_Rec_ID] bigint,
		[Employee_Code_Id] nvarchar(20),
		[Date] datetime,
		[Shift_Id] int,
		[InTime] nvarchar(25),
		[OutTime] nvarchar(25),
		[HrsWork] nvarchar(10),
		[HrsOT] nvarchar(10),
		[NormOT] nvarchar(10),
		[OffOT] nvarchar(10),
		[HolOT] nvarchar(10),
		[EarlyOut] nvarchar(10),
		[LateIn] nvarchar(10),
		[Attendance] nvarchar(20),
		[WorkHrs] nvarchar(10),
		[HrsLess] nvarchar(10),
		[HrsExtra] nvarchar(10),
		[LateInMins] float,
		[EarlyOutMins] float,
		[ExtraMins] float,
		[OtMins] float,
		[OvertimeStatus] nvarchar(50),
		[TotalDays] numeric(18, 1),
		[LeaveCode] nvarchar(20),
		[LateEntryReason] nvarchar(260),
		[EarlyOutReason] nvarchar(260),
		[ProcessFlag] bit,
		[Status] nvarchar(50),
		[FNAttendanceCode] nvarchar(15),
		[ANAttendanceCode] nvarchar(15),
		[ActHrsOT] nvarchar(10),
		[ActNormOT] nvarchar(10),
		[ActOffOT] nvarchar(10),
		[ActHolOT] nvarchar(10),
		[ActOtMins] float,
		[AvailOtMins] float,
		[ExtraTime_Id] bigint,
		
		-----
				SPEC_NormOT1	varchar(10),
				SPEC_NormOTMins1	int,
				SPEC_NormOT2	varchar(10),
				SPEC_NormOTMins2	int,
				SPEC_OffOT1		varchar(10),
				SPEC_OffOTMins1	int,
				SPEC_OffOT2		varchar(10),
				SPEC_OffOTMins2	int,
				SPEC_HOLOT1		varchar(10),
				SPEC_HOLOTMins1	int,
				SPEC_HOLOT2		varchar(10),
				SPEC_HOLOTMins2	int,			
				
				Modified_Spec_NormOTMins1 int,
				Modified_Spec_NormOTMins2 int,
				Modified_Spec_OffOTMins1 int,
				Modified_Spec_OffOTMins2 int,
				Modified_Spec_HolOTMins1 int,
				Modified_Spec_HolOTMins2 int,
				Modified_Spec_NormOTHrs1 varchar(10),
				Modified_Spec_NormOTHrs2 varchar(10),
				Modified_Spec_OffOTHrs1 varchar(10),
				Modified_Spec_OffOTHrs2 varchar(10),
				Modified_Spec_HolOTHrs1 varchar(10),
				Modified_Spec_HolOTHrs2 varchar(10),
				ExpiryDate datetime
				
	)
	--Employee Level Indexes
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@empId,@DesignationID  
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@empId,@employeeType 
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@empId,@employeeCategory     
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDat,@empId      
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@empId is not null and @empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	IF(@EmployeeName IS NOT NULL AND @EmployeeName <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EmployeeName,',')
		END   
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
	;WITH ParentLevel AS
	(
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
		UNION ALL
		SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
		INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
	)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	ORDER BY lvl DESC
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@TopLevelId
	if(@isRequestCompOff is null or @isRequestCompOff='')
		BEGIN
			select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		END
	Declare @sqlTempProcessedData varchar(8000)    
	set @sqlTempProcessedData=
	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@empId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		END
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'     
	Execute(@sqlTempProcessedData)
	Declare @sqlCommonEmployee_Code_Id nvarchar(1000)
	
	
	if(@isRequestCompOff=0 or @SanctionType = 'OverTime')
		BEGIN
			update TA_Tbl_ProcessedData set 
			OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
			set @sqlTempProcessedData=
			'insert into #TempProcessedData
			select PD.Process_Rec_ID,PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.InTime,PD.OutTime,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.OffOT,PD.HolOT,PD.EarlyOut,
			PD.LateIn,PD.Attendance,PD.WorkHrs,PD.HrsLess,PD.HrsExtra,PD.LateInMins,PD.EarlyOutMins,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.TotalDays,
			PD.LeaveCode,PD.LateEntryReason,PD.EarlyOutReason,PD.ProcessFlag,PD.Status,PD.FNAttendanceCode,PD.ANAttendanceCode,PD.ActHrsOT,PD.ActNormOT,PD.ActOffOT,PD.ActHolOT,PD.ActOtMins,case when ISNULL(ActOTMins,0)=0 then [OtMins] else ActOTMins end,0,
			PD.SPEC_NormOT1,
				PD.SPEC_NormOTMins1,
				PD.SPEC_NormOT2,
				PD.SPEC_NormOTMins2,
				PD.SPEC_OffOT1,
				PD.SPEC_OffOTMins1,
				PD.SPEC_OffOT2,
				PD.SPEC_OffOTMins2,
				PD.SPEC_HOLOT1,
				PD.SPEC_HOLOTMins1,
				PD.SPEC_HOLOT2,
				PD.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2,
				NULL
			from TA_Tbl_ProcessedData as PD inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
			Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
			where (PD.Date >= CONVERT(DATETIME,'''+cast( @fromDat as nvarchar(50))+''', 102)) 
			AND (PD.Date <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102)) and (PD.OtMins <> 0 or ActOTMins <> 0)'
			Execute(@sqlTempProcessedData)
			
		update #TempProcessedData set ExpiryDate=OT.DateToExpired
		from #TempProcessedData TP 
		inner join TA_Tbl_OverTimeStatus OT on TP.Process_Rec_ID=OT.Process_RecID
			
		END
	else
		BEGIN
			set @sqlTempProcessedData=' insert into #TempProcessedData 
			select OT.Process_RecID as ''Process_Rec_ID'',E.Employee_Code_Id,OT.Date,p.Shift_Id,P.InTime,P.OutTime,P.HrsWork,P.HrsOT,P.NormOT,P.OffOT,P.HolOT,p.EarlyOut,p.LateIn,
			p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
			p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id,
			P.SPEC_NormOT1,
			P.SPEC_NormOTMins1,
			P.SPEC_NormOT2,
			P.SPEC_NormOTMins2,
			P.SPEC_OffOT1,
			P.SPEC_OffOTMins1,
			P.SPEC_OffOT2,
			P.SPEC_OffOTMins2,
			P.SPEC_HOLOT1,
			P.SPEC_HOLOTMins1,
			P.SPEC_HOLOT2,
			P.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			DateToExpired
			from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
			inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id  
			Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
			where E.Employee_Code_Id in (
			select SwipeCardNo from TA_Tbl_Employee inner join
			#EmpLevel on #EmpLevel.EmployeeId=E.Employee_Id)
			and P.[Date] between '''+cast( @fromDat as nvarchar(50))+''' and '''+cast(@todat as nvarchar(50))+'''  '
			Execute(@sqlTempProcessedData)
		END
	--select * from #TempProcessedData where OtMins <>0
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''	
	set @sqlQuery = @sqlQuery + 'select E.Employee_Code_Id,
										E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'''') as Employee_FirstName,
										replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],
										replace(Ta_tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
										E.Gender,
										case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, TPD.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
												else CONVERT(VARCHAR, TPD.Date, '+CONVERT(varchar,@dateFormat)+') 
										end  as date,
										TPD.HrsWork,
										ISNULL(TPD.ActNormOT,TPD.NormOt) ActHrsOT,
										TPD.NormOt as HrsOT,
										SPEC_NormOT1,
										Modified_Spec_NormOTHrs1=ISNULL(Modified_Spec_NormOTHrs1,SPEC_NormOT1),
										SPEC_NormOT2,
										Modified_Spec_NormOTHrs2=ISNULL(Modified_Spec_NormOTHrs2,SPEC_NormOT2),
										ISNULL(TPD.ActOffOT,TPD.OffOT) ActOffOT,
										TPD.OffOT,
										SPEC_OffOT1,
										Modified_Spec_OffOTHrs1=ISNULL(Modified_Spec_OffOTHrs1,SPEC_OffOT1),
										SPEC_OffOT2,
										Modified_Spec_OffOTHrs2=ISNULL(Modified_Spec_OffOTHrs2,SPEC_OffOT2),
										ISNULL(TPD.ActHolOT,TPD.HolOT) ActHolOT,
										TPD.HolOT,									
										SPEC_HOLOT1,
										Modified_Spec_HolOTHrs1=ISNULL(Modified_Spec_HolOTHrs1,SPEC_HOLOT1),
										SPEC_HOLOT2,	
										Modified_Spec_HolOTHrs2=ISNULL(Modified_Spec_HolOTHrs2,SPEC_HOLOT2),
										ISNULL(TPD.OverTimeStatus,''Pending'') as OverTimeStatus,
										SPEC_NormOTMins1,
										SPEC_NormOTMins2,
										SPEC_OffOTMins1,
										SPEC_OffOTMins2,
										SPEC_HOLOTMins1,
										SPEC_HOLOTMins2,
										Modified_Spec_NormOTMins1,
										Modified_Spec_NormOTMins2,
										Modified_Spec_OffOTMins1,
										Modified_Spec_OffOTMins2,
										Modified_Spec_HolOTMins1,
										Modified_Spec_HolOTMins2,
										TPD.shift_id,
										ISNULL(ta_tbl_shift.Shift_ShortName,''Off'') as ShiftName, TPD.OtMins,
										CASE WHEN ISNULL(NormOt,''00:00'')=''00:00'' THEN 0 ELSE round(OtMins,0) END as ''NormOTMins'',
										CASE WHEN ISNULL(OffOT,''00:00'')=''00:00''	 THEN 0 ELSE round(OtMins,0) END as ''WeekOffOTMins'',
										CASE WHEN ISNULL(HolOT,''00:00'')=''00:00''  THEN 0 ELSE round(OtMins,0) END as ''HolidayOTMins'', 
										CASE WHEN ISNULL(ActNormOT,NormOT)=''00:00'' THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''ActNormOTMins'',
										CASE WHEN ISNULL(ActOffOT,OffOT)=''00:00''	 THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''ActWeekOffOTMins'',
										CASE WHEN ISNULL(ActHolOT,HolOT)=''00:00''	 THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''ActHolidayOTMins'',
										ISNULL(ActOtMins,OtMins) as ApprovedOTHours,
										(ISNULL(round(ActOtMins,0),round(OtMins,0)) - round(OtMins,0)) as RejectOTHours,										
										0 as SelectedRecords,
										E.SwipeCardNo,			
																	
										ISNULL(TPD.ActOtMins,TPD.OtMins) ActOtMins,
										case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, ExpiryDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
												else CONVERT(VARCHAR,ExpiryDate, '+CONVERT(varchar,@dateFormat)+') 
										end
										[Expiry Date]
	from #TempProcessedData TPD INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.SwipeCardNo'
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on  #EmpType.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' where (TPD.OtMins <> 0 or TPD.ActOtMins <> 0) '
	if(@SanctionType = 'CompOff')
		begin
			set @sqlQuery = @sqlQuery + 'AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 '
		end
	ELSE if(@SanctionType = 'OverTime')
		begin
			set @sqlQuery = @sqlQuery + 'AND E.CompOff_Eligible = 0 AND E.OT_Eligible = 1 '
		end
	if(@UserGroupName<>'SuperAdmin')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END
	if(@isReportingto > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@shift<>0) 
		begin
			set @sqlQuery = @sqlQuery + ' And TPD.Shift_Id=' + cast (@shift as nvarchar(50))  
		end 
	set @sqlQuery = @sqlQuery + ' And E.isdeleted=0 and E.report_exclude=0 and
	((E.employee_status=1)
	or 
	(E.employee_status=0 and convert(nvarchar(11),E.InActiveDate,102)>= convert(nvarchar(11),TPD.Date,102))
	)'
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and E.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end   
	if not(@status='' or @status='All')
		begin
			IF(@status = 'Pending')
				BEGIN
					set @sqlQuery = @sqlQuery + ' AND (TPD.OvertimeStatus IS NULL OR TPD.OvertimeStatus = ''' + @status + ''')'
				END
			ELSE
				BEGIN
					set @sqlQuery = @sqlQuery + ' AND TPD.OvertimeStatus = ''' + @status + ''''
				END
		end 
	set @sqlQuery = @sqlQuery + ' order by Employee_Code_Id,convert(datetime,TPD.Date)'
	--print(@sqlQuery)	
	exec (@sqlQuery)	
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempProcessedData
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_SelectWeekday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_SelectWeekday 'superadmin',1,'',''
--	Modified By		:	Manjula.P
--	Modified On		:	09-Apr-2014
--	DEscriptinos	:	Adding @ParentId,@FromDate,@ToDate parameters for Searching purpose in temp weekday
CREATE   PROCEDURE [dbo].[Proc_SelectWeekday]
	@userGroupName nvarchar(50),
	@ParentId int=0,
	@FromDate varchar(20)='01/01/1900',
	@ToDate varchar(20)='01/01/9999'
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	declare @SQLQuery as nvarchar(max);
	declare @LevelIds as varchar(250)
	create table #Temp
	(
	LevelId varchar(250)
	)
	insert into #Temp
	select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	select @LevelIds=  COALESCE(@LevelIds + ',', '') + LevelId FROM #Temp;
	--select * from #Temp
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	declare @Query nvarchar(max);
	--Added by Manjula.P on 09-Apr-2014 for levelwise and Date wise Search
	declare @WhereQuery nvarchar(500)
	declare @OrderByQuery nvarchar(max)
	set @Query='';
	set @WhereQuery='';
	--SET @LevelIds=@ParentId
	--********************************************************************
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	if(@userGroupName='SuperAdmin')
		begin
			if(@ParentId<=0)
			begin	
				set @Query=' SELECT T.tempWeekday_Id,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'' '',''-'') 			
				else CONVERT(VARCHAR, tempWeekday_FromDate, '+cast(@dateFormat as varchar(100))+') end as TempWeekday_FromDate,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, '+cast(@dateFormat as varchar(100))+') end 			
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id '				
				set @WhereQuery=' where LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','','')) '
				set @OrderByQuery=' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted '
			end
			else
			begin
				set @Query=' SELECT T.tempWeekday_Id,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'' '',''-'') 			
				else CONVERT(VARCHAR, tempWeekday_FromDate, '+cast(@dateFormat as varchar(100))+') end as TempWeekday_FromDate,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, '+cast(@dateFormat as varchar(100))+') end 			
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_TemWeekday T
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id '
				set @WhereQuery=' where LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','','')) '
				set @OrderByQuery=' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted '
			end			
		end
	else
		begin
			if(@ParentId<=0)
			begin
				set @Query =' SELECT T.tempWeekday_Id,case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_FromDate, '+cast(@dateFormat as varchar(100))+') end as TempWeekday_FromDate,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, '+cast(@dateFormat as varchar(100))+') end
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id '				
				set @WhereQuery=' where IsDeleted = 0 and LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','',''))'	
				set @OrderByQuery=' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted '
			end
			else
			begin
				set @Query=' SELECT T.tempWeekday_Id,case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_FromDate, '+cast(@dateFormat as varchar(100))+') end as TempWeekday_FromDate,
				case when '+cast(@dateFormat as varchar(100))+'=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'' '',''-'') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, '+cast(@dateFormat as varchar(100))+') end
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id '
				set @WhereQuery=' where IsDeleted = 0 and LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','','')) '	
				set @OrderByQuery=' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted '
			end
		end
	if(isnull(@FromDate,'')<>'' and isnull(@ToDate,'')<>'')
	begin
		if(@WhereQuery!='')
			begin
				set @WhereQuery=@WhereQuery + ' and TempWeekday_FromDate>='''+cast(@FromDate as nvarchar(20))+''' and TempWeekday_ToDate<='''+cast(@ToDate as nvarchar(20))+''' '
			end
			else
			begin
				set @WhereQuery=@WhereQuery + ' where TempWeekday_FromDate>='''+cast(@FromDate as nvarchar(20))+''' and TempWeekday_ToDate<='''+cast(@ToDate as nvarchar(20))+''' '
			end
	end
	SET @Query=@Query+@WhereQuery+@OrderByQuery
	--+@OrderByQuery;
	exec(@Query); 
	DROP TABLE #Temp
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	06-SEP-2013
-- Description	:	Import the Employees
-- EXEC [Proc_TA_ActivateEmployeeBasedOnLicence] '1000'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]
	@EmployeeCount VARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @EmpIdTbl TABLE(Employee_Id INT)
	DECLARE @Query VARCHAR(MAX) 
	Declare @Deleted int	
	IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
	SET @EmployeeCount = (CASE WHEN ISNULL(@EmployeeCount, '') = '' THEN '0' ELSE @EmployeeCount END)
	--SET @Query = 'SELECT TOP ' + @EmployeeCount + ' Employee_Id FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND Isdeleted = 1 AND Employee_Code_Id <> ''18000000'''
	UPDATE TA_Tbl_Employee SET	
		Isdeleted = 1
		--Commented By Manikandan.R. while updating the license, inactive employees are activating automatically.
		--,
		--Report_Exclude = 0,
		--Employee_Status = 0,
		--InActiveDate = DATEADD(D, 1, DateOfJoining)
	WHERE Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
	INSERT INTO @EmpIdTbl
		SELECT TOP (CAST(@EmployeeCount AS BIGINT)) Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 1 	
		AND Employee_Code_Id <> '18000000' AND ISNULL(Isdeleted_Status, 0) = 0
		ORDER BY Employee_Id
	UPDATE TA_Tbl_Employee SET	Isdeleted = 0
		--Commented By Manikandan.R. while updating the license, inactive employees are activating automatically.
		--,
		--Report_Exclude = 0,
		,Employee_Status = 1
		--,--InActiveDate = NULL
	FROM TA_Tbl_Employee E
	INNER JOIN @EmpIdTbl TE ON TE.Employee_Id = E.Employee_Id
	WHERE ISNULL(InActive_Status, 0) = 0
	Declare @SQLQuery varchar(max)
	set @SQLQuery=''
	if @Deleted=1
		begin
			Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActiveEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_ActiveEmployeeDetails  
Description : select active employee details 
Tables Included : TA_Tbl_Employee  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007
Modified By : Kumuthini.L
Modified On :19-Feb-2008
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_ActiveEmployeeDetails] 
 AS
BEGIN
	SELECT Employee_Id,Employee_Code_Id,SwipeCardNo,OT_Eligible,EmailId  FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND IsDeleted = 0
	AND Employee_Firstname <> 'Administrator'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author		: Kumuthini
-- Created  Date        : 13-Jan-09   
-- Proc_TA_AddUpdateEmployeeBonusLeave 1,2,5,6
-- Description:	Add or Update Employee Bonus Leave Details
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]
(
	@YearSettingId int,	
	@EmployeeId int,
	@BonusLeaveQuota int = 0,
	@EmpId int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Count AS int
	SELECT @Count = COUNT(*) FROM TA_Tbl_EmployeeBonusLeave WHERE YearSettingId = @YearSettingId AND EmployeeId = @EmployeeId
	IF(@Count >= 1)
	BEGIN
		UPDATE TA_Tbl_EmployeeBonusLeave SET BonusLeaveQuota = @BonusLeaveQuota,EmpId = @EmpId WHERE YearSettingId = @YearSettingId AND EmployeeId = @EmployeeId
	END
	ELSE
	BEGIN
		INSERT INTO TA_Tbl_EmployeeBonusLeave(YearSettingId,EmployeeId,BonusLeaveQuota,EmpId) VALUES (@YearSettingId,@EmployeeId,@BonusLeaveQuota,@EmpId)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllActiveEmployees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Proc [dbo].[Proc_TA_AllActiveEmployees]
As
	begin
		Select * from TA_Tbl_Employee where Employee_Firstname<>'Administrator'  and Isdeleted=0
	end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllEmployees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_AllEmployees  
Description : To get all the Employee without Filter Condition  
Tables Included : TA_Tbl_Employee  
Created By : Abul  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE  Proc [dbo].[Proc_TA_AllEmployees]
@LevelID int
As
Select * from TA_Tbl_Employee where Employee_Firstname<>'Administrator' 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllocateWeekOff_AutoShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AllocateWeekOff_AutoShift]
AS
BEGIN
	SET NOCOUNT ON;
	Declare @StartDate datetime
	Declare @EndDate datetime
	Declare @AddYear int
	Declare @WeeklyOff1 varchar(20)
	Declare @WeeklyOff2 varchar(20)
	Declare @WeeklyOff3 varchar(20)

	---Default Values
	set @AddYear=10
	set @WeeklyOff1='Sunday'
	set @WeeklyOff2='Saturday'
	set @WeeklyOff3=''

	--set @StartDate=CONVERT(varchar(11),dateadd(month,-1,GETDATE()))
	--set @EndDate=DATEADD(YEAR,@AddYear,@StartDate)
	
	--select @StartDate,@EndDate
	set @StartDate='20191215'
	set @EndDate=getdate();
	--select @StartDate,@EndDate
	
	Create table #TempWeekOffDays(weekoffid int identity(1,1),start datetime,weekdayName varchar(20),MonthValue int,yearValue int,datevalue int)
	;with cte
	as
	(
		select DATEADD(d,0,@startdate) as start,datename(dw,DATEADD(d,0,@startdate)) as weekday
		union all
		select DATEADD(d,1,start),datename(WEEKDAY,DATEADD(d,1,start)) as weekday from cte where @EndDate>=DATEADD(d,1,start) 
	)
	Insert into #TempWeekOffDays
	select start,Weekday,MonthValue=DATEPART(month,start),yearValue=DATEPART(year,start),DATEPART(d,start) from cte where weekday in(@WeeklyOff1,@WeeklyOff2,@WeeklyOff3)
	and start is not null
	option(maxrecursion 0);
	--select * from #TempWeekOffDays

	Declare @TotalDaysCount int
	Declare @Startloop int
	set @Startloop=1
	select @TotalDaysCount=COUNT(weekoffid) from #TempWeekOffDays
	
	Create table #TempEmployee(id int identity(1,1),EmpAutoID int)
	Insert into #TempEmployee
	select Employee_Id from ta_tbl_employee

	while @TotalDaysCount>=@Startloop
	begin
		Declare @Dynamic_InsertQuery varchar(max)
		Declare @insertMonth varchar(10)
		Declare @insertYear varchar(10)
		Declare @insertDate varchar(10)
		Select @insertMonth=MonthValue,@insertYear=yearValue,@insertDate=datevalue from #TempWeekOffDays where weekoffid=@Startloop
		--select @insertMonth,@insertYear,@insertDate
		Declare @EmployeeCount int
		Declare @startEmpLoop int
		set @startEmpLoop=1
		select @EmployeeCount=count(*) from #TempEmployee
		while @EmployeeCount>=@startEmpLoop
		begin
			Declare @EmpAutoID varchar(20)
			set @EmpAutoID=''
			select @EmpAutoID=EmpAutoID from #TempEmployee where id=@startEmpLoop
			if not exists(select * from TA_Tbl_PermanentShiftAllocation where EmployeeId=@EmpAutoID and Month=@insertMonth and year=@insertYear)
			BEGIN
				--print 's'
				insert into TA_Tbl_PermanentShiftAllocation (employeeid,year,Month,Emp_Id,DateShift) values(@EmpAutoID,@insertYear,@insertMonth,1,convert(varchar(20),@insertYear)+'-'+CONVERT(varchar(20),@insertMonth)+'-01')

				set @Dynamic_InsertQuery = ' UPDATE TA_TBL_PERMANENTSHIFTALLOCATION SET DAY'
				set @Dynamic_InsertQuery = @Dynamic_InsertQuery + @insertDate +'shift=-1 where EmployeeId='+@EmpAutoID +' and Month='+@insertMonth +' and Year='+@insertYear
				Execute(@Dynamic_InsertQuery)
			END
			else
			begin
				set @Dynamic_InsertQuery = ' UPDATE TA_TBL_PERMANENTSHIFTALLOCATION SET DAY'
				set @Dynamic_InsertQuery = @Dynamic_InsertQuery + @insertDate +'shift=-1 where EmployeeId='+@EmpAutoID +' and Month='+@insertMonth +' and Year='+@insertYear
				Execute(@Dynamic_InsertQuery)
			end
			set @startEmpLoop=@startEmpLoop+1
		end		
		set @Startloop=@Startloop+1
	end
	--select * from #TempWeekOffDays
	drop table #TempWeekOffDays
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ApexChartEmployeeLeaveDetail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_ApexChartEmployeeLeaveDetail] 

		 @FromDate Nvarchar(50)='01-JAN-2024',@Tag nvarchar(50)='Admin',@Employee_Id int='1'
AS
BEGIN
	
	
	if(@FromDate ='')
	begin 

	Select @FromDate=StartYear from TA_Tbl_YearSetting where IsActive =1

	end
	Declare @InYear varchar(4) = DATEPART(YEAR, @FromDate) 
	Declare @FromD Nvarchar(50) 
	Declare @ToD Nvarchar(50)
	set @FromD= @InYear+'-'+'1'+'-'+'1'
	Set @ToD = @InYear+'-'+'12'+'-'+'31'
	Print @FromD
	print @ToD

CREATE TABLE #Calendar (CalendarDate DATE)

DECLARE @StartDate DATE = @FromD
DECLARE @EndDate DATE = @ToD

WHILE @StartDate <= @EndDate
BEGIN
    INSERT INTO #Calendar (CalendarDate) VALUES (@StartDate)
    SET @StartDate = DATEADD(DAY, 1, @StartDate)
END

-- Count leave applications by month
SELECT DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1) AS LeaveMonth,
       COUNT(la.Leave_ApplicationDate) AS LeaveCount into #TempMonth
FROM #Calendar c
LEFT JOIN TA_Tbl_LeaveApplication la ON c.CalendarDate = la.Leave_ApplicationDate
WHERE c.CalendarDate BETWEEN @FromD AND @ToD
GROUP BY DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1)
--ORDER BY LeaveMonth

Declare @YearSetting Nvarchar(10)
if(@FromDate='')
begin

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where IsActive =1
end 
else
begin 

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where StartYear = @InYear

end


Select  Count(*)as EmployeeCount into #EmployeeCount
from TA_Tbl_Employee where InActive_Status = 0


SELECT 
   DATENAME(MONTH, DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1)) AS Leave_ApplicationMonths,
   Convert(int, SUM(NumberOfDays)/#EmployeeCount.EmployeeCount * 100 ) AS [Leave Percentage from over all strength for a month] into #tempMonthlyLeaveCount
FROM TA_Tbl_LeaveApplication
cross Join #EmployeeCount
WHERE 
    (Leave_ApplicationDate BETWEEN @FromD AND @ToD) and Status ='Approved'	and IsDeleted=0
	and Employee_Id =case when @Employee_Id ='1' then TA_Tbl_LeaveApplication.Employee_Id  else @Employee_Id end 
    OR (Leave_ApplicationDate IS NULL) 
    OR (NumberOfDays = 0 )
GROUP BY 
    DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1) ,#EmployeeCount.EmployeeCount
--ORDER BY 
--    Leave_ApplicationMonths;



DECLARE @newTableName NVARCHAR(MAX) = 'TA_Tbl_NewChartGridTable';
DECLARE @columns NVARCHAR(MAX), @query NVARCHAR(MAX);

-- Get distinct Leave_Type values to use as columns for pivoting
SELECT @columns = COALESCE(@columns + ', ', '') + QUOTENAME(Type)
FROM (
    SELECT DISTINCT Type
    FROM TA_Tbl_LeaveApplication
) AS LeaveTypes;

-- Dynamic SQL to pivot the data
SET @query = '
SELECT Month, ' + @columns + '
INTO ' + @newTableName + ' -- Create a new table
FROM (
    SELECT DATENAME(MONTH,Leave_ApplicationDate) AS Month, Type AS Leave_Type, NumberOfDays 
    FROM TA_Tbl_LeaveApplication
    WHERE Leave_ApplicationDate BETWEEN @FromD AND @ToD and Status =''Approved'' and 
	Employee_Id =case when @Employee_Id =''1'' then TA_Tbl_LeaveApplication.Employee_Id  else @Employee_Id end 
) AS SourceData
PIVOT (
    SUM(NumberOfDays)
    FOR Leave_Type IN (' + @columns + ')
) AS PivotTable
';
--ORDER BY Month;
-- Execute the dynamic SQL query
EXEC sp_executesql @query, N'@FromD DATETIME, @ToD DATETIME,@Employee_Id Int', @FromD, @ToD,@Employee_Id;

Select DATENAME(MONTH,DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1))AS ApplicationMonth,
Sum(NumberOfDays)as [Total Leaves Taken Per month] into #TempTotalLeave
from TA_Tbl_LeaveApplication
WHERE Leave_ApplicationDate BETWEEN @FromD AND @ToD and Status ='Approved'
and Employee_Id =case when @Employee_Id ='1' then TA_Tbl_LeaveApplication.Employee_Id  else @Employee_Id end 
    OR Leave_ApplicationDate IS NULL
    OR NumberOfDays = 0 
GROUP BY DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1)
--ORDER BY ApplicationMonth;


Select Convert(Datetime,'1-'+ TL.ApplicationMonth+'-2023') as Dates,TC.Leave_ApplicationMonths +'-'+@InYear as Leave_ApplicationMonths ,NT.*,#EmployeeCount.EmployeeCount,TL.[Total Leaves Taken Per month],
TC.[Leave Percentage from over all strength for a month] 
--into #TempLeaves
from TA_Tbl_NewChartGridTable NT
cross Join #EmployeeCount
Left Join #TempTotalLeave TL on TL.ApplicationMonth = NT.Month
inner JOin #tempMonthlyLeaveCount TC on TC.Leave_ApplicationMonths = NT.Month
order by Dates ASC



Drop table #tempMonthlyLeaveCount
Drop Table TA_Tbl_NewChartGridTable
Drop Table #EmployeeCount

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ApexChartEmployeeLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[Proc_TA_ApexChartEmployeeLeaveDetails]

  @FromDate Nvarchar(50)='February-2022' ,@Employee_Id Nvarchar(50) =''
AS
BEGIN

 --declare @FromDate Nvarchar(50)='Nov-2023'
 
declare @EmployeeCode nvarchar(100) , @DateFormate nvarchar(100),@FromatCode int 
Select @DateFormate=DateFormat from TA_Tbl_DateandTimeFormat
	print @DateFormate

	if (@DateFormate ='MM/dd/yyyy')
	begin 
	print @DateFormate
	 set @FromatCode =110
	end 
	else if (@DateFormate ='dd-MMM-yyyy')
	 begin
	 print @DateFormate

	 set @FromatCode =106
	 end 
	 else if (@DateFormate ='dd/MM/yyyy')
	 begin 
	 print @DateFormate
	 set @FromatCode =105
	 end 
	 declare @FromD datetime
	 declare @Todate datetime

	-- Convert(varchar,Convert(date, Trnsfr_From),@FromatCode)
	if('February'=SUBSTRING(@FromDate, 0, 9))
	begin 
	set  @FromD  =Convert( Datetime, '1'+'-'+@FromDate)
	Set @Todate  =Convert( Datetime, '28'+'-'+@FromDate)
	end 
	else
	begin 
	Set @FromD  =Convert( Datetime, '1'+'-'+@FromDate)
	Set @Todate  =Convert( Datetime, '30'+'-'+@FromDate)
	end 
	print SUBSTRING(@FromDate, 0, 9)

	
	Print @FromD
	
	
	Select TA_Tbl_Employee.Employee_Code_Id,
	TA_Tbl_Employee.Employee_FirstName + TA_Tbl_Employee.Employee_MiddleName+TA_Tbl_Employee.Employee_LastName as EmployeeName,
	 Convert(varchar,Convert(date,Leave_ApplicationDate),@FromatCode)as Leave_ApplicationDate,
	 Convert(varchar,Convert(date,Leave_FromDate),@FromatCode) as Leave_FromDate
	 ,Convert(varchar,Convert(date,Leave_ToDate),@FromatCode) as Leave_ToDate,NumberOfDays from TA_Tbl_LeaveApplication 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id =TA_Tbl_LeaveApplication.Employee_Id
	where Leave_ApplicationDate between @FromD  and @Todate
	and TA_Tbl_Employee.Employee_Id = case when @Employee_Id = '1' then TA_Tbl_Employee.Employee_Id else @Employee_Id end 

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_API_InsertHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*

exec Proc_TA_API_InsertHoliday @Type='I',@HolidayId=0,@HolidayType='G',@Holiday_FromDate='2024-10-31 00:00:00',
@Holiday_Todate='2024-10-31 00:00:00',@Holiday_Description=N'Diwali',@YearSettings_Id=N'0',@CompanyNameLevel='MK industries'

*/


CREATE PROCEDURE [dbo].[Proc_TA_API_InsertHoliday] 
(
	@Type char(1),
	@HolidayId int=0,
	@HolidayType char(1),
	@Holiday_FromDate datetime,
	@Holiday_Todate datetime,
	@Holiday_Description nvarchar(255),
	@YearSettings_Id nvarchar(25),
	@CompanyNameLevel Nvarchar(Max)=0

)
as
	declare @sql as nvarchar(3000)
	declare @Isdeleted bit
	set @Isdeleted=0
	--Declare @LevelId int
	--set @LevelId=0
   --Insert Method
	if(@Type='I')
		begin
		Declare @YearSettingID nvarchar(50)
		declare @HolidayIDForAPI Nvarchar(10)

			Select @YearSettingID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1

			INSERT INTO TA_Tbl_Holiday(Holiday_Type,Holiday_FromDate,Holiday_ToDate,Holiday_Description,YearSettings_Id,
			Isdeleted,Emp_Id,LevelId) Values (@HolidayType,cast(@Holiday_FromDate as nvarchar(25)),cast(@Holiday_Todate as nvarchar(25)),
			@Holiday_Description,@YearSettingID,@Isdeleted,1,0)


				Select @HolidayIDForAPI = MAX(Holiday_Id) from TA_Tbl_Holiday
				
				-- Select the ids from Ta_Tbl_levelDetails where parentId = 0
				declare @LevelIdTable table (id int)
				

				if(@CompanyNameLevel !='')
				begin 
				declare @AddParentId int 
				Select @AddParentId=id from Ta_Tbl_levelDetails where name Like @CompanyNameLevel

					
				;WITH RecursiveCTE AS (
				    -- Anchor member: Select the parent row with id = 9
				    SELECT id, levelId, parentId, name
				    FROM Ta_Tbl_levelDetails
				    WHERE id = @AddParentId
				
				    UNION ALL
				
				    -- Recursive member: Select rows where parentId matches the id from the previous level
				    SELECT t.id, t.levelId, t.parentId, t.name
				    FROM Ta_Tbl_levelDetails t
				    INNER JOIN RecursiveCTE r
				    ON t.parentId = r.id
				)
				-- Final result: Get all parent and child rows
				insert into @LevelIdTable 
				SELECT id
				FROM RecursiveCTE
				ORDER BY levelId, id;

				end 
				else
				begin

				insert into @LevelIdTable 
				Select id from Ta_Tbl_levelDetails 

				end

				-- Loop through each id and insert into Ta_Tbl_levelDetails with the HolidayID
				declare @CurrentId int
				
				while exists (select top 1 id from @LevelIdTable)
				begin
				    -- Get the top id from the table
				    select top 1 @CurrentId = id from @LevelIdTable
				
				    -- Insert the current id and the HolidayID into the Ta_Tbl_levelDetails
				    Insert into TA_Tbl_HolidayChildTable (LevelId,Holiday_Id ) 
				    Values (@CurrentId, @HolidayIDForAPI)
				
				    -- Remove the inserted id from the temporary table
				    delete from @LevelIdTable where id = @CurrentId
				end
				
	end



GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		<Velumani P>
-- CREATE DATE: <15/7/2019>
-- DESCRIPTION:	<THIS PROCEDURE WORKS FOR LATEIN AND EARLY OUT - attendance Updation>
-- =============================================
--PROC_TA_AttendanceUpdationBasedOnLateIn '2020/12/01 00:00:00.000','5',1
--THIS PROCEDURE WORKS FOR 2 CASES . ONE IS LATEIN AND ANOTHER ONE IS EARLY OUT
CREATE PROCEDURE [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]
 @SHIFTDATE DATETIME,
 @EMPLOYEECODEID NVARCHAR(40),
 @COMPANYID INT
AS
BEGIN
	SET NOCOUNT OFF;
	--VARIABLES FOR LATE IN --
	DECLARE @LATEMINSPERDAY INT
	DECLARE @LATEDAYSPERMONTH INT	
	DECLARE @LATECOUNT INT
	DECLARE @ODDEVENDECIDER INT
	DECLARE @FROMDATE DATETIME
	DECLARE @TODATE DATETIME
	--VARIABLES FOR EARLY OUT--
	DECLARE @EARLYOUTMINSPERDAY INT
	DECLARE @EARLYOUTDAYSPERMONTH INT	
	DECLARE @EARLYOUTCOUNT INT
	DECLARE @EARLYOUTODDEVENDECIDER INT
		--GETTING COMPANY CONFIGURED LATEIN MINUTES VALUE--
	SELECT @LATEMINSPERDAY =  ISNULL(LATEMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	SELECT @LATEDAYSPERMONTH =   ISNULL(LATEDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	Declare @ShiftSecondHalf_Time datetime
	Declare @Shift_FirstHalf_EndTime datetime
	Declare @intime datetime
	Declare @outtime datetime
	Declare @shift_id int
	Declare @diff int			
	SELECT @shift_id= Shift_Id,@intime=InTime,@outtime=OutTime FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID 
	select @ShiftSecondHalf_Time=Shift_SecondHalf_StartTime,@Shift_FirstHalf_EndTime =Shift_FirstHalf_EndTime from TA_Tbl_Shift where shift_id=@shift_id
	--CHECKING LATEIN MINTES PER DAY CASE --
	IF(@LATEMINSPERDAY !=0)
	BEGIN
		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY AND FNATTENDANCECODE='PRESENT')
		BEGIN
			UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND FNATTENDANCECODE='PRESENT'	
		END
		ELSE
		BEGIN			
			if(CONVERT(datetime,@intime)>convert(datetime,@ShiftSecondHalf_Time))
			BEGIN
				set @diff=DATEDIFF(minute,@intime,@ShiftSecondHalf_Time)
				if(@diff>=@LATEMINSPERDAY)
				begin
					UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND ANATTENDANCECODE = 'PRESENT'
				end
			END
		END
	END
	--CHECKING LATEIN DAYS PER MONTH CASE --
	-- 2 CASES HERE, @LATEMINSPERDAY MAY BE  >0 , @LATEMINSPERDAY = 0
	--CASE 1 LATEMINTS PER DAY IS > 0 
	IF(@LATEDAYSPERMONTH !=0)
	BEGIN	
		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
		IF(@LATEMINSPERDAY > 0)
		BEGIN
			SET @LATECOUNT=0;
			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (LATEINMINS <= @LATEMINSPERDAY) and (LATEINMINS > 0)
			IF(@LATECOUNT > @LATEDAYSPERMONTH)
			BEGIN
				SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
				IF(@ODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY) AND FNATTENDANCECODE='PRESENT' and (LATEINMINS > 0))
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND FNATTENDANCECODE='PRESENT' and (LATEINMINS > 0)
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND ANATTENDANCECODE = 'PRESENT' and (LATEINMINS > 0)
					END
				END	
			END		
		END
			--CASE 2 LATEMINTS PER DAY IS = 0 
		ELSE IF(@LATEMINSPERDAY = 0)
		BEGIN
			SET @LATECOUNT=0;
			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND LATEINMINS > 0
			IF(@LATECOUNT > @LATEDAYSPERMONTH)
			BEGIN
				SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
				IF(@ODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0 AND FNATTENDANCECODE='PRESENT')
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND FNATTENDANCECODE='PRESENT'	
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND ANATTENDANCECODE = 'PRESENT'
					END
				END	
			END		
		END
	END
	--EARLY OUT STARTS HERE--
	--GETTING COMPANY CONFIGURED EARLY OUT MINUTES VALUE--
	SELECT @EARLYOUTMINSPERDAY =  ISNULL(EARLYEXITMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	SELECT @EARLYOUTDAYSPERMONTH =   ISNULL(EARLYEXITDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	--CHECKING LATEIN MINTES PER DAY CASE --
	IF(@EARLYOUTMINSPERDAY !=0)
	BEGIN
		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY AND ANATTENDANCECODE='PRESENT')
		BEGIN
			UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND ANATTENDANCECODE='PRESENT'	
		END
		ELSE
		BEGIN
			if(CONVERT(datetime,@outtime)<convert(datetime,@Shift_FirstHalf_EndTime))
			BEGIN
				set @diff=DATEDIFF(minute,@outtime,@Shift_FirstHalf_EndTime)
				if(@diff>=@EARLYOUTMINSPERDAY)
				begin
					UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND FNATTENDANCECODE = 'PRESENT' 
				end
			end
			--and ANATTENDANCECODE = 'ABSENT'
		END
	END
	--CHECKING EARLY OUT DAYS PER MONTH CASE --
	-- 2 CASES HERE, @EARLYOUTMINSPERDAY MAY BE  >0 , @EARLYOUTMINSPERDAY = 0
	--CASE 1 EARLY OUT  PER DAY IS > 0 
	IF(@EARLYOUTDAYSPERMONTH !=0)
	BEGIN	
		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
		IF(@EARLYOUTMINSPERDAY > 0)
		BEGIN
			SET @EARLYOUTCOUNT=0;
			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) and (EARLYOUTMINS > 0)
			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
			BEGIN
				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;		
				IF(@EARLYOUTODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) AND ANATTENDANCECODE='PRESENT' and (EARLYOUTMINS > 0 ))
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND ANATTENDANCECODE='PRESENT'	and (EARLYOUTMINS > 0 )
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND FNATTENDANCECODE = 'PRESENT' and (EARLYOUTMINS > 0 )
					END
				END	
			END		
		END
			--CASE 2 EARLY OUT PER DAY IS = 0 
		ELSE IF(@EARLYOUTMINSPERDAY = 0)
		BEGIN
			SET @EARLYOUTCOUNT=0;
			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND EARLYOUTMINS > 0
			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
			BEGIN
				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;	
				IF(@EARLYOUTODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0 AND ANATTENDANCECODE='PRESENT')
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND ANATTENDANCECODE='PRESENT'	
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND FNATTENDANCECODE = 'PRESENT'
					END
				END	
			END		
		END
	END
---Below is the vaighai Agro client uncomment below line of coding and comment the coding above.
	
--	BEGIN
--	SET NOCOUNT OFF;
--	--VARIABLES FOR LATE IN --
--	DECLARE @LATEMINSPERDAY INT
--	DECLARE @LATEDAYSPERMONTH INT	
--	DECLARE @LATECOUNT INT
--	DECLARE @ODDEVENDECIDER INT
--	DECLARE @FROMDATE DATETIME
--	DECLARE @TODATE DATETIME
--	--VARIABLES FOR EARLY OUT--
--	DECLARE @EARLYOUTMINSPERDAY INT
--	DECLARE @EARLYOUTDAYSPERMONTH INT	
--	DECLARE @EARLYOUTCOUNT INT
--	DECLARE @EARLYOUTODDEVENDECIDER INT
--		--GETTING COMPANY CONFIGURED LATEIN MINUTES VALUE--
--	SELECT @LATEMINSPERDAY =  ISNULL(LATEMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
--	SELECT @LATEDAYSPERMONTH =   ISNULL(LATEDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
--	--CHECKING LATEIN MINTES PER DAY CASE --
--	IF(@LATEMINSPERDAY !=0)
--	BEGIN
--		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY AND FNATTENDANCECODE='PRESENT')
--		BEGIN
--			UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND FNATTENDANCECODE='PRESENT'	
--		END
--		ELSE
--		BEGIN
--			UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND ANATTENDANCECODE = 'PRESENT'
--		END
--	END
--	--CHECKING LATEIN DAYS PER MONTH CASE --
--	-- 2 CASES HERE, @LATEMINSPERDAY MAY BE  >0 , @LATEMINSPERDAY = 0
--	--CASE 1 LATEMINTS PER DAY IS > 0 
--	IF(@LATEDAYSPERMONTH !=0)
--	BEGIN	
--		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
--		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
--		IF(@LATEMINSPERDAY > 0)
--		BEGIN
--			SET @LATECOUNT=0;
--			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
--			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
--			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (LATEINMINS <= @LATEMINSPERDAY) and (LATEINMINS > 0)
--			IF(@LATECOUNT > @LATEDAYSPERMONTH)
--			BEGIN
--				--As per client requisition commented below line of coding on 02-Feb-2020. After reaching the count, next late in days lop need to be updated.
--				--SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
--				--IF(@ODDEVENDECIDER = 0)
--				--BEGIN
--					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY) AND FNATTENDANCECODE='PRESENT' and (LATEINMINS > 0))
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND FNATTENDANCECODE='PRESENT' and (LATEINMINS > 0)
--					END
--					ELSE
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND ANATTENDANCECODE = 'PRESENT' and (LATEINMINS > 0)
--					END
--				--END	
--			END		
--		END
--			--CASE 2 LATEMINTS PER DAY IS = 0 
--		ELSE IF(@LATEMINSPERDAY = 0)
--		BEGIN
--			SET @LATECOUNT=0;
--			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
--			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
--			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND LATEINMINS > 0
--			IF(@LATECOUNT > @LATEDAYSPERMONTH)
--			BEGIN
--				--As per client requisition commented below line of coding on 02-Feb-2020. After reaching the count, next late in days lop need to be updated.
--				--SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
--				--IF(@ODDEVENDECIDER = 0)
--				--BEGIN
--					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0 AND FNATTENDANCECODE='PRESENT')
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND FNATTENDANCECODE='PRESENT'	
--					END
--					ELSE
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND ANATTENDANCECODE = 'PRESENT'
--					END
--				--END	
--			END		
--		END
--	END
--	--EARLY OUT STARTS HERE--
--	--GETTING COMPANY CONFIGURED EARLY OUT MINUTES VALUE--
--	SELECT @EARLYOUTMINSPERDAY =  ISNULL(EARLYEXITMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
--	SELECT @EARLYOUTDAYSPERMONTH =   ISNULL(EARLYEXITDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
--	--CHECKING LATEIN MINTES PER DAY CASE --
--	IF(@EARLYOUTMINSPERDAY !=0)
--	BEGIN
--		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY AND ANATTENDANCECODE='PRESENT')
--		BEGIN
--			UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND ANATTENDANCECODE='PRESENT'	
--		END
--		ELSE
--		BEGIN
--			UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='Absent' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND FNATTENDANCECODE = 'PRESENT' 
--			--and ANATTENDANCECODE = 'ABSENT'
--		END
--	END
--	--CHECKING EARLY OUT DAYS PER MONTH CASE --
--	-- 2 CASES HERE, @EARLYOUTMINSPERDAY MAY BE  >0 , @EARLYOUTMINSPERDAY = 0
--	--CASE 1 EARLY OUT  PER DAY IS > 0 
--	IF(@EARLYOUTDAYSPERMONTH !=0)
--	BEGIN	
--		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
--		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
--		IF(@EARLYOUTMINSPERDAY > 0)
--		BEGIN
--			SET @EARLYOUTCOUNT=0;
--			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
--			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
--			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) and (EARLYOUTMINS > 0)
--			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
--			BEGIN
--				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;		
--				IF(@EARLYOUTODDEVENDECIDER = 0)
--				BEGIN
--					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) AND ANATTENDANCECODE='PRESENT' and (EARLYOUTMINS > 0 ))
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND ANATTENDANCECODE='PRESENT'	and (EARLYOUTMINS > 0 )
--					END
--					ELSE
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND FNATTENDANCECODE = 'PRESENT' and (EARLYOUTMINS > 0 )
--					END
--				END	
--			END		
--		END
--			--CASE 2 EARLY OUT PER DAY IS = 0 
--		ELSE IF(@EARLYOUTMINSPERDAY = 0)
--		BEGIN
--			SET @EARLYOUTCOUNT=0;
--			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
--			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
--			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND EARLYOUTMINS > 0
--			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
--			BEGIN
--				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;	
--				IF(@EARLYOUTODDEVENDECIDER = 0)
--				BEGIN
--					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0 AND ANATTENDANCECODE='PRESENT')
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND ANATTENDANCECODE='PRESENT'	
--					END
--					ELSE
--					BEGIN
--						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE='LOP' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND FNATTENDANCECODE = 'PRESENT'
--					END
--				END	
--			END		
--		END
--	END
--END
	
	
	
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AuditTrailGetforGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AuditTrailGetforGrid]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Select * from TA_Tbl_AuditField  
	

		SELECT  FieldID, TA_Tbl_AuditField.TableID, FieldName, FieldDescription, InsertBit, UpdateBit, DeleteBit, TA_Tbl_AuditField.Status,TA_Tbl_AuditTable.Status as TableStatus
FROM  dbo.TA_Tbl_AuditField
inner join TA_Tbl_AuditTable on TA_Tbl_AuditTable.TableID = TA_Tbl_AuditField.TableID


END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AuditTrailUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AuditTrailUpdate]

@TableStatus Bit='',
@InsertBit Bit='' , 
@UpdateBit Bit='' , 
@DeleteBit Bit='' ,
@Status Bit='',
@FieldID int='',
@TableID int =''

AS
BEGIN

	update TA_Tbl_AuditTable set Status= @TableStatus where TableID=@TableID
	update TA_Tbl_AuditField set InsertBit=@InsertBit, UpdateBit=@UpdateBit, DeleteBit=@DeleteBit,Status =@Status where FieldID = @FieldID

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteCommaSeparated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <13-Dec-2012>
-- Description:	<To Load the auto complete comma separated>
--Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level 
--	Proc_TA_AutoCompleteCommaSeparated '1','EmployeeCodeId',4,0,0
--	Modified by : Manjula.P on 20-Aug-2014 to searching employeeid and employeename based on employee category and employee type selecting criteria
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteCommaSeparated]
@RequiredInput varchar(80),
@SearchType varchar(50),
@EmpAutoId int,
@EmpCategoryShift int=0,
@EmpTypeShift int=0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	DECLARE @SQLQuery as nvarchar(max)
	Declare @GradeLevel int	
	declare @UserGroupName varchar(250)
	set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
	select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	select @GradeLevel=Grade_Level from ta_tbl_grade G
	Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
	inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
	where eDesig.EffectiveDate =
	(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
	and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
	IF(@SearchType = 'SwipeCardNo')
	BEGIN 
		  IF(@EmpAutoId!=1 and @EmpAutoId!=128)		  
			BEGIN
			select swipecardNo from TA_Tbl_Employee E 			
			inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
			Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
			inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
			where swipecardNo like @RequiredInput + '%' and swipecardNo not in('18000000') 
			AND G.Grade_Level>=@GradeLevel AND E.Isdeleted=0
			END
	ELSE
			 BEGIN
			    select swipecardNo from TA_Tbl_Employee where 
                swipecardNo like @RequiredInput + '%' and swipecardNo not in('18000000') and isdeleted=0				
			 END
	END		
		IF(@SearchType = 'EmployeeCodeId')
	BEGIN
			  set @SQLQuery=''
		      IF(@EmpAutoId!=1 and @EmpAutoId!=128)
		       BEGIN	
					set @SQLQuery=' select distinct Employee_Code_Id  from TA_Tbl_Employee E 			
					inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
					Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
					inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
					inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
					inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
					where Employee_code_Id like '''+CAST(@RequiredInput AS VARCHAR(100)) +'%'' and Employee_code_Id not in(''18000000'')
					AND G.Grade_Level>='''+CAST(@GradeLevel AS VARCHAR(100))+''' '
					if(@isReportingto > 0)
						BEGIN
						   set @SQLQuery = @SQLQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
						END
		       END	
			  ELSE
			 BEGIN	
				  set @SQLQuery=' select distinct Employee_code_Id from TA_Tbl_Employee E 
				  inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				  Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				  inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				  inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
				  where  Employee_code_Id like '''+CAST(@RequiredInput AS VARCHAR(100)) +'%'' and Employee_code_Id not in(''18000000'')	'
			  END	
			 -- IF(@EmpCategoryShift>0)
			 -- BEGIN
				--SET @SQLQuery=@SQLQuery+' AND T.TitleId = '+cast(@EmpCategoryShift as varchar(50))+' '
			 -- END
			 -- IF(@EmpTypeShift>0)
			 -- BEGIN
				--SET @SQLQuery=@SQLQuery+' AND TP.TypeId = '+cast(@EmpTypeShift as varchar(50))+' '
			 -- END
			  EXEC(@SQLQuery)
   END
	IF(@SearchType = 'EmployeeName')
	BEGIN
			set @SQLQuery=''
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)	
			BEGIN
				set @SQLQuery=' select distinct Employee_FirstName + '' '' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 	
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				where  Employee_FirstName + '' '' + Employee_LastName 
				like '''+cast(@RequiredInput as varchar(100)) + '%'' and Employee_FirstName not in(''Administrator'')
                AND G.Grade_Level>='''+cast(@GradeLevel AS VARCHAR(100))+'''  '
                if(@isReportingto > 0)
						BEGIN
						   set @SQLQuery = @SQLQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
						END
			END		
		ELSE
		 BEGIN
				set @SQLQuery=' select distinct Employee_FirstName + '' '' + Employee_LastName as Employee_FirstName  from TA_Tbl_Employee E
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId 
				where 
                Employee_FirstName + '' '' + Employee_LastName like '''+cast(@RequiredInput as varchar(100)) + '%'' 
                and Employee_FirstName not in(''Administrator'') '					 
                END
		 --IF(@EmpCategoryShift>0)
		 -- BEGIN
			--SET @SQLQuery=@SQLQuery+' AND T.TitleId = '+cast(@EmpCategoryShift as varchar(50))+' '
		 -- END
		 -- IF(@EmpTypeShift>0)
		 -- BEGIN
			--SET @SQLQuery=@SQLQuery+' AND TP.TypeId = '+cast(@EmpTypeShift as varchar(50))+' '
		 -- END
		  EXEC(@SQLQuery)
    END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtender]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level 
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteExtender] 
	-- Add the parameters for the stored procedure here
	@Id varchar(50),
	@ParameterName varchar(25),
	@EmpAutoId int,	
	@ParentLevelId varchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @GradeLevel int
	--Added by Manjula.P on 08-Sep-2014 for checking whether it is super admin group or not 
	declare @UserGroupName varchar(250)
	declare @sqlQuery varchar(max)
	set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
	select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId  
	select @GradeLevel=Grade_Level from ta_tbl_grade G
	Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
	inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
	where eDesig.EffectiveDate =
	(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
	and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
    -- Insert statements for procedure here
	if(@ParameterName = 'CardNo')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
							select swipecardNo from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where SwipeCardNo like ''+@Id+ '%'
								AND Employee_Status=1 and Employee_Code_Id<>'18000000' 
							--where swipecardNo like @RequiredInput + '%' and swipecardNo not in('18000000') 
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds)) order by swipecardno asc 
						END
					ELSE
						BEGIN
									select swipecardNo from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where SwipeCardNo like ''+@Id+ '%'
								AND Employee_Status=1 and Employee_Code_Id<>'18000000' 
							--where swipecardNo like @RequiredInput + '%' and swipecardNo not in('18000000') 
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 order by swipecardno asc 
						END
				END
			ELSE
				BEGIN
					select swipecardno from TA_Tbl_Employee where SwipeCardNo like ''+@Id+ '%'
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>'18000000' order by swipecardno asc 
				END
		END
	else if(@ParameterName='EmployeeName')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
								select Employee_FirstName + ' ' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
							where 
							Employee_firstName + ' ' + Employee_LastName like '' + @Id + '%'
							AND Employee_Status=1 and Employee_Code_Id<>'18000000'
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds))
						END
					ELSE
						BEGIN
							select Employee_FirstName + ' ' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
							where 
							Employee_firstName + ' ' + Employee_LastName like '' + @Id + '%'
							AND Employee_Status=1 and Employee_Code_Id<>'18000000'
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0
						END
				END
			ELSE
				BEGIN
					select Employee_firstName + ' ' + Employee_LastName as Employee_firstName  from TA_Tbl_Employee where 
					Employee_firstName + ' ' + Employee_LastName like '' + @Id + '%'
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>'18000000'
			END
		END
	else if(@ParameterName='EmployeeId')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
							select Employee_Code_Id  from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where Employee_Code_Id like '' + @Id + '%'
							  AND Employee_Status=1 and Employee_Code_Id<>'18000000' 
							  AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds)) order by Employee_Code_Id asc 
						END
					ELSE
						BEGIN
							select Employee_Code_Id  from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where Employee_Code_Id like '' + @Id + '%'
							  AND Employee_Status=1 and Employee_Code_Id<>'18000000' 
							  AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 order by Employee_Code_Id asc 
						END
				END
			ELSE
				begin
					select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id like '' + @Id + '%'
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>'18000000' order by Employee_Code_Id asc 
				end
		END
		drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtenderForReports]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By : Thilakraj.C
ON- 29-Jul-2013
For Reports AutoComplete Extender
Exec Proc_TA_AutoCompleteExtenderForReports '','EmployeeName',1,0
Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level
Modified By : Manjula.P for dynamic query with checking whether the usergroup is superadmin or not  :Mantis Bug 0025802 (TimecheckV1.5)
*/
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteExtenderForReports] 
	-- Add the parameters for the stored procedure here
	@Id varchar(50),
	@ParameterName varchar(25),
	@EmpAutoId int,
	@ParentLevelId varchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;	
Declare @GradeLevel int
--Added by Manjula.P on 08-Sep-2014 for checking whether it is super admin group or not 
declare @UserGroupName varchar(250)
declare @sqlQuery varchar(max)
set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId  
set @GradeLevel=(select Grade_Level from ta_tbl_grade G
Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
where eDesig.EffectiveDate =
(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) 
and eDesig.EmployeeId=@EmpAutoId )
    -- Insert statements for procedure here
		if(@ParameterName = 'CardNo')
		 BEGIN
		    IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
				 set @sqlQuery=' select swipecardNo from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID 
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
				where SwipeCardNo like  '''+CAST(@Id as varchar(100))+'%''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''' '
				if(@UserGroupName<>'SuperAdmin')
				begin
				SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>='''+cast(@GradeLevel as varchar(150))+''' '  
				end			
				SET @sqlQuery = @sqlQuery + ' Order by swipecardno asc ' 
			  END
		 ELSE
				BEGIN
				SET @sqlQuery =' select swipecardno from TA_Tbl_Employee where SwipeCardNo like 
				'''+CAST(@Id as varchar(100))+'%''			
				and Isdeleted=0 AND ((Employee_Status=1) or		
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))		
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''' Order by swipecardno asc  '
				END
	END
	else if(@ParameterName='EmployeeName')
	 BEGIN
		      IF(@EmpAutoId!=1 and @EmpAutoId!=128)
		      BEGIN
				set @sqlQuery=' select Employee_FirstName + '' ''+ Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
			    where Employee_firstName + '' '' + Employee_LastName like '''+CAST(@Id as varchar(100))+'%''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''' '                
                if(@UserGroupName<>'SuperAdmin')
				begin
                set @sqlQuery=@sqlQuery+' AND G.Grade_Level>='''+cast(@GradeLevel as varchar(150))+''' '  
                end
			 END
		ELSE
			BEGIN
				SET @sqlQuery =' select Employee_firstName + '' '' + Employee_LastName as Employee_firstName  
				from TA_Tbl_Employee where 
				Employee_firstName + '' '' + Employee_LastName like '''+CAST(@Id as varchar(100))+'%''
				and Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''' '
			END
	END	
		else if(@ParameterName='EmployeeId')		
		BEGIN
				IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN	
				 set @sqlQuery=' select Employee_Code_Id  from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
				where Employee_Code_Id like '''+CAST(@Id as varchar(100))+'%''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
			   (Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''''
				if(@UserGroupName<>'SuperAdmin')
				begin
				set @sqlQuery=@sqlQuery+'  AND G.Grade_Level>='''+cast(@GradeLevel as varchar(150))+''' '  
				end
				set @sqlQuery=@sqlQuery+' order by Employee_Code_Id asc '
              END
		 ELSE
		     BEGIN
				set @sqlQuery=' select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id like  '''+CAST(@Id as varchar(100))+'%''
				and Isdeleted=0 AND ((Employee_Status=1) or				
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))				
				and Employee_Code_Id<>'''+cast(18000000 as varchar(1000))+''' order by Employee_Code_Id asc  '
			END
	END
	exec(@sqlQuery);
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutomaticLeaveCancellation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-July-2019>
-- Description:	<When the employee work hours meet out their day hours that case, it will cancel the leave application automatically,
-- even 1 minutes difference between work hours and defined hours, that case it will cancell the leave automatically.>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AutomaticLeaveCancellation]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    Declare @CurrentDate datetime
	Declare @currentDay varchar(20)
	set @CurrentDate=CONVERT(varchar(11),getdate())
	set @currentDay=DATENAME(dw,CONVERT(varchar(11),getdate()))
	if exists(select pageId from TA_Tbl_Page where pageId=185)
	begin
		
	CREATE TABLE #TempLeaveAppliedEmployees
	(
		[LeaveApplication_Id] [int] NOT NULL,
		[Employee_Id] [nvarchar](20) NOT NULL,
		[Leave_ApplicationDate] [datetime] NOT NULL,
		[LeaveType_id] [int] NOT NULL,
		[Type] [nvarchar](50) NOT NULL,
		[Leave_FromDate] [datetime] NOT NULL,
		[Leave_ToDate] [datetime] NOT NULL,
		[Leave_SessionFrom] [nvarchar](50) NULL,
		[Leave_SessionTo] [nvarchar](50) NULL,
		[NumberOfDays] [decimal](18, 1) NOT NULL,
		[Reason] [nvarchar](1000) NULL,
		[IntimationType] [nvarchar](25) NULL,
		[Status] [nvarchar](50) NOT NULL,
		[IsDeleted] [bit] NOT NULL,
		[Remarks] [nvarchar](1000) NULL,
		[IsBorrow] [bit] NULL,
		[Emp_Id] [int] NULL,
		[YearSettings_Id] [int] NULL,
		[CheckedIDs] [int] NULL,
		[InformTo] [varchar](max) NULL,
		[companyId] [int] NULL,
		[Successiveyear] [bit] NULL,
		[Intervening] [char](5) NULL
	) ON [PRIMARY]

	Insert into #TempLeaveAppliedEmployees
	select LA.* from TA_Tbl_LeaveApplication LA
	Inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
	Where E.Employee_Status=1 and (LA.Leave_FromDate>=@CurrentDate and LA.Leave_ToDate<=@CurrentDate)
	and LA.Status!='Rejected'

	--select * from #TempLeaveAppliedEmployees

	
	create table #tempCategoryDetails
	(
		EmployeeId bigint,
		SwipeCardNo varchar(20),
		CategoryId int,
		WeekDay_WorkHrs decimal(18,1),
		Sat_WorkHrs decimal(18,1)
	)

	insert into #tempCategoryDetails
	select	EmpCategory.EmployeeId,
			SwipeCardNo,
			c.CategoryId,
			convert(decimal(18,1),WeekDay_WorkHrs)*60-5,convert(decimal(18,1),Sat_WorkHrs)*60-5
	from 
	(
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		inner join #TempLeaveAppliedEmployees TLA on TLA.Employee_Id=emp.Employee_Id
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ECategory.CategoryId is not null
	inner join TA_Tbl_Category c on c.CategoryId=ECategory.CategoryId

	--select * from #tempCategoryDetails
	
		if(@currentDay='saturday')
		begin
			update TA_Tbl_LeaveApplication set IsDeleted= 
			--SELECT 
			CASE	WHEN SUBSTRING(pd.HrsWork,0,CHARINDEX(':',pd.HrsWork))*60+SUBSTRING(pd.HrsWork,CHARINDEX(':',pd.HrsWork)+1,LEN(pd.HrsWork))=tcd.Sat_WorkHrs THEN 0
					ELSE 0
			END,Status='Cancelled'
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!='00:00') AND LA.Status!='Rejected'
			
			insert into AutoLeaveupdation
			select LA.LeaveApplication_Id
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!='00:00')AND LA.Status!='Rejected'
			
		end
		else
		begin
			update TA_Tbl_LeaveApplication set IsDeleted= 
			--SELECT 
			CASE	WHEN SUBSTRING(pd.HrsWork,0,CHARINDEX(':',pd.HrsWork))*60+SUBSTRING(pd.HrsWork,CHARINDEX(':',pd.HrsWork)+1,LEN(pd.HrsWork))=tcd.WeekDay_WorkHrs THEN 1
					ELSE 0
			END,Status='Cancelled'
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!='00:00')AND LA.Status!='Rejected'
			
			insert into AutoLeaveupdation
			select LA.LeaveApplication_Id
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!='00:00')AND LA.Status!='Rejected'
		end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoShiftConfiguration_Import]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <13/07/2019>
-- Description:	<Import Auto Shift Configuration>
-- =============================================
/* 
Proc_TA_AutoShiftConfiguration_Import
'<Dst_ShiftAlloc>
<Tbl_ShiftAlloc>
<EmployeeId>S1164</EmployeeId>
<Employee_Name>velu</Employee_Name>
<ShiftId1>G1</ShiftId1>
<ShiftId2>G2</ShiftId2>
<ShiftId3>F1</ShiftId3>   
<ShiftId4>F2</ShiftId4>
<ShiftId5>F3</ShiftId5>
</Tbl_ShiftAlloc>
</Dst_ShiftAlloc>', 1,'Superadmin'
*/
CREATE PROCEDURE [dbo].[Proc_TA_AutoShiftConfiguration_Import]
	-- Add the parameters for the stored procedure here
@ShiftData XML = NULL,
@EmpId bigInt,
@UserGroup VARCHAR(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
  	Declare @local_LeaveData XML = @ShiftData
	Declare	@local_EmpAutoID bigInt=@EmpId	
	Declare @local_UserGroup VARCHAR(max)=@UserGroup
	SET NOCOUNT ON;
	DECLARE @XMLParams INT	
	DECLARE @ErrMsg VARCHAR(MAX)
	Declare @ErrIds VARCHAR(MAX)
	Declare @SQLQuery varchar(max)
	declare @ValidEmpId varchar(40)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)	
	BEGIN TRY
		BEGIN TRAN ImportAutoShift
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
			SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_UserGroup
			INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EmpAutoID) AS EMPAUTOID  
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_UserGroup,0) AS LEVELID
			DECLARE @SQLEMPLEVEL			NVARCHAR(4000)			
			SET @SQLEMPLEVEL=
			'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
			SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'

			

			IF(@ISREPORTINGTO > 0)
			BEGIN
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
			END

			EXECUTE(@SQLEMPLEVEL)
						
			create table #TempShiftData
			(	
				autoid int identity(1,1),
				Employee_Id int,					
				Employee_Code_Id varchar(100),	 
				ShiftId1 varchar(8),
				ShiftId2 varchar(8),
				ShiftId3 varchar(8),
				ShiftId4 varchar(8),
				ShiftId5 varchar(8),
			)	
			INSERT INTO #TempShiftData
			SELECT E.Employee_Id, Tbl.* FROM OPENXML (@XMLParams, '/Dst_ShiftAlloc/Tbl_ShiftAlloc', 2) WITH 
			(	
				EmployeeId varchar(100),						
				ShiftId1 varchar(8),
				ShiftId2 varchar(8),
				ShiftId3 varchar(8),
				ShiftId4 varchar(8),
				ShiftId5 varchar(8)
			) Tbl			
			left outer join TA_Tbl_Employee E ON E.Employee_Code_Id = convert(varchar(40),Tbl.EmployeeId)
			AND E.IsDeleted = 0 AND E.Employee_Status = 1


			

			INSERT INTO @ErrorMsg
			SELECT autoid,Employee_Code_Id,'',1,getdate() FROM #TempShiftData
			EXEC SP_XML_RemoveDocument @XMLParams
				--select '1'
			--Empty excel File error checking--
			IF NOT EXISTS(SELECT Employee_Code_Id FROM #TempShiftData where Employee_Code_Id is not null or Employee_Code_Id='')
			BEGIN
				SET @ErrMsg = 'There is no record in the Excel File Please Upload Valid File'
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END		
			--Valid Employee Code Id checking--	
			IF EXISTS(SELECT Employee_Code_Id FROM #TempShiftData WHERE ISNULL(Employee_Code_Id, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Employee Id is missing;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Employee_Code_Id, '') = ''
			END	
			UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Employee Id is Invalid <br />',flag=0 FROM @ErrorMsg EM
			inner join #TempShiftData tot on tot.autoid=EM.RecordID 
			where (tot.Employee_Id is null or tot.Employee_Id = '')
			IF EXISTS(SELECT ShiftId1 FROM #TempShiftData WHERE ShiftId1 = '' or ShiftId1 is null)
			Begin
						UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 1 Name is missing;<br />',flag=0 FROM @ErrorMsg EM
						inner join #TempShiftData tot on tot.autoid=EM.RecordID 	
						where (tot.ShiftId1 is null or tot.ShiftId1 = '')	
			END
			--First shift Id 1 valid Id checking--		
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 1 Name is not Valid;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId1 != '' 				
				where tot.ShiftId1 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 2 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 2 Name is not Valid;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId2 != '' 				
				where tot.ShiftId2 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 3 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 3 Name is not Valid;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId3 != '' 				
				where tot.ShiftId3 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 4 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 4 Name is not Valid;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId4 != '' 				
				where tot.ShiftId4 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 5 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Shift 5 Name is not Valid;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId5 != '' 				
				where tot.ShiftId5 not in (select Shift_ShortName from ta_tbl_shift a)
			--Duplicate Employee id Check --	
			IF Exists(
			SELECT autoid FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,Employee_Id ORDER BY Employee_Code_Id ASC)AS duplicate,
						autoid FROM #TempShiftData
			)AS A WHERE duplicate>1)
			BEGIN
				set @alertMsg='Duplication Record Found;Please find and remove duplicate record in excel file;<br />'				
				UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,Employee_Id ORDER BY Employee_Code_Id ASC)AS duplicate,
					Employee_Code_Id,autoid FROM #TempShiftData
				)AS A on EM.RecordID=a.autoid WHERE a.duplicate>1
				and ISNULL(a.Employee_Code_Id, '') != ''
			END
			--Level Rights Check ---
			IF EXISTS(SELECT t.Employee_Code_Id FROM #TempShiftData t INNER JOIN ta_tbl_employee e on convert(varchar(40),t.Employee_Code_Id)=e.Employee_Code_Id
			LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID=''))
			BEGIN
				set @alertMsg='Employee is not available or you are not having an previlege to import overtime data for this employee;<br />'				
				UPDATE @ErrorMsg SET Error_Msg=CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN #TempShiftData t on EM.RecordID=t.autoid				
				INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID='')
				and ISNULL(t.Employee_Code_Id, '') != ''
			END
			--Insert or Update function only all records are valid--
				Declare @IsValidImport int
				Declare @TotLeaveRecord int
				select @IsValidImport = isnull(COUNT(*),0) from @ErrorMsg where flag=0
				
				IF(@IsValidImport = 0)
				begin
						select @TotLeaveRecord=COUNT(*) from #TempShiftData				
						Declare @start int
						set @start=1	
						while @TotLeaveRecord>=@start
							begin	
								Declare @Employeeid int
								select @Employeeid=Employee_Id from #TempShiftData where autoid=@start

									IF NOT EXISTS(SELECT EmployeeId from TA_Tbl_AutoShiftConfiguration a inner join #TempShiftData b on b.Employee_Id= a.EmployeeId where EmployeeId=@Employeeid)
										BEGIN
										
											INSERT INTO TA_Tbl_AutoShiftConfiguration(EmployeeId,ShiftId1,ShiftId2,ShiftId3,ShiftId4,ShiftId5,CreatedBy, CreatedDate, IsImport) 
											Select Employee_Id, isnull(c.Shift_Id,0), isnull(d.Shift_Id,0),isnull(e.Shift_Id,0), isnull(f.Shift_Id,0), isnull(g.Shift_Id,0),@EmpId,getdate(),1 from #TempShiftData	a
											left outer join ta_tbl_shift c on c.Shift_ShortName = a.ShiftId1
											left outer join ta_tbl_shift d on d.Shift_ShortName = a.ShiftId2
											left outer join ta_tbl_shift e on e.Shift_ShortName = a.ShiftId3
											left outer join ta_tbl_shift f on f.Shift_ShortName = a.ShiftId4
											left outer join ta_tbl_shift g on g.Shift_ShortName = a.ShiftId5										
										END
									ELSE IF EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration a inner join #TempShiftData b on b.Employee_Id= a.EmployeeId where EmployeeId=b.Employee_Id )
										BEGIN
											Update a set
											ShiftId1 = isnull(c.Shift_Id,0),
											ShiftId2 = isnull(d.Shift_Id,0),
											ShiftId3 = isnull(e.Shift_Id,0),
											ShiftId4 = isnull(f.Shift_Id,0),
											ShiftId5 = isnull(g.Shift_Id,0),
											ModifiedBy = @EmpId,
											ModifiedDate = getdate(),
											isimport=1
											from TA_Tbl_AutoShiftConfiguration a
											inner join #TempShiftData b on b.Employee_Id= a.EmployeeId 
											left outer join ta_tbl_shift c on c.Shift_ShortName = b.ShiftId1
											left outer join ta_tbl_shift d on d.Shift_ShortName = b.ShiftId2
											left outer join ta_tbl_shift e on e.Shift_ShortName = b.ShiftId3
											left outer join ta_tbl_shift f on f.Shift_ShortName = b.ShiftId4
											left outer join ta_tbl_shift g on g.Shift_ShortName = b.ShiftId5
											where EmployeeId=@Employeeid							
										END
							set @start=@start+1
							End
							SELECT 'Msg:DataImportedSuccessfully' [Message]
				End
				ELSE 
					BEGIN
							SELECT	RecordID=RecordID,
							Employee_Id, 
							Error_Msg,
							date
							FROM @ErrorMsg where flag=0
					END
					drop table #TempShiftData
		COMMIT TRAN ImportAutoShift
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportAutoShift
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
	END CATCH
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BindProjectdetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<Filter and dropdown filling of project info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BindProjectdetails]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	select Project_Id, Project_Name=isnull(Project_Name,'') from TA_Tbl_Project	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BiostarAPI]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BiostarAPI]
	-- Add the parameters for the stored procedure here
			@tag nvarchar(10),
			@APIID bigint=null,
			@APIURL nvarchar(2000)=null, 
			@BiostarUsername nvarchar(200)=null,
			@BiostarPassword nvarchar(200)=null,
			@Createdby bigint=null,
			@isMainAPI int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    if(@tag='I')
		begin
			INSERT INTO [dbo].[ta_tbl_BiostarAPIDetails]([APIURL],[BiostarUsername],[BiostarPassword],[Createdby],[createdDate]) VALUES(@APIURL,@BiostarUsername,@BiostarPassword,@Createdby,GETDATE())
		end
	else if(@tag='U')
		begin
			UPDATE [dbo].[ta_tbl_BiostarAPIDetails] SET [APIURL] = @APIURL,[BiostarUsername] = @BiostarUsername,[BiostarPassword] = @BiostarPassword,[Modifyby] = @Createdby,[Modifydate] = GETDATE() WHERE APIID=@APIID
		end
	else if(@tag='S')
		begin
			select APIURL=BlockAPI,BiostarUsername=userName,BiostarPassword=password  from Ta_tbl_PolicyConfiguration 
		end


END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <14-11-2019 01:44 PM>
-- Description:	<Bulk UPDATE of availed leave values through excel sheet>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]
AS
BEGIN
	SET NOCOUNT ON;	
	DECLARE @YearSetID int
	DECLARE @Count int
	DECLARE @Start int
	SET  @Start=1
	SELECT @YearSetID=YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive=1
	SELECT @Count=COUNT(*) FROM ImportFromExcel	
	WHILE @Count>=@Start
	BEGIN		
		DECLARE @EmpAutoID bigint
		DECLARE @Employeeid	varchar(50)
		DECLARE @LeaveType1	DECIMAL(18,1)
		DECLARE @LeaveType2	DECIMAL(18,1)
		DECLARE @LeaveType3	DECIMAL(18,1)
		DECLARE @LeaveType4	DECIMAL(18,1)
		DECLARE @LeaveType5	DECIMAL(18,1)
		DECLARE @LeaveType6	DECIMAL(18,1)
		DECLARE @LeaveType7	DECIMAL(18,1)
		DECLARE @LeaveType8	DECIMAL(18,1)
		DECLARE @LeaveType9	DECIMAL(18,1)
		DECLARE @LeaveType10 DECIMAL(18,1)
		DECLARE @LeaveType11 DECIMAL(18,1)
		DECLARE @LeaveType12 DECIMAL(18,1)
		DECLARE @LeaveType13 DECIMAL(18,1)
		DECLARE @LeaveType14 DECIMAL(18,1)
		DECLARE @LeaveType15 DECIMAL(18,1)
		
		SET  @Employeeid=''
		SET  @LeaveType1=0 
		SET  @LeaveType2=0 
		SET  @LeaveType3=0 
		SET  @LeaveType4=0 
		SET  @LeaveType5=0 
		SET  @LeaveType6=0 
		SET  @LeaveType7=0
		SET  @LeaveType8=0 
		SET  @LeaveType9=0
		SET  @LeaveType10=0 
		SET  @LeaveType11=0 
		SET  @LeaveType12=0
		SET  @LeaveType13=0
		SET  @LeaveType14=0 
		SET  @LeaveType15=0
		
		SELECT
		@Employeeid=Employeeid,
		@LeaveType1=LeaveType1,
		@LeaveType2=LeaveType2,
		@LeaveType3=LeaveType3, 
		@LeaveType4=LeaveType4,
		@LeaveType5=LeaveType5,
		@LeaveType6=LeaveType6,
		@LeaveType7=LeaveType7,
		@LeaveType8=LeaveType8,
		@LeaveType9=LeaveType9,
		@LeaveType10=LeaveType10, 
		@LeaveType11=LeaveType11,
		@LeaveType12=LeaveType12,
		@LeaveType13=LeaveType13,
		@LeaveType14=LeaveType14,
		@LeaveType15=LeaveType15			
		FROM ImportFromExcel WHERE [Sl.No]=@Start
		
		SELECT @EmpAutoID=Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@Employeeid and Isdeleted=0		
		if(@EmpAutoID is not null and @EmpAutoID<>'')
		BEGIN
			DECLARE @LeaveTypeID int
			--1
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=1 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType1,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---2
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=2 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType2,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---3
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=3 ORDER BY LeaveType_Id			
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType3,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---4
			SET  @LeaveTypeID=0							
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=4 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType4,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---5
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=5 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType5,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---6
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=6 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType6,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---7
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=7 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType7,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---8
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=8 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType8,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---9
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=9 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType9,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---10
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=10 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType10,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---11
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=11 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType11,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---12
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=12 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType12,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---13
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=13 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType13,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---14
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=14 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType14,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---15
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=15 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'')!='')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET NoOffLeaveAvailed=ISNULL(@LeaveType15,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
		END
		SET  @Start=@Start+1 
	END
	DELETE FROM ImportFromExcel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportPrevLeaveBalance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <28-01-2019 04.42 PM>
-- Description:	<Import Previous year Leave values into employee leave type table>
--select * from ImportFromExcel
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkImportPrevLeaveBalance]
AS
BEGIN
	SET NOCOUNT on;	
	Declare @YearSetID int
	Declare @Count int
	Declare @Start int
	set @Start=1
	--select * from TA_Tbl_Emp_LeaveTypeDetails
	select @YearSetID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
	select @Count=COUNT(*) from ImportFromExcel	
	--select * from ImportFromExcel
	While @Count>=@Start
	BEGIN		
		Declare @EmpAutoID bigint
		Declare @Employeeid	varchar(50)
		Declare @LeaveType1	decimal(18,1)
		Declare @LeaveType2	decimal(18,1)
		Declare @LeaveType3	decimal(18,1)
		Declare @LeaveType4	decimal(18,1)
		Declare @LeaveType5	decimal(18,1)
		Declare @LeaveType6	decimal(18,1)
		Declare @LeaveType7	decimal(18,1)
		Declare @LeaveType8	decimal(18,1)
		Declare @LeaveType9	decimal(18,1)
		Declare @LeaveType10 decimal(18,1)
		Declare @LeaveType11 decimal(18,1)
		Declare @LeaveType12 decimal(18,1)
		Declare @LeaveType13 decimal(18,1)
		Declare @LeaveType14 decimal(18,1)
		Declare @LeaveType15 decimal(18,1)
		
		set @Employeeid=''
		set @LeaveType1=0 
		set @LeaveType2=0 
		set @LeaveType3=0 
		set @LeaveType4=0 
		set @LeaveType5=0 
		set @LeaveType6=0 
		set @LeaveType7=0
		set @LeaveType8=0 
		set @LeaveType9=0
		set @LeaveType10=0 
		set @LeaveType11=0 
		set @LeaveType12=0
		set @LeaveType13=0
		set @LeaveType14=0 
		set @LeaveType15=0
		
		select 
		@Employeeid=Employeeid,
		@LeaveType1=LeaveType1,
		@LeaveType2=LeaveType2,
		@LeaveType3=LeaveType3, 
		@LeaveType4=LeaveType4,
		@LeaveType5=LeaveType5,
		@LeaveType6=LeaveType6,
		@LeaveType7=LeaveType7,
		@LeaveType8=LeaveType8,
		@LeaveType9=LeaveType9,
		@LeaveType10=LeaveType10, 
		@LeaveType11=LeaveType11,
		@LeaveType12=LeaveType12,
		@LeaveType13=LeaveType13,
		@LeaveType14=LeaveType14,
		@LeaveType15=LeaveType15			
		from ImportFromExcel where [Sl.No]=@Start
		
		select @EmpAutoID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employeeid and Isdeleted=0
		Declare @i int
		set @i=1
		if(@EmpAutoID is not null and @EmpAutoID<>'')
		begin
			Declare @LeaveTypeID int
			--1
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=1 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType1,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			end
			---2
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=2 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType2,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---3
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=3 order by LeaveType_Id			
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType3,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---4
			set @LeaveTypeID=0							
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=4 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType4,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---5
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=5 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType5,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---6
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=6 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType6,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---7
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=7 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType7,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---8
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=8 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType8,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---9
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=9 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType9,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---10
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=10 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType10,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---11
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=11 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType11,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---12
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=12 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType12,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---13
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=13 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType13,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---14
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=14 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType14,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---15
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=15 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'')!='')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType15,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
		end
		set @Start=@Start+1 
	END
	delete from ImportFromExcel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkLeaveSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 29-Nov-2011
-- Description:	Bulk Leave Approval
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkLeaveSanction]
	@LeaveApplication_id int
AS
BEGIN
	SET NOCOUNT ON;
	update ta_tbl_leaveapplication set Status='Approved' where LeaveApplication_id=@LeaveApplication_id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]
	@inSwipeCardNo varchar(50),
	@Date varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime,Clk_InPunchType, clk_outpunchtype FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @Date AND IsVoid = 0 order by clk_id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculateOTDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_CalculateOTDays
Description		:	Calculate OT Days
Tables Included		:	TA_Tbl_ProcessedData
Created By		:	Kumuthini.L
Created On		:	25-Apr-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_CalculateOTDays]
(
	@SwipeCardNo NVARCHAR(10),
	@StartDate  NVARCHAR(10),
	@EndDate  NVARCHAR(10)
)
AS
DECLARE @TotalOTMins AS BIGINT
DECLARE @TotalOTDays AS NUMERIC(8,2)
BEGIN
	-- Get Total OT Minutes
	SET @TotalOTMins=(SELECT SUM(OtMins) FROM TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @StartDate AND @EndDate) AND Employee_Code_Id=@SwipeCardNo)
	-- Calculate Total OT Days
	SET @TotalOTDays = (@TotalOTMins / 60) / 8
	SELECT ISNULL(@TotalOTDays,0) AS TotalOTDays
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 09-01-2015
-- Description:	To calculate the physical work hours
-- =============================================
-- select * from TA_Tbl_ClockDetails where clk_date='2014-09-01' and clk_empid='788'
-- 300+51+120+39=351+159=510
-- Proc_TA_CalculatePhysicalWorkHoursForService '789','2015-01-02 00:00:00.000'
CREATE PROCEDURE [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50),
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Start int
	Declare @TotalRecord int
	Declare @strInDateTime datetime
	declare @strOutDateTime datetime
	declare @strInDate datetime
	declare @strOutDate datetime
	declare @strOutDateTimeCrossed datetime
	declare @strInDateTimeCrossed datetime
	declare @NumberofApplied int
	Declare @TotalHoursWorked int
	Declare @FinalTotalHoursWorked int
	set @FinalTotalHoursWorked=0
	set @NumberofApplied=0
	set @Start=1
    -- Insert statements for procedure here
    if exists(SELECT Clk_InDate FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @Date AND IsVoid = 0)
		begin
			Create table #TempClockDetails
			(
				id int identity(1,1),Clk_InDate datetime,Clk_InTime datetime,Clk_OutDate datetime,Clk_OutTime datetime,
				--TotalHoursWorked as (datepart(hh,Clk_OutTime) * 60 + datepart(mi,Clk_OutTime))-(datepart(hh,Clk_InTime) * 60 + datepart(mi,Clk_InTime))
				TotalHoursWorked as (DATEDIFF(minute,Clk_InDate+Clk_InTime,Clk_OutDate + Clk_OutTime))
			)		
			Insert into #TempClockDetails
			SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo 
			AND Clk_Date = @Date AND IsVoid = 0			
			select @TotalRecord=COUNT(*)from #TempClockDetails
			while @TotalRecord>=@Start
				begin
					select	@strInDateTime=Clk_InTime,
							@strOutDateTime=Clk_OutTime,
							@strInDate=Clk_InDate,
							@strOutDate=Clk_OutDate,
							@TotalHoursWorked=TotalHoursWorked 
					from #TempClockDetails where id=@Start					
					if(@strInDate!='' and @strInDateTime!='' and @strOutDate!='' and @strOutDateTime!='')
						begin
							set @strInDateTime=@strInDate+' '+@strInDateTime
							set @strOutDateTime=@strOutDate+' '+@strOutDateTime
							if exists(SELECT P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0)
								begin
									SELECT @strInDateTime=P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0
								end
							if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0)
								begin
									SELECT @strOutDateTime=P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0
								end
							if exists(SELECT P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0)
								begin
									if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status='Approved' AND P.IsDeleted=0)
										begin
											if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status='Approved' AND P.IsDeleted=0)
												begin
													SELECT @strInDateTimeCrossed=P.Permission_FromTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status='Approved' AND P.IsDeleted=0
													SELECT @strOutDateTimeCrossed=P.Permission_ToTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status='Approved' AND P.IsDeleted=0
													if(@strOutDateTime>@strOutDateTimeCrossed)
														begin
															SELECT @NumberofApplied=P.No_Of_Hours FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status='Approved' AND P.IsDeleted=0
														end
												end
										end
								end
							set @FinalTotalHoursWorked=@FinalTotalHoursWorked+@TotalHoursWorked-@NumberofApplied
						end									
					set @Start=@Start+1
				end			
		end
		select @FinalTotalHoursWorked as TotalHoursWorked		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ChckTrnsfrAlrdyExstsBasedOnEmp_Date]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ChckTrnsfrAlrdyExstsBasedOnEmp_Date] 
	@EmpAutoID bigint,
	@TrnsfrDte datetime
AS
BEGIN	
	SET NOCOUNT ON;
	SELECT count(*) FROM Ta_tbl_Transfer T
	Inner join TA_Tbl_Employee E on T.Emp_AutoID=E.Employee_Id
	WHERE T.Emp_AutoID=@EmpAutoID and Trnsfr_Dte=@TrnsfrDte
	and E.Employee_Status=1 and E.Isdeleted=0 and T.Trnsfr_status!='Rejected'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created On		:	09-Oct-2013
Descriptions	:	Adding procedure for checking addtional weekly off grouping restore
Proc_TA_CheckAdditionalWeeklyOffGroupCount '32,33'
*/
CREATE proc [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]
(
@AddionalWeekId nvarchar(2000)
)
as
begin
	select count(AL.LevelId) as count,AD.Addl_WeekOff_Day,AD.Addl_WeekOff_Week,IsDeleted from TA_Tbl_Additional_WeeklyOff AD
	inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=AD.Addl_WeeklyOff_Id
	where AD.Addl_WeeklyOff_Id in (select Value from dbo.Split(@AddionalWeekId,','))
	group by AL.LevelId,AD.Addl_WeekOff_Day,AD.Addl_WeekOff_Week,AD.IsDeleted
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOff]
	-- Add the parameters for the stored procedure here
	@dtmDate datetime,
	@SwipeCardNo varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW
    inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id
    INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId
    INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID
    WHERE emp.SwipeCardNo = @SwipeCardNo AND AW.IsDeleted = 0  AND
    EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND 
    EffectiveDate <=CONVERT(DATETIME,@dtmDate, 102) order by EffectiveDate desc)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <30-May-2019>
-- Description:	<Verifying current date is weekly off or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]
	@SwipeCardNo varchar(50),
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW 
	inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id 
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId 
	INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID 
	WHERE emp.SwipeCardNo = @SwipeCardNo AND AW.IsDeleted = 0  AND 		
	EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,@dtmDate, 102) order by EffectiveDate desc)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckAddlWeekOff_Insert  
Description : check additional week off before insert, is already there   
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P   
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Insert]
(
	@LevelID INT,
	@addlWeekoffDay NVARCHAR(15)='',
	@addlWeekoffWeek NVARCHAR(15)=''
)
AS
BEGIN
	SELECT COUNT(Addl_WeeklyOff_Id) AS AID FROM TA_Tbl_Additional_WeeklyOff WHERE LevelId_Id=@LevelID AND Addl_WeekOff_Day=@addlWeekoffDay AND Addl_WeekOff_Week=@addlWeekoffWeek AND Isdeleted=0	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckAddlWeekOff_Update  
Description : check additional week off before update, is already there   
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P  
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Update]
(
	@AddlWeekOffID INT,
	@LevelId INT,
	@addlWeekoffDay NVARCHAR(15)='',
	@addlWeekoffWeek NVARCHAR(15)=''
)
AS
BEGIN
	SELECT COUNT(Addl_WeeklyOff_Id) AS AID FROM TA_Tbl_Additional_WeeklyOff WHERE LevelId_Id=@LevelId AND Addl_WeekOff_Day=@addlWeekoffDay AND Addl_WeekOff_Week=@addlWeekoffWeek AND Isdeleted=0 AND Addl_WeeklyOff_Id<>@AddlWeekOffID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckApplicableAfterDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckApplicableAfterDays  202,53,'01/03/2008'
Description  :    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckApplicableAfterDays]    
(   
@Employee_Id bigint,    
@leaveType_Id int,
@FromDate datetime   
)    
AS    
declare @test as decimal    
declare @Result as varchar(10)    
if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
BEGIN   
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 
	and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
else
BEGIN
    set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101))     
if(@test=0)    
 begin    
 set @Result='Y'    
 end    
else    
 begin 
 declare @eligible as decimal       
 if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
  BEGIN   
	  set @eligible=(select distinct (Datediff(d,e.DateOfJoining,@FromDate) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 
	  and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	  and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))   
  END 
  else
  BEGIN
      set @eligible=(select distinct (Datediff(d,e.DateOfJoining,@FromDate) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))   
  END 
    if (@eligible>=0)    
      begin    
      set @Result='Y'    
      end       
    else    
     begin    
     set @Result='N'    
     end    
end    
select @Result as RemainingNoOfLeaves
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_CheckAttandanceCode 2,1,'present',3,'U'
CREATE PROCEDURE [dbo].[Proc_TA_CheckAttandanceCode]
	@AttandanceID as int,
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@opr as varchar(1)
AS
BEGIN
	if (@opr='I')
		Begin
			select count(*) as RecCount from TA_Tbl_AttandanceCode  where 
			(AttandanceCode=@AttandanceCode or AttandanceValue=@AttandanceValue) and
			CompanyID=@CompanyID 
		End
	else
		Begin
			--declare @AttCode varchar(25)
			--declare @AttValue varchar(25)
			--declare @CompID int
			--select @AttCode=AttandanceCode,@AttValue=AttandanceValue,@CompID=CompanyID
			--from TA_Tbl_AttandanceCode where AttandanceID=@AttandanceID
			----select @AttCode,@AttValue,@CompID
			select count(*) as RecCount from TA_Tbl_AttandanceCode  where 
			(AttandanceCode=@AttandanceCode or AttandanceValue=@AttandanceValue) and	CompanyID=@CompanyID and AttandanceID!=@AttandanceID
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckBorrowExists 6,1
Description		:	Check Borrow Exists for Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
CREATE    PROCEDURE [dbo].[Proc_TA_CheckBorrowExists]
	@Employee_Id int,
	@LeaveType_Id int
AS
begin
	SET NOCOUNT ON;
	select lpd.Borrow_FromNextYear as Borrow from TA_TbL_LeavePolicyDetails lpd
	inner join TA_Tbl_Emp_LeavePolicy elp 
	on elp.LeavePolicy_Id=lpd.Policy_Id
	inner join TA_Tbl_YearSetting ys
	on ys.YearSettings_Id=elp.YearSettingId
	where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
	and ys.IsActive=1 and elp.Isdeleted=0 
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowLeaveExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name  : Proc_TA_CheckBorrowLeaveExists '2008-09-15','2008-12-17',151  
Description  : Check Approved Borrow Leave Exists after normal leaves  
Tables Included  : TA_Tbl_LeaveApplication  
Created By  : Prabakaran  
Created On  : 10-Sep-08  
Modified By  :   
Modified On  :   
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckBorrowLeaveExists]   
	@LeaveFromDate datetime,  
	@LeaveToDate datetime,
	@LeaveTypeId int,  
	@EmployeeId int  
as  
 BEGIN 
	SET NOCOUNT ON;
	select count(LeaveApplication_Id) as BorrowCount  from TA_Tbl_LeaveApplication   
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=TA_Tbl_LeaveApplication.YearSettings_Id  
	where LeaveType_Id=@LeaveTypeId and Employee_Id=@EmployeeId and Isdeleted=0 and Status='Approved' and IsBorrow=1 and ys.IsActive=1
 END   

 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDelete]
	@CategoryID as int
AS
BEGIN
	select count(*) as RecCount from ta_tbl_employeeCategory
	where CategoryId=@CategoryId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : Prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicate]
	@Opr as nvarchar(1),	
	@CategoryID as int
AS
BEGIN
	Declare @CategoryName as nvarchar(50)
	Set @CategoryName=(select CategoryName from ta_tbl_Category where CategoryId=@CategoryID)
	if (@Opr='I')
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and Isdeleted=0
		End
	Else
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and CategoryId<>@CategoryId and Isdeleted=0
		End	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		R.Manikandan
-- Create date: 12-June-2012
-- Description:	Checking Duplication Before adding category
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]
	@Opr as nvarchar(1),	
	@CategoryName as nvarchar(50),
	@CategoryID as int
AS
BEGIN
	SET NOCOUNT ON;
	if (@Opr='I')
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName 
		End
	Else
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and CategoryId<>@CategoryId 
		End	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCCGroupExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 11-Oct-2010
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCCGroupExists] 
	@LevelId int,
	@DesignationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
   select count(*) from TA_Tbl_CCMailGroup where LevelID=@LevelId and DesignationID=@DesignationId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompoffEligibility]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <19-March-2012>
-- Description:	<Check the Working for Comp off Apply Eligibility>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCompoffEligibility]
	-- Add the parameters for the stored procedure here
	@Employee_Code_Id nvarchar(25),
	@date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @SwipeCardNo varchar(10)
	Declare @EmployeeId int
	Declare @Day int
	Declare @Month int
	Declare @Year int
	select @SwipeCardNo=swipeCardNo from TA_Tbl_Employee where Employee_Code_Id=@Employee_Code_Id
	select @EmployeeId=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employee_Code_Id
	set @Day=DAY(@date)
	set @Month=MONTH(@date)
	set @Year=YEAR(@date)
    -- Insert statements for procedure here
    SELECT top 1 * FROM TA_Tbl_ProcessedData
    SELECT top 1 * FROM TA_Tbl_PermanentShiftAllocation
    SELECT top 1 * FROM TA_Tbl_TemporaryShiftAllocation
    select * from TA_Tbl_Shift
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompOffMapped]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan
-- Create date: 22-Mar-2017
-- Description:	Delete the compensation entry by ID check the compoff taken any leave, If yes then entry can't deleted.
-- Proc_TA_CompensationEntryByID 253
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_CheckCompOffMapped]
	-- Add the parameters for the stored procedure here
	@CompOff_ID as bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LeaveApplication as nvarchar(50)
	SELECT @LeaveApplication=LeaveApplicationId FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@CompOff_ID
	if(@LeaveApplication is null or @LeaveApplication='')
		Begin
			Select '1'
		END
	else
		BEGIn
			Select 'Availed'
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckConcurrentUserCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckConcurrentUserCount  
Description : check maximum no of concurrent user count   
Tables Included : TA_Tbl_ConcurrentUser  
Created By : Christopher S   
Created On : 24-Mar-08
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckConcurrentUserCount]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_ConcurrentUser WHERE UserId<>'Admin'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountFacorLeaveTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created date	:	29-Jan-2014
Descriptinos	:	Adding this procedure for checking whether the leave types is with count factor or not
Proc_TA_CheckCountFacorLeaveTypes 0
*/
CREATE PROC [dbo].[Proc_TA_CheckCountFacorLeaveTypes]
(
	@LeaveTypeId int=0
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @count int;
	DECLARE @LeaveType VARCHAR(10)
	select @count=COUNT(*),@LeaveType=LeaveType from TA_Tbl_LeaveType where LeaveType_Id<>@LeaveTypeId and CountFactor=1 group by LeaveType
	select  cast(isnull(@count,0) as varchar) +','+isnull(@LeaveType,'') as count
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountryInsertUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckCountryInsertUpdate  
Description : check country before insert and update, is already there
Tables Included : Ta_tbl_lookup  
Created By : P.Prabakaran  
Created On : 27-10-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckCountryInsertUpdate]  
@Mode char(1),  
@ID int,  
@Title nvarchar(50)  
as
declare @sql as nvarchar(3000)  
/* For Insert */  
if(@Mode='I')  
begin  
  set @sql = 'select count(*) as CountryCount from Ta_tbl_lookup where Type=1  and Title=N'''+@Title+''''  
  exec(@sql)
end  
/* For Modify */  
if(@Mode='M')  
begin  
  set @sql = 'select count(*) as CountryCount  from Ta_tbl_lookup where Type=1 and Title=N'''+@Title+''' and ID<>'+cast(@ID as nvarchar(25))+''  
  exec(@sql)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDateForHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_CheckDateForHoliday '06/01/2015','2222'
/*  
Procedure Name : Proc_TA_CheckDateForHoliday  
Description : check date fore holidays
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  Gopinath on 23Nov15 for bug no.31239
Modified On :  
*/  
--Proc_TA_CheckDateForHoliday '07/28/2011','Emp103'
CREATE PROCEDURE [dbo].[Proc_TA_CheckDateForHoliday]
(
	@Date Varchar(15),
	@EmployeeCodeId nvarchar(15)
)
AS
BEGIN
	set nocount on 
	declare @EmployeeLevelId int
	set @EmployeeLevelId = (select top 1 EL.LevelId from TA_Tbl_EmployeeLevel EL
	inner join TA_Tbl_Employee E on E.Employee_Id=EL.EmployeeId
	where E.employee_Code_Id = @EmployeeCodeId order by EffectiveDate desc)
	create table #Level (LevelID int) 
	declare @EmployeeLevelIdNew int
	set @EmployeeLevelIdNew=@EmployeeLevelId  
	while((select Id from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew) <> '')    
	BEGIN    
	  insert into #Level select id from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew    
	  select @EmployeeLevelIdNew = parentId from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew
	END   
	SELECT h.Holiday_Id FROM TA_Tbl_Holiday H 
	inner join TA_Tbl_HolidayChildTable HCT on H.Holiday_Id=HCT.Holiday_Id
	INNER JOIN #Level on (#Level.LevelID = HCT.LevelID or HCT.LevelID=0)
	WHERE Holiday_FromDate <= @Date AND Holiday_ToDate >= @Date 
	AND (Holiday_Type = 'G' or Holiday_Type = 'L') AND IsDeleted = 0 and HCT.LevelID=@EmployeeLevelId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-01-2013>
-- Description:	<To check whether default shift is created or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCount]
	-- Add the parameters for the stored procedure here
	@LevelId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_Shift where Level_Id=@LevelId and DefaultShift=1 and Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-01-2013>
-- Description:	<To check whether default shift is created or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]
	-- Add the parameters for the stored procedure here
	@LevelId int,
	@ShiftID int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_Shift where Level_Id=@LevelId and DefaultShift=1 and Shift_Id<>@ShiftID and Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmailID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: [Proc_TA_CheckDuplicateEmailID]   
Description 	: check Email ID is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By 		: karthikeyan.R
Created On 		: 23-08-2017
Proc_TA_CheckDuplicateEmailID 'U',60,'manikandan.rr@angleritech.com'
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmailID] 
(
	@tag char(1),
	@EmployeeID int,
	@EmailID NVARCHAR(500)
)
AS
BEGIN
	set nocount on
	declare @sql as varchar(3000)
	if(@tag='I')
		begin
			select COUNT(EmailId) as EID from TA_Tbl_Employee where EmailId=@EmailID
		end
	else if(@tag='U')
		begin
			select COUNT(EmailId) as EID from TA_Tbl_Employee where EmailId=@EmailID and Employee_Id<>@EmployeeID
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: Proc_TA_CheckDuplicateEmployeeCode  
Description 	: check employee code is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By 	: Arun Vinoth.T  
Created On 	: 27-Aug-2007  
Modified By 	:  A.K.T.MOORTHI
Modified On	 :  08-Apr-2014
Description  :  When Demo Mode Remove Condition For IsDeleted = 0 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCode] 
(
	@EmpCode NVARCHAR(10),
	@LevelId int,
	@ApplnMode BIT
)
AS
BEGIN
	set nocount on
	declare @sql as varchar(3000)
	set @sql = 'SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE Employee_Code_Id = N''' + @EmpCode + '''' + (CASE WHEN @ApplnMode = 1 THEN 'AND Isdeleted = 0' ELSE '' END)
    exec(@sql)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckDuplicateEmployeeCodeupdate  
Description : check employee code is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007  
Modified By :  A.K.T.MOORTHI
Modified On :  08-Apr-2014
Description  :  When Demo Mode Remove Condition For IsDeleted = 0 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate] 
(
@EmpCode NVARCHAR(15),
@Empid int,
@ApplnMode BIT
)
AS
declare @sql as varchar(3000)
BEGIN
	set @sql = 'SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE Employee_Code_Id=N'''+@EmpCode+''' AND Employee_Id<>' + CAST(@Empid as nvarchar(25)) +  (CASE WHEN @ApplnMode = 1 THEN 'AND Isdeleted = 0' ELSE '' END)
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
Procedure Name : Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate    
Description : check employee code is already there or not to avoid duplication    
Tables Included : TA_Tbl_Employee    
Created By : Arun Vinoth.T    
Created On : 27-Aug-2007    
Modified By :    
Modified On :    
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]   
(  
@SwipeCardNo NVARCHAR(15),  
@Empid nvarchar(15),
@inType nvarchar(15)
)  
AS  
  BEGIN  
declare @sql as varchar(3000)  
if(@inType='Add') 
BEGIN  
 set @sql = 'SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE SwipeCardNo=N'''+@SwipeCardNo+''' AND Isdeleted=0'  
END  
else if (@inType='Modify')
BEGIN  
 set @sql = 'SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE SwipeCardNo=N'''+@SwipeCardNo+''' AND Employee_Id<>'+cast(@Empid as nvarchar(25))+' AND Isdeleted=0'  
END  
 exec(@sql)  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_checkDuplicationUsergroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_checkDuplicationUsergroup  
Description : Checking for duplication of usergroup 
Tables Included : ta_tbl_usergroup  
Created By : Senthil  
Created On : 13-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_checkDuplicationUsergroup]
	(
		@groupName nvarchar(100)
	)
AS
BEGIN
		select groupName  as recCount from ta_tbl_usergroup where groupName=@groupName and isdeleted !=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEmployeePFESI]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckEmployeePFESI  
Description : Select PF Eligible, ESI Eligible for an Employee for a given Swipe Card No.
Tables Included : TA_Tbl_Employee  
Created By : Kumuthini.L
Created On : 22-Apr-2008
Modified By : 
Modified On :
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckEmployeePFESI] 
(
   @SwipeCardNo NVARCHAR(10)
)
AS
     SELECT PF_Eligible,ESI_Eligible  FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND IsDeleted = 0
     AND SwipeCardNo = @SwipeCardNo
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckEntrance_Delete
Description	:	Checking the entrance In Terminal and out Terminal Mapped in TA_Tbl_Clk_RawData
Tables Included	:	ta_tbl_entrance Ta_tbl_Terminal and TA_Tbl_Clk_RawData
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:  R.Manikandan
Modified On	:  22-11-2016 16.53
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Delete]    
( 
    @EntranceId int   
)     
As    
BEGIN    
	SET NOCOUNT ON
	DECLARE @Count AS INT
	DECLARE @Count1 AS INT
	select @Count = Count(CLK_DEVICEID) from TA_Tbl_Clk_RawData C
	inner join TA_Tbl_Terminal t on C.CLK_DEVICEID=t.Terminal_ReaderID
	inner join TA_Tbl_Entrance_INOUTDetails e on t.Terminal_Id=e.Reader_Id 
	where e.Entrance_Id=@EntranceId and t.IsDeleted=0
	SELECT @Count1 = COUNT(M.ManualTimeEntry_Id) FROM TA_Tbl_Entrance_INOUTDetails E
	inner join TA_Tbl_ManualTimeEntry M on (E.Reader_Id = M.ManualTimeEntry_InReaderID OR E.Reader_Id = M.ManualTimeEntry_OutReaderID ) 
	WHERE E.Entrance_Id = @EntranceId 
	SELECT @Count + @Count1 AS EntranceReadersCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckEntrance_Insert
Description	:	Checking the entrance name already exists in the same level
Tables Included	:	ta_tbl_entrance
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:  R.Manikandan
Modified On	:23-11-2016	12.43
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Insert]    
(  
	@EntranceName as nvarchar(50),
	@OrgLevel as int
) 
AS   
 BEGIN    
   SET NOCOUNT ON
   Select Count(Entrance_Name) AS EntranceNameCount from TA_Tbl_entrance WHERE Entrance_Name=@EntranceName AND OrgLevel_Id = @OrgLevel
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckEntrance_Update
Description	:	Checking the entrance name already exists in the same level while updating
Tables Included	:	ta_tbl_entrance
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:   Manikandan.R       
Modified On	:   23-11-2016 12.43
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Update]    
( 
	@EntranceId INT,   
	@EntranceName NVARCHAR(50),
	@OrgLevel INT 
)     
AS    
BEGIN    
	SET NOCOUNT ON
	DECLARE @sql as nvarchar(2000)
	SET @sql='Select Count(Entrance_Name) AS EntranceNameCount FROM TA_Tbl_Entrance    
	WHERE Entrance_Id <> ' + cast(@EntranceId as nvarchar(20)) + ' AND Entrance_Name=N''' + @EntranceName + ''' AND OrgLevel_Id = ' + cast(@OrgLevel as nvarchar(20)) + ''    
	EXEC(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntranceMap]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_CheckEntranceMap]
(
@Entrance NVARCHAR(50)
)
AS
BEGIN
	SELECT COUNT (TerMap_Id) AS TID FROM TA_Tbl_TerminalMapping WHERE EntranceName=@Entrance AND IsDeleted=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckExactDuplicateRecordExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 11.59 AM>
-- Description:	<Checking Exact record already exists>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckExactDuplicateRecordExists]
	-- Add the parameters for the stored procedure here
	@Clk_Date datetime,
	@Clk_Time datetime,
	@Clk_CardId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Count(*) AS Count FROM TA_Tbl_ClockDetails WHERE ((Clk_OutDate = @Clk_Date AND Clk_OutTime = @Clk_Time) or (Clk_InDate = @Clk_Date AND Clk_InTime = @Clk_Time)) 
	AND Clk_EmpId = @Clk_CardId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckFileUpdatedorNot]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <20-Feb-2020>
-- Description:	<This Procedure check last updation of file for Abraj>
-- =============================================
--Proc_TA_CheckFileUpdatedorNot
--'C:\\Users\\Velumani\\Desktop\\Foldertest\\Emp\\tam_emp_30_01_2020.CSV','02-20-2020 10:41:38','02-18-2020 15:48:20'
create PROCEDURE [dbo].[Proc_TA_CheckFileUpdatedorNot]
(
	@PathwithFileName varchar(max), 
	@CreationDate datetime,
	@modifiedDate datetime
)
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS (SELECT UpdationId from Ta_Tbl_LastUpdationofFile_Samsung where filepath = @PathwithFileName and LastFileModifiedDate = @modifiedDate )
	BEGIN
		SELECT 'No' as IsUpdateorNewFile  --same file with no data updation, so no need to check file content
	END
	ELSE
	BEGIN
		SELECT 'yes' as IsUpdateorNewFile -- file with some data updation, so need to check file content
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckForHolidayForCollect]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11:39 AM>
-- Description:	<Checking holiday is declared for current date>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckForHolidayForCollect]
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
    Select Holiday_Id from TA_Tbl_Holiday where Holiday_FromDate <= @dtmDate and Holiday_ToDate >= @dtmDate and Holiday_Type = 'G' and IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGEOFencingUtilization]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckGEOFencingUtilization]
	@FencingID bigint
AS
BEGIN	
	SET NOCOUNT ON;
	select FencingId from TA_tbl_GeoFencingAllocation where FencingId=@FencingID	
END

--Create Table TA_tbl_GeoFencingAllocation (EmployeeId int,FencingId int,shiftDate varchar(20),FromDate varchar(20),Todate varchar(20),CreatedBy int,CreatedOn varchar(20),ModifyBy int,ModifyOn varchar(20),months int,years bigint)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGEOLocationUtilization]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-Aug-2020 10:21 AM,,>
-- Description:	<Which is used to check whether geo location was utilized for any one person or not>
-- Proc_TA_CheckGEOLocationUtilization 0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckGEOLocationUtilization]
	@LandMarkID bigint
AS
BEGIN	
	SET NOCOUNT ON;
	select LocationId from TA_tbl_ShiftAdd_Location where LocationId=@LandMarkID	
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckGlobalHoliday 'Y'
Description : check global holiday  
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting    
Created By : Janakaraj.P   
Created On : 20-Aug-2007  
Modified By :    
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGlobalHoliday](@HolidayType varchar(3))  
AS   
BEGIN  
	SET NOCOUNT ON	
	select isnull(SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1),0) as 'Days' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id  
	where h.Holiday_type=@HolidayType and h.Isdeleted=0 and ys.IsActive=1 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHolidayUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckGlobalHolidayUpdate  
Description : check global holiday while update
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGlobalHolidayUpdate]
(
	@HID int,
	@HolidayType varchar(3)
)  
AS  
BEGIN  
	select isnull(SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1),0) as 'Days' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type=@HolidayType and h.Holiday_Id<>@HID and  h.Isdeleted=0  and ys.IsActive=1
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckGradeName_Insert 
Description : check grade name before insert, is already there  
Tables Included : Ta_Tbl_Grade  
Created By : Arun Vinoth.T  
Created On : 21-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeName_Insert]      
( 
	@Grade_Name NVARCHAR(50)            
)       
AS	
BEGIN
	Declare @Isdel int      
	declare @sql as nvarchar(3000)
	SET @Isdel=0
	set @sql = 'SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N'''+@Grade_Name+''' '      
	exec(@sql)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name : Proc_TA_CheckGradeName_Update   
Description : check grade name before update, is already there    
Tables Included : Ta_Tbl_Grade    
Created By : Arun Vinoth.T    
Created On : 21-Aug-2007  
Modified By :
Modified On : 
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeName_Update]    
(    
	@GradeId int
)     
AS    
	Declare @Isdel int    
	declare @sql as nvarchar(3000)
	declare @Grade_Name NVARCHAR(50)         
	SET @Isdel=0    
BEGIN
	Select @Grade_Name=grade_name from TA_Tbl_Grade where Grade_ID=@GradeId 
	set @sql = 'SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N'''+@Grade_Name+''' AND Grade_ID<>'+cast(@GradeId as	nvarchar(250))+' '
	exec(@sql)    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Updates]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name : Proc_TA_CheckGradeName_Update   
Description : check grade name before update, is already there    
Tables Included : Ta_Tbl_Grade    
Created By : Arun Vinoth.T    
Created On : 21-Aug-2007  
Modified By :
Modified On : 
*/
create PROCEDURE [dbo].[Proc_TA_CheckGradeName_Updates]    
(    
	@GradeId int,@Grade_Name nvarchar(50)
)     
AS    
	Declare @Isdel int    
	declare @sql as nvarchar(3000)	    
	SET @Isdel=0    
BEGIN	
	set @sql = 'SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N'''+@Grade_Name+''' AND Grade_ID<>'+cast(@GradeId as	nvarchar(250))+' '
	exec(@sql)    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckGradeStandard 
Description : check grade name before insert, is already there  
Tables Included : Ta_Tbl_Grade  
Created By : Arun Vinoth.T  
Created On : 21-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeStandard]      
AS      
BEGIN      
declare @RecordCount as int
set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name='StandardGradeDefault' and Grade_Level=1 and IsDeleted=0)    
if(@RecordCount=0)
	begin
		insert into Ta_Tbl_Grade (Grade_Name,Grade_Level,Emp_ID,Isdeleted)
		values ('StandardGradeDefault','1','1','0')
	end
END      
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHalfDayLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by	:	Prabakaran.P
-- Created on	:	15-Mar-08
-- Description	:	Procedure to check the Half Day Leaves exist or not
-- Proc_TA_CheckHalfDayLeave 1224,'10/02/2013','10/04/2013','First half','First half'
CREATE PROCEDURE [dbo].[Proc_TA_CheckHalfDayLeave]
(
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@SessionFrom nvarchar(50),
	@SessionTo nvarchar(50)
)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @diff int
	declare @i int
	declare @fromdate datetime
	declare @Todate datetime
	declare @fromsession varchar(20)
	declare @tosession varchar(20)
	declare @count int	
	set @count=0	
	set @i=0
	set @fromdate=@Leave_FromDate 
	set @Todate=@Leave_ToDate	
	set @diff=(select DATEDIFF(d,@Leave_FromDate,@Leave_ToDate))	
	if(@diff=0)
		begin
			if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
				And(Leave_FromDate=@Leave_FromDate) and Status<>'Rejected')>0)
					begin						
						if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
							And(Leave_FromDate=@Leave_FromDate) and Status<>'Rejected')=1)
								begin								 
									select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
									And(Leave_FromDate=@Leave_FromDate) and Status<>'Rejected'
									if @fromsession=@SessionFrom
										begin
											set @count=@count+1
										end
									if @tosession=@SessionTo
										begin
											set @count=@count+1
										end
								end
						else
							begin
								set @count=@count+1
							end
					end
		end
	else
		begin
			while @i<=@diff 
				begin
					if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
				And(Leave_FromDate=@fromdate) and Status<>'Rejected')>0)
					begin
						if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
							And(Leave_FromDate=@fromdate) and Status<>'Rejected')=1)
								begin
									if(@fromdate=@Todate)
										begin									
											select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
											And(Leave_FromDate=@fromdate) and Status<>'Rejected'									
											if @fromsession='First half' and @tosession='First half'
												begin
													if(@SessionTo='Second half' or @SessionTo='First half')
														begin
															set @count=@count+1
														end
												end
											if @fromsession='Second half' and @tosession='Second half'
												begin
													if(@SessionTo='Second half')
														begin
															set @count=@count+1
														end
												end
											if @fromsession='First half' and @tosession='Second half'
												begin
													if(@SessionTo='Second half' or @SessionTo='First half')
														begin
															set @count=@count+1
														end
												end
										end
									else if(@fromdate=@Leave_FromDate)
										begin											
											select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
											And(Leave_FromDate=@fromdate) and Status<>'Rejected'																										if @fromsession='First half' and @tosession='First half'
												begin
													if(@SessionFrom='First half')
														begin
															set @count=@count+1
														end
												end
											if @fromsession='Second half' and @tosession='Second half'
												begin
													if(@SessionTo='Second half' or @SessionTo='First half')
														begin
															set @count=@count+1
														end
												end
											if @fromsession='First half' and @tosession='Second half'
												begin
													if(@SessionTo='Second half' or @SessionTo='First half')
														begin
															set @count=@count+1
														end
												end
										end
									else
										begin
											set @count=@count+1											
										end
								end
						else
							begin
								set @count=@count+1
							end
					end					
					set @fromdate=DATEADD(d,1,@fromdate)					
					set @i=@i+1	
				end
		end
		select @count as CS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayBasedOnLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		sashma
-- Create date: 07-Jul-2011
-- Description:	checks holiday based on organization in windows service.
--Modified by Manikandan.R on 12-11-2015 11:51 AM
--Commented existing coding and added new codings. --Flexible
-- =============================================
--Proc_TA_CheckHolidayBasedOnLevel '2019-08-02 00:00:00.000','2019-08-02 00:00:00.000','G',5
CREATE PROCEDURE [dbo].[Proc_TA_CheckHolidayBasedOnLevel]
(
 @FromDate datetime,
 @ToDate datetime,
 @HolidayType varchar(5),
 @EmployeeAutoId bigint
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @HolidayLevelId int
	CREATE TABLE #TempHoliday(LevelIds int)
	DECLARE @EmployeeLeveld int
	insert into #TempHoliday
	Select HC.LevelId from TA_tbl_Holiday H inner join TA_Tbl_HolidayChildTable HC
	on H.Holiday_Id=HC.Holiday_Id
	where	Holiday_FromDate <= @ToDate and Holiday_ToDate >= @FromDate and 
			Holiday_Type = @HolidayType and H.IsDeleted = 0	
	select @EmployeeLeveld=EL.LevelId from TA_Tbl_EmployeeLevel EL inner join TA_Tbl_Employee E 
	on E.Employee_Id=EL.EmployeeId where E.Isdeleted=0 and E.Employee_Id=@EmployeeAutoId and EffectiveDate<=@FromDate
	IF EXISTS(SELECT * FROM #TempHoliday WHERE LevelIds=@EmployeeLeveld)
	BEGIN 
				SELECT 1 as HolidayId, '' as HolidayDesc
	END
	Else
	Begin
			SELECT 0 as HolidayId, '' as HolidayDesc
	End

END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaycount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : Proc_TA_CheckHolidaycount  
Description : check holidays count
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckHolidaycount]
AS
BEGIN
	SET NOCOUNT ON
	SELECT COUNT(*) AS MaxCount  FROM TA_Tbl_Holiday WHERE Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForOnDuty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 15-02-2014
-- Description:	Check for holidays while onduty entry
-- =============================================
 CREATE procedure [dbo].[Proc_TA_CheckHolidayForOnDuty]
	@Date Varchar(15)
as 
BEGIN
	SET NOCOUNT ON;
	SELECT COUNT(*) as HolidayCount from TA_Tbl_Holiday where IsDeleted=0 And(@Date between Holiday_FromDate and Holiday_ToDate) and Holiday_Type='G'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		SASHMA
-- CREATE DATE: 07-JUL-2011
-- DESCRIPTION:	CHECKS HOLIDAY BASED ON ORGANIZATION IN WINDOWS SERVICE.  -- Nonflexible
-- =============================================
--Proc_TA_CheckHolidayForService '2019-08-02','G',93
CREATE PROCEDURE  [dbo].[Proc_TA_CheckHolidayForService]   
(
 @FROMDATE DATETIME,
 --@TODATE DATETIME,
 @HOLIDAYTYPE VARCHAR(5),
 @EMPLOYEEAUTOID BIGINT
)
AS
BEGIN
	SET NOCOUNT ON;
    DECLARE @HOLIDAYLEVELID INT
    DECLARE @employeelevelid INT
	SET @HOLIDAYLEVELID = -1
	select  @employeelevelid = EL.levelId from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 and emp.Employee_Id=@EMPLOYEEAUTOID group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@FROMDATE as nvarchar(50)), 102) and EL.LevelId is not null
	
	if not exists(SELECT hct.LevelId FROM TA_TBL_HOLIDAY 
	inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
	WHERE HOLIDAY_FROMDATE <= @FROMDATE
			AND HOLIDAY_TODATE >= @FROMDATE AND HOLIDAY_TYPE = 'G' AND ISDELETED = 0 and hct.LevelId=@employeelevelid)
		begin

			SET @HOLIDAYLEVELID = (SELECT top 1 hct.LevelId FROM TA_TBL_HOLIDAY 
			inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
			WHERE HOLIDAY_FROMDATE <= @FROMDATE
			AND HOLIDAY_TODATE >= @FROMDATE AND HOLIDAY_TYPE = 'G' AND ISDELETED = 0)		
		end
	else
		begin
		
			set @HOLIDAYLEVELID=@employeelevelid
		end
	IF((@HOLIDAYLEVELID <> '') OR (@HOLIDAYLEVELID IS NOT NULL))
		BEGIN

			CREATE TABLE #LEVELRIGHTS(LEVELID INT)
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD]('SUPERADMIN',@HOLIDAYLEVELID) AS LEVELID
			DECLARE @HOLIDAYID INT
			DECLARE @HOLIDAYDesc varchar(500)

			SELECT TOP 1 @HOLIDAYID =  H.HOLIDAY_ID, @HOLIDAYDesc = Holiday_Description 
			FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId			
			WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID			
			AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			AND H.HOLIDAY_TODATE >= @FROMDATE)			
			AND H.HOLIDAY_TYPE = 'G' AND H.ISDELETED = 0 
			and hct.LevelId=@HOLIDAYLEVELID

			--SET @HOLIDAYID = (SELECT TOP 1 H.HOLIDAY_ID FROM TA_TBL_EMPLOYEELEVEL EL
			--INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			--INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			--inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId
			--WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			--AND H.HOLIDAY_TODATE >= @FROMDATE) AND H.HOLIDAY_TYPE = 'G' AND H.ISDELETED = 0 and hct.LevelId=@HOLIDAYLEVELID)


			--SET @HOLIDAYDesc = (SELECT TOP 1 H.Holiday_Description FROM TA_TBL_EMPLOYEELEVEL EL
			--INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			--INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			--inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId
			--WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			--AND H.HOLIDAY_TODATE >= @FROMDATE) AND H.HOLIDAY_TYPE = 'G' AND H.ISDELETED = 0 and hct.LevelId=@HOLIDAYLEVELID)

			IF((@HOLIDAYID <> '') OR (@HOLIDAYID IS NOT NULL))
				BEGIN
		
					SELECT @HOLIDAYID as holidayId, @HOLIDAYDesc as HolidayDesc
				END
			ELSE
				BEGIN
					SELECT 0 as holidayId, '' as HolidayDesc
				END
			DROP TABLE #LEVELRIGHTS
		END
	ELSE
		BEGIN
			SELECT 0 as holidayId, '' as HolidayDesc
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: Proc_TA_CheckHolidays  'G','09/25/2008','10/31/2008','test'  
Description 	: check holidays count  
Tables Included : TA_Tbl_Holiday    
Created By 	: Janakaraj.P   
Created On 	: 20-Aug-2007  
Modified By	:    
Modified On 	:  
Proc_TA_CheckHolidays 'G','05/Dec/2016','09/Dec/2016','checking',1
*/  
CREATE procedure [dbo].[Proc_TA_CheckHolidays]
(
	@HolidayType nvarchar(2),
	@HolidayFdate nvarchar(20),
	@HolidayTodate nvarchar(20),
	@HolidayDescription nvarchar(50),
	@LevelId int
)
AS
BEGIN
	DECLARE @yearSetingId int
	SET @yearSetingId = 0
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	IF(@LevelId = 0)
	BEGIN	
		SELECT COUNT(*) as HCount FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
		where 
		(
			((TA_Tbl_Holiday.Holiday_FromDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0) 
			or 
			(TA_Tbl_Holiday.Holiday_ToDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId
		) 
		or 
		(TA_Tbl_Holiday.Holiday_Description= @HolidayDescription and TA_Tbl_Holiday.Isdeleted=0 and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
		or 
		(
			((@HolidayFdate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
		 or 
			(@HolidayTodate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId
		) 
	END
	ELSE
	BEGIN
 		SELECT COUNT(*) as HCount FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
		where 
		(
			((TA_Tbl_Holiday.Holiday_FromDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0) 
			or 
			(TA_Tbl_Holiday.Holiday_ToDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (hct.LevelId = @LevelId or hct.LevelId=0)
		) 
		or 
		(TA_Tbl_Holiday.Holiday_Description= @HolidayDescription and TA_Tbl_Holiday.Isdeleted=0 and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and 
		(hct.LevelId= @LevelId or hct.LevelId = 0)) 
		or 
		(
			((@HolidayFdate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
		 or 
			(@HolidayTodate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (hct.LevelId = @LevelId or hct.LevelId = 0)
		) 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays_GlobalDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sp_helptext N'Proc_TA_CheckHolidays_GlobalDate'
/*  
Created By  : Manjula.P  
Created Date : 11-Jun-2013  
Descriptions : For checking global holiday with global holiday date   
Proc_TA_CheckHolidays_GlobalDate '06/26/2013','06/26/2013','S'  
*/    
CREATE procedure [dbo].[Proc_TA_CheckHolidays_GlobalDate]  
(  
	@HolidayFdate nvarchar(20),  
	@HolidayTodate nvarchar(20),  
	@Mode varchar(10),  
	@HolidayId int  
)  
AS 
Begin
	DECLARE @yearSetingId int  
	SET @yearSetingId = 0  	
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	if(@Mode='S')  
	BEGIN  
		SELECT *  FROM TA_Tbl_Holiday   
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id  
		where Holiday_Type='G'  
		and Holiday_FromDate = @HolidayFdate and  Holiday_ToDate=@HolidayTodate    
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and Isdeleted=0  
		and Holiday_Id<>@HolidayId  
	END  
	else if(@Mode='M')  
	BEGIN  
		SELECT *  FROM TA_Tbl_Holiday   
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id  
		where Holiday_Type='G'  
		and  Holiday_FromDate between @HolidayFdate and  @HolidayTodate  
		and  Holiday_ToDate between @HolidayFdate and  @HolidayTodate  
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and Isdeleted=0  
		and Holiday_Id<>@HolidayId  
	END  	
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysRestore]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	:	Proc_TA_CheckHolidaysRestore  
Description 	:	check holidays Duplicate while Restore Proc_TA_CheckHolidaysRestore '136','Global Holiday','09/25/2008','10/01/2008','f'
Tables Included :	TA_Tbl_Holiday  
Created By 	:	Janakaraj.P 
Created On 	:	20-Aug-2007
Modified By 	:	Prabakaran.P  
Modified On 	:  	08-Feb-08
*/  
CREATE     PROCEDURE [dbo].[Proc_TA_CheckHolidaysRestore]      
(    
	@HolidayId int,    
	@HolidayType nvarchar(30),    
	@HolidayFdate datetime,  
	@HolidayTodate datetime,   
	@HolidayDescription nvarchar(50))      
AS      
BEGIN 
	Declare @Sql as varchar(2000)
	set @Sql=''
	set @Sql='SELECT COUNT(Holiday_Id) as HCount FROM TA_Tbl_Holiday where((((Holiday_FromDate between ''' + cast(@HolidayFdate as varchar(20)) + ''' and  ''' + cast(@HolidayTodate as varchar(20)) + ''') or (Holiday_ToDate between ''' + cast(@HolidayTodate as varchar(20)) + ''' and ''' + cast(@HolidayTodate as varchar(20)) + ''')) and Holiday_Id<>''' + cast(@HolidayId as varchar(100)) + ''') or ((Holiday_Description=N''' +  @HolidayDescription + ''' and Holiday_Id<>''' + cast(@HolidayId as varchar(100)) + '''))) and Isdeleted=0'
	EXEC(@Sql)
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysTempWeekDay]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	: Proc_TA_CheckHolidaysTempWeekDay  'G','09/25/2008','10/31/2008','test'  
Description 	: check weekday count  
Tables Included : TA_Tbl_TempWeekDay  
Created By 	: Prabakaran.P   
Created On 	: 09-Sep-2007  
Modified By	:    
Modified On :
*/  
CREATE    procedure [dbo].[Proc_TA_CheckHolidaysTempWeekDay]
(
	@HolidayFdate nvarchar(20),
	@HolidayTodate nvarchar(20)
)
AS
BEGIN
	SELECT COUNT(*) as TempWeekDayCount FROM TA_Tbl_TemWeekDay 
	where 
	(
		(TempWeekday_FromDate between @HolidayFdate and @HolidayTodate)
		or
		(TempWeekday_ToDate between @HolidayFdate and @HolidayTodate)
		or
		(@HolidayFdate between TempWeekday_FromDate and TempWeekday_ToDate)
		or
		(@HolidayTodate between TempWeekday_FromDate and TempWeekday_ToDate)
	)
	and Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckHolidaysUpdate  
Description : check holidays updation
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
Proc_TA_CheckHolidaysUpdate  26,'Y','2013/12/06','2013/12/06','Dec 06',0
*/  
CREATE   procedure [dbo].[Proc_TA_CheckHolidaysUpdate]      
(    
	@HolidayId int,    
	@HolidayType nvarchar(2),    
	@HolidayFdate nvarchar(20),  
	@HolidayTodate nvarchar(20),   
	@HolidayDescription nvarchar(50),
	@LevelId int
)      
AS      
BEGIN 
	DECLARE @yearSetingId int      
	SET @yearSetingId = 0
	DECLARE @count1 int
	DECLARE @count2 int 
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	IF(@LevelId = 0)
		BEGIN
			SELECT @count1=COUNT(Holiday_Id) FROM TA_Tbl_Holiday 
			INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
			where     
			(((Holiday_FromDate between @HolidayFdate and @HolidayTodate) or (Holiday_ToDate between @HolidayFdate and @HolidayTodate) ) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId)  
			  or 
			  (Holiday_Description= @HolidayDescription and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
			or 
			(((@HolidayFdate between Holiday_FromDate and Holiday_ToDate) or (@HolidayTodate between Holiday_FromDate and Holiday_ToDate)) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
			SELECT @count2=COUNT(LeaveApplication_Id) FROM TA_Tbl_LeaveApplication where LeaveType_Id=@HolidayId and Type='Restricted Holiday' and Isdeleted=0 and Status <> 'Rejected'
			select @count1+@count2 as HCount 
		END
	ELSE
		BEGIN
			SELECT @count1=COUNT(Holiday_Id) FROM TA_Tbl_Holiday 
			INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
			where     
			(((Holiday_FromDate between @HolidayFdate and @HolidayTodate) or (Holiday_ToDate between @HolidayFdate and @HolidayTodate) ) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0))  
			  or 
			  (Holiday_Description= @HolidayDescription and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0)) 
			or 
			(((@HolidayFdate between Holiday_FromDate and Holiday_ToDate) or (@HolidayTodate between Holiday_FromDate and Holiday_ToDate)) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0)) 
			SELECT @count2=COUNT(LeaveApplication_Id) FROM TA_Tbl_LeaveApplication where LeaveType_Id=@HolidayId and Type='Restricted Holiday' and Isdeleted=0 and Status <> 'Rejected'
			select @count1+@count2 as HCount 
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 10.49 am>
-- Description:	<Checking ignore Duplicate punches point>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]
	-- Add the parameters for the stored procedure here
	@inShiftType bit, 
	@inClk_CardId varchar(50), 
	@inClk_Date varchar(50), 
	@inClk_Time varchar(50), 
	@strClockDate varchar(50), 
	@inClk_Type varchar(50),
	@gstrPunchInterval varchar(10)
AS
BEGIN
	SET NOCOUNT ON;
	if (@inShiftType=1) 	--Free Scan
    begin
        --Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for both IN & OUT Punches
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
        AND Clk_InDate=@inClk_Date
        AND ((@inClk_Time BETWEEN Clk_InTime AND Clk_InTime + @gstrPunchInterval)
        OR (@inClk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @gstrPunchInterval))
        AND Clk_Date=@strClockDate
	end
	else --Function Key
	begin
		if (@inClk_Type ='I')
		begin
			--Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for IN Punches
			SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
			AND Clk_InDate=@inClk_Date
			AND (@inClk_Time BETWEEN Clk_InTime AND Clk_InTime + @gstrPunchInterval)
			AND Clk_Date=@strClockDate
		end
		else
		begin
			--Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for OUT Punches
			SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
			AND Clk_InDate=@inClk_Date
			AND (@inClk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @gstrPunchInterval)
			AND Clk_Date=@strClockDate
		end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIndividualUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: Proc_TA_CheckIndividualUser  
Description 	: Checking whether the user is individual user or not
Tables Included : ta_tbl_userRights  
Created By 	: Prabakaran.P  
Created On 	: 08-July-2008
Modified By 	:  
Modified On 	:  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckIndividualUser]
(
	@UserGroupName varchar(250)
)
AS
BEGIN
	select count(*) as IndUserCount from TA_Tbl_Usergroup where (groupName=@UserGroupName and IndividualUsers=1 and Isdeleted=0) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@inClk_Date  varchar(20),
	@inClk_Time  varchar(20),
	@strINorOUTEntry char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @count int
    -- Insert statements for procedure here
    if (@strINorOUTEntry='I')
		begin
			select @count=count(*) from  TA_Tbl_ClockDetails where  Clk_EmpId= @inClk_EmpId and Clk_InDate = @inClk_Date
			and Clk_InTime = @inClk_Time
		end
	if (@strINorOUTEntry='O')
		begin
			select @count=count(*) from  TA_Tbl_ClockDetails where  Clk_EmpId= @inClk_EmpId and Clk_OutDate = @inClk_Date
			and Clk_OutTime = @inClk_Time
		end
	select @count  as RecordCount 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Any non mapped in data is exists or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]
	@strInDateTime varchar(20),
	@strOutDateTime varchar(20),
	@inClk_EmpId varchar(50),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='I')
	begin
		select count(*) as RecordCount from ta_tbl_clockdetails 
		where ((((Clk_InDate+Clk_InTime) > CONVERT(datetime,@strInDateTime) and ((Clk_InDate+Clk_InTime) < CONVERT(datetime,@strOutDateTime))) 
		or (((Clk_OutDate+Clk_OutTime) > CONVERT(datetime,@strInDateTime)) and ((Clk_OutDate+Clk_OutTime) < CONVERT(datetime,@strOutDateTime))))) 
		and Clk_EmpId = @inClk_EmpId AND IsVoid=0
	end
	else
	begin
		select count(*) as RecordCount from ta_tbl_clockdetails 
		where ((((Clk_InDate+Clk_InTime) > CONVERT(datetime,@strInDateTime) and ((Clk_InDate+Clk_InTime) < CONVERT(datetime,@strOutDateTime))) 
		or (((Clk_OutDate+Clk_OutTime) > CONVERT(datetime,@strInDateTime)) and ((Clk_OutDate+Clk_OutTime) < CONVERT(datetime,@strOutDateTime)))))
		and Clk_EmpId = @inClk_EmpId AND IsVoid=0
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016 13:17>
-- Description:	Check in the TimeCheck Processed Data whether there are records for appropriate EmployeeId and Date
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]
	@Clk_EmpId varchar(50),
	@ClockDate varchar(20),
	@Datafrom char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Datafrom='I')
	begin	
		Select Employee_Code_Id,CONVERT(varchar(25), Date,120) as Date,InTime,LateIn,InNotation 
		from TA_Tbl_ProcessedData where Employee_Code_Id = @Clk_EmpId and Date = CONVERT(datetime,@ClockDate)
	end
	else
	begin
		Select Employee_Code_Id,convert(varchar(25),Date,120) as Date,OutTime,OutNotation 
		from TA_Tbl_ProcessedData where Employee_Code_Id = @Clk_EmpId and Date = CONVERT(datetime,@ClockDate)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsAlready]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Data is already available in clockdetails or not>
-- Proc_TA_CheckingDataExistsAlready 1053,'54391,57794,57679,57789,787','11/03/2016 04:35 PM','11/03/2016','o'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataExistsAlready]
	@inClk_EmpId varchar(50),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@gstrClockDate varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
    if @Type='I'
    begin
		SELECT Top 1 Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
		AND (Clk_InTime = '' OR Clk_InTime IS NULL) AND Clk_OutDate <> '' AND Clk_OutDate IS NOT NULL AND Clk_OutDeviceId IN (select * from SplitupEmployeeCode(@strOutDeviceId)) 
		AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND Clk_Date= CONVERT(datetime,@gstrClockDate) AND IsVoid=0 
		ORDER BY (Clk_OutDate+Clk_OutTime) ASC
	end
	else if @Type='O'
	begin
		SELECT Top 1 Clk_Id,Clk_Date,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
		AND (Clk_OutTime = '' OR Clk_OutTime IS NULL) AND Clk_InDate <> '' AND Clk_InDate IS NOT NULL AND Clk_InDeviceId IN (select * from SplitupEmployeeCode(@strOutDeviceId))
		AND (Clk_InDate+Clk_InTime) <= Cast(@strInDateTime as DateTime) and Clk_Date=CONVERT(datetime,@gstrClockDate) AND IsVoid=0
		ORDER BY (Clk_InDate+Clk_InTime) DESC
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Data is alread Exists or not for processing>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]
	@PunchType char(1),
	@inClk_EmpId varchar(50),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
    if @PunchType='I'
    begin 
		select count(*) as RecordCount from  TA_Tbl_ClockDetails 
		where  Clk_EmpId= @inClk_EmpId and Clk_InDate =convert(datetime,@inClk_Date) 
		and Clk_InTime = CONVERT(datetime,@inClk_Time)
	end
	else
	begin
		select count(*) as RecordCount from  TA_Tbl_ClockDetails 
		where  Clk_EmpId= @inClk_EmpId and Clk_OutDate =CONVERT(datetime,@inClk_Date) 
		and Clk_OutTime =CONVERT(datetime,@inClk_Time)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 12.05 PM>
-- Description:	<Checking Device Mapping in Entrance>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]
	-- Add the parameters for the stored procedure here
	@Clk_DeviceId nvarchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='C')
	begin
		select count(TYPE)as count from ta_tbl_entrance_inoutdetails EIO 
		inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
		where T.Terminal_ReaderID=@Clk_DeviceId
	end
	else
	begin
		select TYPE from ta_tbl_entrance_inoutdetails EIO 
		inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
		where T.Terminal_ReaderID=@Clk_DeviceId
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingEachDropDown]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingEachDropDown]
	-- Add the parameters for the stored procedure here
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT count(*) from Ta_Tbl_levelDetails where parentId=@ParentId and isDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking Employee Availed In Clock Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]
	@inClk_EmpId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	Select Clk_EmpId from TA_Tbl_ClockDetails WHERE Clk_EmpId =@inClk_EmpId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<CheckingEmployeeRecordAvailedForParticularDate>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]
	@inClk_EmpId varchar(50),
	@InReaderID varchar(50),
	@InDate varchar(20),
	@InTime varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='I')
	begin
		Select Clk_EmpId from TA_Tbl_ClockDetails where Clk_EmpId = @inClk_EmpId
		and Clk_InDeviceId =(select Terminal_ReaderID from ta_tbl_terminal where Terminal_Id= @InReaderID) 
		and Clk_InDate = cast(@InDate as datetime) and clk_InTime = cast(@InTime as datetime) 
	end
	if(@Type='O')
	begin
		Select Clk_EmpId from TA_Tbl_ClockDetails where Clk_EmpId = @inClk_EmpId
		and Clk_OutDeviceId =(select Terminal_ReaderID from ta_tbl_terminal where Terminal_Id= @InReaderID) 
		and Clk_OutDate =cast(@InDate as datetime)  and clk_OutTime=cast(@InTime as datetime)	
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingIgnorePunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	 Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for both IN & OUT Punches                          
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingIgnorePunches]
	-- Add the parameters for the stored procedure here
	@Clk_CardId varchar(50),
	@Clk_Date varchar(20),
	@Clk_Time varchar(10),
	@PunchInterval varchar(10),
	@ClockDate varchar(20),
	@DataFrom char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@DataFrom='FS')
	begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND ((@Clk_Time BETWEEN Clk_InTime AND Clk_InTime + @PunchInterval)
		OR (@Clk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @PunchInterval))
		AND Clk_Date=@ClockDate
    end
    else if(@DataFrom='FKI')
    begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND (@Clk_Time BETWEEN Clk_InTime AND Clk_InTime + @PunchInterval)
		AND Clk_Date=@ClockDate
	end
	else if(@DataFrom='FKO')
	begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND (@Clk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @PunchInterval)
		AND Clk_Date=@ClockDate                           
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_Id FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
	AND (CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) <= Cast(@strDateTime as DateTime)) 
	AND (CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + convert(char(10), Clk_OutTime, 108)) >= Cast(@strDateTime as DateTime)) 
	AND IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Clk_Id,(Clk_OutDate+Clk_OutTime) as PunchDateTime,'Out' as Type from TA_Tbl_Clockdetails where (Clk_OutDate+Clk_OutTime) = 
	(select MAX(Clk_OutDate+Clk_OutTime) from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) < Cast(@strDateTime as DateTime)
	and Clk_EmpId = @inClk_EmpId and IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) 
	and Clk_EmpId = @inClk_EmpId 
	UNION 
	select Clk_Id,(Clk_InDate+Clk_InTime) as PunchDateTime,'In' as Type from TA_Tbl_Clockdetails where (Clk_InDate+Clk_InTime)=
	(select MIN(Clk_InDate+Clk_InTime) from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) > Cast(@strDateTime as DateTime)
	and Clk_EmpId = @inClk_EmpId and IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) and Clk_EmpId =@inClk_EmpId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Clk_Id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) as InDateTime from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) = 
	(select MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108))) from TA_Tbl_Clockdetails
	where Clk_EmpId = @inClk_EmpId 
	AND CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) > CAST(@strDateTime AS DateTime) 
	AND IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) and Clk_EmpId =@inClk_EmpId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) AS InDateTime,Clk_OutDate,'F' as Type 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND (Clk_InDate+Clk_Intime) = (SELECT MAX(Clk_InDate+Clk_InTime) 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND (clk_indate+Clk_intime) < CAST(@strDateTime AS DateTime) AND Clk_OutDate IS NULL and IsVoid = 0)
	UNION 
	SELECT Clk_id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + convert(char(10), Clk_InTime, 108)) AS InDateTime,Clk_OutDate,'S' as Type FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inClk_EmpId AND (Clk_Indate+Clk_Intime) = (SELECT MIN(Clk_InDate+Clk_InTime) FROM TA_Tbl_ClockDetails WHERE clk_empid = @inClk_EmpId and IsVoid = 0 
	AND (Clk_Indate+Clk_Intime) > CAST(@strDateTime AS DateTime))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016>
-- Description:	<Checking whether permission applied during the shift start time>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]
	@gintShiftId int,
	@Shift_StartTime varchar(50),
	@Permission_FromTime varchar(50),
	@Permission_ToTime varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_Id = @gintShiftId AND CONVERT(DATETIME,@Shift_StartTime) 
	BETWEEN @Permission_FromTime AND @Permission_ToTime
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>

-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime 'Early Exit',1


-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime 'Absent - Single Day',2
-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime 'Continuous Absent',6
-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime 'Late Entry',2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]
	-- Add the parameters for the stored procedure here
	@TemplateName VARCHAR(50),
	@ShiftID INT
AS
BEGIN
	SET NOCOUNT ON;	
	if not exists(
	select sl.Status from TA_Tbl_SMSLogDetails SL 
	inner join ta_tbl_Smstemplates ST on ST.id=SL.TemplateId 
	where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and sl.status=1 and ST.TemplateName=@TemplateName 
	and ShiftId=@ShiftID and ST.TemplateName!='Late Entry')
	begin	
		if exists(select sl.Status from TA_Tbl_SMSLogDetails SL 
		inner join ta_tbl_Smstemplates ST on ST.id=SL.TemplateId 
		where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and sl.status=1 and ST.TemplateName='Continuous Absent')
		begin
			select 0
			return
		end
		DECLARE @FirstTriggeringTime DATETIME
		DECLARE @ShiftTiming DATETIME
		DECLARE @TriggeringTime DATETIME
		DECLARE @TemplateID int
		DECLARE @NextTriggeringTime DATETIME
		DECLARE @LessHrsLimitation VARCHAR(5)	
		DECLARE @lesshrsLimitationInMins INT
		DECLARE @TagName VARCHAR(50)
		if(@TemplateName='Late Entry')
		begin
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1   --active template need to take
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0  -- active shift shift starttime
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming		
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		-- today date add shift shift starttime
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
			if not exists(select top 1 logid from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID 
			and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and ShiftId=@ShiftID and Status=1)
			begin
				set @TriggeringTime=@TriggeringTime
			end
			else
			begin
				SELECT top 1 @NextTriggeringTime= NextTriggeringTime from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
				and Status=1 and ShiftId=@ShiftID
				order by logid desc			
				set @TriggeringTime=@NextTriggeringTime	
			end
		end	
		if(@TemplateName='Early Exit')
		begin
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming		
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName='Less Hours Worked')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@LessHrsLimitation=LessHrsLimitation 
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName='Absent - Single Day')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName='Continuous Absent')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		end
		if(@TriggeringTime<=GETDATE())
		begin
			select 1
		end
		else 
		begin
			select 0
		end
	end
	else
	begin
		select 1000000
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Specific device punch Type detail status>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]
	@inClk_DeviceId varchar(20),
	@inClk_Type varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	select P.PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID = @inClk_DeviceId and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]	
	@blnIsPMAM int,
	@dtmActualShiftStartTime datetime,
	@dtmShiftEndTime datetime,
	@levelId int,
	@Is24Hrs int
AS
BEGIN	
		SET NOCOUNT ON;    
		if (@blnIsPMAM=1)
		begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T
			inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate between @dtmActualShiftStartTime and @dtmShiftEndTime)
			AND T.IsDeleted = 0 AND TL.LevelId=@levelId AND @dtmActualShiftStartTime Between  T.TempWeekday_FromDate And T.TempWeekday_ToDate
		end
		else if (@Is24Hrs=1)
        begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T
            inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate = @dtmActualShiftStartTime)
            AND T.IsDeleted = 0 AND TL.LevelId=@levelId
		end
		else
        begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T 
			inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate <= @dtmActualShiftStartTime and T.TempWeekday_ToDate >= @dtmActualShiftStartTime) AND T.IsDeleted = 0 
			AND TL.LevelId=@levelId
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingTerminalStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Terminal status using Terminal ID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingTerminalStatus]
	-- Add the parameters for the stored procedure here
	@Terminal_ReaderID nvarchar(20),
	@inClk_Type varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
    Declare @Status int
	Declare @PunchType varchar(50)
	select @Status=IsDeleted from TA_Tbl_Terminal T where T.Terminal_ReaderID = convert(varchar(20),@Terminal_ReaderID) and T.IsDeleted = 0
	select @PunchType=P.PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID = @Terminal_ReaderID and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
	select isnull(@Status,1) as Status,@PunchType as PunchType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeave_Insert  
Description : check leave before insert, is alraedy there   
Tables Included : TA_Tbl_LeaveType  
Created By : Arun Vinoth T  
Created On : 14-Aug-2007
Modified By :  Karthikeyan.R
Modified On :  23-11-2016
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeave_Insert]  
(  
	@LeaveType NVARCHAR(50)
)   
As  
 BEGIN  
	SET NOCOUNT ON;
	Select Count(LeaveType)as Ltype from TA_Tbl_LeaveType where LeaveType=@LeaveType
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeave_Update 'CL',3
Description : check leave before update, is alraedy there   
Tables Included : TA_Tbl_LeaveType  
Created By : Arun Vinoth T  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeave_Update]    
(    
 @LeaveType NVARCHAR(50),    
 @Type_Id int    
)     
As    
 BEGIN    
  SET NOCOUNT ON;
   Select Count(LeaveType)as Ltype from TA_Tbl_LeaveType where LeaveType_Id<> cast(@Type_Id as nvarchar(20)) And LeaveType= @LeaveType 
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy 5,'01-Aug-2008','31-Dec-2016'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]
	-- Add the parameters for the stored procedure here
	@intEmpId int, 
	@leavePolicyFromDate nvarchar(25),
	@leavePolicyToDate nvarchar(25)
AS
	DECLARE @flag as int 
	DECLARE @count as int
	SET @flag = 0
	SET @count = 0
BEGIN
	SET NOCOUNT ON;
	SELECT @count =count(*) FROM TA_Tbl_LeaveApplication 
	WHERE Employee_Id = @intEmpId And IsDeleted = 0 
	And 
	((
	Leave_FromDate between CONVERT(DATETIME,@leavePolicyFromDate,102) And CONVERT(DATETIME,@leavePolicyToDate,102)
	) 
	or 
	(
	Leave_ToDate between CONVERT(DATETIME,@leavePolicyFromDate,102) And CONVERT(DATETIME,@leavePolicyToDate,102)
	))
	IF(@count=0)
		BEGIN
			SELECT @count = count(*) FROM TA_Tbl_Permission WHERE Employee_Id =@intEmpId And IsDeleted=0 And (Permission_Date >=  CONVERT(DATETIME,@leavePolicyFromDate,102) AND Permission_Date <=  CONVERT(DATETIME,@leavePolicyToDate,102))
		END
	SELECT @count as mappedCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Created Date	:	16-Dec-2013
-- Description	:	Check The Leave And Permission Exists When Deleted Date(Reg Bug No 0020677, 0020676).
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId=1,@FromDate='2012/12/17',@ToDate='2013/12/31'
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId='346, 345',@FromDate='12/24/2013',@ToDate='12/24/2013',@Func='SEC'
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId='<DocumentElement><Table><EmployeeAutoID>346</EmployeeAutoID></Table></DocumentElement>',@FromDate='2013/12/19',@ToDate='2013/12/31',@Func='SRA'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]
	@EmployeeId VARCHAR(MAX),
	@FromDate VARCHAR(25),
	@ToDate VARCHAR(25),
	@Func VARCHAR(5)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@Func = 'SD')
	BEGIN
		SELECT 'ShiftDelete_Check_Permission' [Message] FROM TA_Tbl_Permission P		
		INNER JOIN TA_Tbl_TempShiftAllocation TSA ON TSA.EmpID = P.Employee_Id
		WHERE TSA.LoginEmployeeId = CAST(@EmployeeId AS BIGINT) AND P.Permission_Status = 'Approved' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)
		UNION
		SELECT 'ShiftDelete_Check_Leave' [Message] FROM TA_Tbl_LeaveApplication LA
		INNER JOIN TA_Tbl_TempShiftAllocation TSA ON TSA.EmpID = LA.Employee_Id
		WHERE TSA.LoginEmployeeId = CAST(@EmployeeId AS BIGINT) AND [Status] = 'Approved' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)))
	END
	ELSE IF(@Func = 'SEC')
	BEGIN
		DECLARE @Query VARCHAR(MAX)
		SET @Query = 'SELECT ''ShiftExchange_Check_Permission'' [Message] FROM TA_Tbl_Permission P		
			WHERE P.Employee_Id IN(' + @EmployeeId + ') AND P.Permission_Status = ''Approved'' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), ''' + @FromDate + ''', 102) AND CONVERT(VARCHAR(11), ''' + @ToDate + ''', 102)
			UNION
			SELECT ''ShiftExchange_Check_Leave'' [Message] FROM TA_Tbl_LeaveApplication LA
			WHERE LA.Employee_Id IN(' + @EmployeeId + ') AND [Status] = ''Approved'' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), ''' + @FromDate + ''', 102) AND CONVERT(VARCHAR(11), ''' + @ToDate + ''', 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), ''' + @FromDate + ''', 102) AND CONVERT(VARCHAR(11), ''' + @ToDate + ''', 102)))'
		EXEC(@Query)
	END
	ELSE IF(@Func = 'SRA')
	BEGIN
		DECLARE @XML XML
		DECLARE @Index INT
		CREATE TABLE #TempEmployeeId(Employee_Id BIGINT)
		SET @XML = @EmployeeId
		SET @Index = 0
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO #TempEmployeeId
			SELECT Emp.EmployeeAutoID FROM OPENXML(@Index, '/DocumentElement/Table') WITH(EmployeeAutoID BIGINT 'EmployeeAutoID') AS Emp
		EXEC sp_xml_removedocument @Index
		SELECT 'ShiftReAlloc_Check_Permission' [Message] FROM TA_Tbl_Permission P
			INNER JOIN #TempEmployeeId E ON E.Employee_Id = P.Employee_Id
		WHERE P.Permission_Status = 'Approved' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), @FromDate , 102) AND CONVERT(VARCHAR(11), @ToDate, 102)
		UNION
		SELECT 'ShiftReAlloc_Check_Leave' [Message] FROM TA_Tbl_LeaveApplication LA
		INNER JOIN #TempEmployeeId E ON E.Employee_Id = LA.Employee_Id
		WHERE [Status] = 'Approved' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)))
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeaveApplication    
Description : check leave application is already there or not   
Tables Included : TA_Tbl_LeaveApplication    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By : Manikandan.R   
Modified On : 2012-Mar-03
*/  
--[Proc_TA_CheckLeaveApplication] 3,'2015-09-30','2016-09-30'

CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication]
(
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@LeaveType int
)
AS
BEGIN
	SET NOCOUNT ON;
	if exists(Select * from TA_Tbl_LeaveType where LeaveType_Id=@LeaveType and isnull(isWFH,0)=1)
		begin
			select COUNT(*)  as CS from TA_Tbl_LeaveApplication LA 
			Left outer join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			inner join TA_Tbl_LeaveApplicationExists LAE on LA.Employee_Id=LAE.Employee_Id and la.LeaveApplication_Id=lae.LeaveApplicationId where LA.Employee_Id =cast(@Employee_Id as nvarchar(5)) And LAE.IsDeleted=0 and LAE.Status<>'Rejected' AND ((LAE.Leave_FromDate between(CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))   , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102))) or (LAE.Leave_ToDate between (CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))  , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102)))) and isnull(LT.isWFH,0)=1
		end
	else
		begin
			select COUNT(*)  as CS from TA_Tbl_LeaveApplication LA 
			Left outer join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			inner join TA_Tbl_LeaveApplicationExists LAE on LA.Employee_Id=LAE.Employee_Id and la.LeaveApplication_Id=lae.LeaveApplicationId where LA.Employee_Id =cast(@Employee_Id as nvarchar(5)) And LAE.IsDeleted=0 and LAE.Status<>'Rejected' AND ((LAE.Leave_FromDate between(CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))   , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102))) or (LAE.Leave_ToDate between (CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))  , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102)))) and isnull(LT.isWFH,0)=0
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckLeaveApplication  
Description : Angler Timecheck
Tables Included : TA_Tbl_LeaveApplication  
Created By : Karthikeyan  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
Proc_TA_CheckLeaveApplication -1,32,'01/20/2010','01/20/2010','Second Half','Second Half'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication_Angler]
(
@leaveApplicationId int,
@Employee_Id int,
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@SessionFrom nvarchar(50),
@SessionTo nvarchar(50)
)
 AS
begin
SET NOCOUNT ON;
declare @intCount as int
declare @intCount1 as int
declare @intCount2 as int
declare @intCount3 as int
declare @intCount4 as int
set @intCount=0
set @intCount1=0
set @intCount2=0
set @intCount3=0
set @intCount4=0
if(@leaveApplicationId=-1)
BEGIN
set @intCount = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected'
And
(
(@Leave_FromDate > Leave_FromDate and @Leave_FromDate<Leave_ToDate)
or
(@Leave_ToDate > Leave_FromDate and @Leave_ToDate<Leave_ToDate)
or
(Leave_FromDate > @Leave_FromDate and Leave_FromDate<@Leave_ToDate)
or
(Leave_ToDate > @Leave_FromDate and Leave_ToDate<@Leave_ToDate)
))
if(@intCount=0)
	begin
		set @intCount1 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected'
		And
		(
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount2 = (select COUNT(*) as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected'
		And
		(
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionTo)
		)
		)
		set @intCount3 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected'
		And
		(
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount4 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected'
		And
		(
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionTo)
		))
	end
else
	BEGIN
	select @intCount as CS
	END
if(@intCount1=0 and @intCount2=0 and @intCount3=0 and @intCount4=0)
BEGIN
select '0' as CS
END
else
BEGIN
select '1' as CS
END
END
ELSE
BEGIN
	set @intCount = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected' and LeaveApplication_Id<>@leaveApplicationId
And
(
(@Leave_FromDate > Leave_FromDate and @Leave_FromDate<Leave_ToDate)
or
(@Leave_ToDate > Leave_FromDate and @Leave_ToDate<Leave_ToDate)
or
(Leave_FromDate > @Leave_FromDate and Leave_FromDate<@Leave_ToDate)
or
(Leave_ToDate > @Leave_FromDate and Leave_ToDate<@Leave_ToDate)
))
if(@intCount=0)
	begin
		set @intCount1 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount2 = (select COUNT(*) as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionTo)
		)
		)
		set @intCount3 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount4 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>'Rejected' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionTo)
		))
	end
else
	BEGIN
	select @intCount as CS
	END
if(@intCount1=0 and @intCount2=0 and @intCount3=0 and @intCount4=0)
BEGIN
select '0' as CS
END
else
BEGIN
select '1' as CS
END
END
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	02-07-2013
-- Description		:	Change The Query
-- Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat -1, 396, '5/Jul/2013', '5/Jul/2013', 'First Half', 'First Half'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]
	@leaveApplicationId int,
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@SessionFrom nvarchar(50),
	@SessionTo nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @intCount as int
	set @intCount=0
	if(@leaveApplicationId=-1)
		BEGIN
			SELECT 
				@intCount = CASE WHEN Leave_FromDate = @Leave_FromDate AND Leave_ToDate = @Leave_ToDate THEN 0 ELSE COUNT(LeaveApplication_Id) END from TA_Tbl_LeaveApplication 
			WHERE Employee_Id = @Employee_Id AND IsDeleted = 0 AND [Status] <> 'Rejected' AND
				Leave_FromDate = @Leave_FromDate and Leave_ToDate = @Leave_ToDate
			GROUP BY Leave_FromDate, Leave_ToDate
		end
	select @intCount as CS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeaveApplicationRestrictedHolidays    
Description : check leave application on restricted holidays   
Tables Included : TA_Tbl_LeaveApplication    
Created By : Prabakaran.P    
Created On : 14-Aug-2007  
Modified By :    
Modified On :  
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays](@Employee_Id int,@HolidayId int)
AS
BEGIN
	SET NOCOUNT ON;
	select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id =@Employee_Id And IsDeleted=0 And 
	LeaveType_Id=@HolidayId and Type='Restricted Holiday' and Status<>'Rejected'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : Proc_TA_CheckLeaveApplicationUpdate  
Description : check leave application before update, is already there or not 
Tables Included : TA_Tbl_LeaveApplication  
Created By : Prabakaran.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationUpdate](@LID int,@Employee_Id int,@Leave_FromDate datetime,@Leave_ToDate datetime)
 AS
	begin
		SET NOCOUNT ON;
		select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id =@Employee_Id and LeaveApplication_Id<>@LID  And IsDeleted=0 And (( Leave_FromDate  between @Leave_FromDate And @Leave_ToDate) or (Leave_ToDate between @Leave_FromDate And @Leave_ToDate))
	end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckLeaveBeforeAfterWithPermission '02/19/2008','02/20/2008','LeaveOnPermission',5
Description		:	Check Permission Count for Before or After Leave Dates
Tables Included	:	TA_Tbl_Permission
Created By		:	Kumuthini.L
Created On		:	05-Sep-08
Modified By		:	Sasireka.M
Modified On		:	25.04.09
*/
-- [Proc_TA_CheckLeaveBeforeAfterWithPermission] '09/17/2008','09/17/2008','LeaveAfterPermission','152'
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]
@LeaveFromDate datetime,
@LeaveToDate datetime,
@LeaveType nvarchar(50),
@EmployeeId int
as
BEGIN
SET NOCOUNT ON;
	declare @Count as int
	if(@LeaveType='LeaveBeforePermission')
	-- Check Leave falls Before Permission
		BEGIN
			select * from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,1,@LeaveToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END
	else if(@LeaveType='LeaveAfterPermission')
	-- Check Leave falls After Permission
		BEGIN
			select * from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,-1,@LeaveFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END 
	else if(@LeaveType='LeaveOnPermission')
	-- Check Leave and Permission on same day
		BEGIN
			select * from TA_Tbl_Permission
			where (Permission_Date between  @LeaveFromDate and @LeaveToDate)
			and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name  : Proc_TA_CheckLeaveExistsBeforeBorrow '06/09/2008 12:00:00 AM','06/10/2008 12:00:00 AM',2    
Description  : Check normal Leave Exists Before Borrow leave    
Tables Included  : TA_Tbl_LeaveApplication    
Created By  : Prabakaran    
Created On  : 10-Sep-08    
Modified By  :     
Modified On  :     
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]     
@LeaveFromDate datetime,    
@LeaveToDate datetime,   
@LeaveTypeId int,   
@EmployeeId int    
as    
declare @Count as int    
SET NOCOUNT ON;
-- Check normal Leave Exists Before Borrow leave    
 BEGIN    
  set @Count=(select count(LeaveApplication_Id) from TA_Tbl_LeaveApplication la  
inner join TA_Tbl_YearSetting ys on  ys.YearSettings_Id=la.YearSettings_Id  
  where   
--(Leave_FromDate < @LeaveFromDate or Leave_FromDate < @LeaveToDate or Leave_ToDate < @LeaveFromDate or Leave_ToDate < @LeaveToDate)   and   
la.Employee_Id=@EmployeeId and la.Isdeleted=0 and la.Type='Leave'  
and la.LeaveType_Id=@LeaveTypeId  
  and la.Status in('Pending','Forwarded') and la.IsBorrow=0 and ys.IsActive=1)    
  select @Count as LeaveCount    
 END     
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForGivenDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name	: Proc_TA_CheckLeaveForGivenDate  
Description		: check leave for given date 
Tables Included              : TA_Tbl_LeaveApplication, TA_Tbl_Employee  
Created By		: Prabakaran.P  
Created On		: 14-Aug-2007
Modified By		:  
Modified On		:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForGivenDate] 
(
   @SwipeCardNo Varchar(15),
   @Date DateTime
)
AS
begin
SET NOCOUNT ON;
SELECT la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate FROM TA_Tbl_LeaveApplication la,TA_Tbl_Employee emp WHERE la.Employee_Id = emp.Employee_Id AND emp.SwipeCardNo = @SwipeCardNo AND la.Leave_FromDate <= @Date AND la.Leave_ToDate >= @Date AND la.Status = 'Approved' AND la.IsDeleted = 0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : Proc_TA_CheckLeaveForManualEntry  'ot2','9/03/2012','9/03/2012'
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Gopinath.k   
Created On : 03-Feb-2014
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15)
)
AS
BEGIN  	
	SET NOCOUNT ON;
	SELECT COUNT(*) as ManualEntry FROM TA_Tbl_LeaveApplication P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE P.Status = 'Approved' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
	((Cast(@ManualInDate as DateTime) between P.Leave_FromDate and P.Leave_ToDate))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : Proc_TA_CheckLeaveForManualEntry_OD  'ot2','9/03/2012','9/03/2012'
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Gopinath.k   
Created On : 03-Feb-2014
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15)
)
AS
BEGIN  	
	SET NOCOUNT ON;
	SELECT COUNT(*) as ManualEntry FROM TA_Tbl_LeaveApplication P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND 
	((Cast(@ManualInDate as DateTime) between P.Leave_FromDate and P.Leave_ToDate))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForOnDuty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		K.Gopinath
-- Create date: 12-02-2014
-- Description:	Check for leave entry sessions available to particular employee
--	Modified By		:	Manjula.P
--	Modified On		:	17-Feb-2014
--	Descriptinos	:	Changing @EmployeeCodeId datatype from int to varchar(50) to avoid error conversion failed server error  :0021751(timecheckV1.4)	 
--	Proc_TA_CheckLeaveForOnDuty '11/01/2016','100'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForOnDuty]
	@Date Varchar(15),
	@EmployeeCodeId varchar(50)
AS
BEGIN	
	SET NOCOUNT ON;
	IF((SELECT COUNT(*) from TA_Tbl_LeaveApplicationExists L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0 
	And(L.Leave_FromDate=@Date) and L.Status<>'Rejected')>0)
		BEGIN
			IF((SELECT COUNT(*) from TA_Tbl_LeaveApplicationExists  L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0
			And(L.Leave_FromDate=@Date) and L.Status<>'Rejected')=1)
				BEGIN																
					SELECT L.Leave_SessionFrom,L.Leave_SessionTo from TA_Tbl_LeaveApplicationExists L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0
					And(L.Leave_FromDate=@Date) and L.Status<>'Rejected'					
				END
			ELSE
				BEGIN
					SELECT 'First half' as Leave_SessionFrom,'Second half' as Leave_SessionTo
				END
		END
	else
		begin
			SELECT 'NoLeave' as Leave_SessionFrom,'NoLeave' as Leave_SessionTo
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForProcessing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name	:	Proc_TA_CheckLeaveForProcessing
Created By		:	Kumuthini.L
Created On		:	16-Sep-08
Description		:	Used to get approved leave details for particular Employee and Date
*/
CREATE   PROCEDURE [dbo].[Proc_TA_CheckLeaveForProcessing]
(
	@SwipeCardNo nvarchar(25),
	@Date nvarchar(15)
)
AS
begin
SET NOCOUNT ON;
SELECT LA.Employee_Id,LA.Leave_SessionFrom,LA.Leave_SessionTo FROM TA_Tbl_LeaveApplication LA,TA_Tbl_Employee E WHERE E.SwipeCardNo = @SwipeCardNo AND Leave_FromDate >= @Date AND Leave_ToDate <= @Date AND LA.Employee_Id = E.Employee_Id AND LA.Leave_SessionFrom = LA.Leave_SessionTo AND LA.Status = 'Approved' AND LA.IsDeleted = 0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForwardingPerson]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	K. Gopinath
-- Create date: 13-Jun-2014
-- Description:	for getting FOrwarding authority for OD application
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForwardingPerson]
	@EmpID as int
AS
BEGIN
	SET NOCOUNT ON;
	Select Reporting_TO from ta_tbl_employee where Employee_ID=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE Procedure [dbo].[Proc_TA_CheckLeaveMaster_Insert]  
(            
 @Company_Id int,    
@Region_Id int,    
@Branch_Id int,    
@Department_Id int,    
@Section_Id int,    
@Title_Id int,   
@LeaveId int           
)             
As            
DECLARE @Isdel INT            
SET @Isdel=1            
 BEGIN            
	SET NOCOUNT ON;            
	Select Count(Id)as [Id] from TA_Tbl_LeaveMaster where LeaveType_Id=@LeaveId AND Company_Id=@Company_Id AND Region_Id=@Region_Id AND Branch_Id=@Branch_Id AND Department_Id=@Department_Id AND Section_Id=@Section_Id AND Title_Id=@Title_Id AND IsDeleted=1    
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE Procedure [dbo].[Proc_TA_CheckLeaveMaster_Update]            
(           
@Id int, 
 @Company_Id int,    
@Region_Id int,    
@Branch_Id int,    
@Department_Id int,    
@Section_Id int,    
@Title_Id int,    
@LeaveId int           
)             
As            
DECLARE @Isdel INT            
SET @Isdel=1            
 BEGIN         
	SET NOCOUNT ON;   
	Select Count(Id)as [Id] from TA_Tbl_LeaveMaster            
	where Company_Id=@Company_Id AND Region_Id=@Region_Id AND Branch_Id=@Branch_Id     
	AND Department_Id=@Department_Id AND Section_Id=@Section_Id AND Title_Id=@Title_Id AND LeaveType_Id=@LeaveId AND IsDeleted=1    
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveOnSameDay]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveOnSameDay]
	-- Add the parameters for the stored procedure here
	@EmployeeId INT,
	@LeaveFromDate datetime,
	@LeaveToDate datetime
	AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_Permission where IsDeleted=0 and Permission_Status <> 'Rejected' and Permission_Date between @LeaveFromDate and @LeaveToDate
	and Employee_Id=@EmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeavePolicy  
Description : check leave policy before insert, is already there or not  
Tables Included : TA_Tbl_Emp_LeavePolicy  
Created By : Arun Vinoth.T  
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeavePolicy] 
	-- Add the parameters for the stored procedure here
	@LeavePolicy INT
AS
BEGIN
	SET NOCOUNT ON;
	SELECT COUNT(LeavePolicy_Id) as count FROM TA_Tbl_Emp_LeavePolicy WHERE LeavePolicy_Id=@LeavePolicy AND Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : Proc_TA_CheckLeavePolicyDatesExists  60010,'2008-12-01 00:00:00.000','2008-12-31 00:00:00.000'
Description  :    Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    */    
-- Proc_TA_CheckLeavePolicyDatesExists 10899,'20120408','20120408',58
CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists]    
@Employee_Id bigint,    
@FromDate datetime,
@ToDate datetime,
@LevelId int     
AS  
begin  
	SET NOCOUNT ON;
	declare @test as decimal    
	declare @Result as varchar(10)
	Declare @LevelId1 int
	declare @SuceesiveFromDate datetime
	declare @SuceesiveToDate datetime
	select @LevelId1= LevelId from ta_tbl_employeeLevel where employeeId=@Employee_Id
	while((select Id from TA_tbl_LevelDetails where id=@LevelId1) <> '') 
		BEGIN
			if((select levelID from TA_tbl_LevelDetails where Id=@LevelId1) <> 1)
				begin
					set @LevelId1 = (select parentId from TA_tbl_LevelDetails where id=@LevelId1) 
				end
			else
				begin
					break
				end
		ENd
	set @LevelId=@LevelId1
	Declare @Successivedays int
	if exists( select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@LevelId)
		begin
			set @Successivedays=(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@LevelId)
		end
	else
		begin
			set @Successivedays=(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=-1)
		end
	-- select ToDate from ta_tbl_YearSetting where Isactive=1
	select @SuceesiveFromDate = ToDate from ta_tbl_YearSetting where Isactive=1
	select @SuceesiveToDate = dateadd(day,@Successivedays,ToDate) from ta_tbl_YearSetting where Isactive=1 
	if(@SuceesiveToDate < @FromDate or @SuceesiveToDate < @ToDate)
		begin
			select '2' as PolicyCount
		end
	else if ( (@FromDate > @SuceesiveFromDate and @FromDate <= @SuceesiveToDate) and (@ToDate > @SuceesiveFromDate and @ToDate <= @SuceesiveToDate) )
			begin	
				create table #LevelRights(LevelId int)
				insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild]('SuperAdmin',@LevelId) as LevelId
				if exists( select * from #LevelRights LR inner join ta_tbl_EmployeeLevel EL on LR.LevelId=EL.Levelid where EL.EmployeeId=@Employee_Id)
					begin
						create table #TempLeavePolicy(EmployeeId int,fromdate datetime,ToDate datetime,YearSettingsId int)
						insert into #TempLeavePolicy
						select empl.Employeeid,empl.FromDate,dateadd(day,@Successivedays,empl.ToDate) as ToDate,empl.YearSettingId from ta_tbl_emp_leavepolicy empl inner join ta_tbl_yearsetting ys on empl.YearSettingId=ys.YearSettings_Id 
						where empl.employeeId=@Employee_Id and ys.IsActive=1
						select 1 as PolicyCount
						drop table #TempLeavePolicy
					end
				else
					begin
						select '0' as PolicyCount
					end
			end
	else
		begin
			select count(empl.EmployeeId) as PolicyCount from ta_tbl_emp_leavepolicy empl
			inner join ta_tbl_yearsetting ys on empl.YearSettingId=ys.YearSettings_Id
			where empl.EmployeeId=@Employee_Id 
			and (@FromDate between empl.FromDate and empl.ToDate) and (@ToDate between empl.FromDate and empl.ToDate)
			and ys.IsActive=1
		end
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckLeavePolicyDatesExists  60010,'2008-12-01 00:00:00.000','2008-12-31 00:00:00.000'
Description  :    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]    
@Employee_Id bigint,    
@FromDate datetime,
@ToDate datetime     
AS    
begin
	SET NOCOUNT ON;
	declare @test as decimal    
	declare @Result as varchar(10)    
	select count(empl.EmployeeId) as PolicyCount from ta_tbl_emp_leavepolicy empl
	where empl.EmployeeId=@Employee_Id 
	and (@FromDate between empl.FromDate and empl.ToDate) and (@ToDate between empl.FromDate and empl.ToDate)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavepolicyName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : Proc_TA_CheckLeavePolicy    
Description : check leave policy before insert, is already there or not    
Tables Included : TA_Tbl_Emp_LeavePolicy    
Created By : Arun Vinoth.T    
Created On : 14-Aug-2007    
Modified By :    
Modified On :  */  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeavepolicyName](@PolicyName varchar(50))
AS
begin
	SET NOCOUNT ON;
	SELECT COUNT(*) FROM TA_Tbl_LeavePolicy WHERE PolicyName=@PolicyName --and IsDeleted=0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveSanctioningPerson]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:	K. Gopinath
-- Create date: 13-Jun-2014
-- Description:	for getting Approval authority for OD application
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveSanctioningPerson]
	@EmpID as int
AS
BEGIN
	SET NOCOUNT ON;
	Select Leave_Sanc_Authority from ta_tbl_employee where Employee_ID=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeaveType 86 
Description		: check leave type before insert, is already there or not  
Tables Included : TA_Tbl_LeavePolicyDetails  
Created By		: Arun Vinoth.T  
Created On		: 14-Aug-2007  
Modified By		: Prabakaran.P  
Modified On		: 27-Feb-08 
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeaveType]
(        
 @LeaveTypeId int        
)         
As        
DECLARE @Isdel INT        
SET @Isdel=0        
 BEGIN 
	SET NOCOUNT ON;
    select count(LeaveType_Id) as LType from TA_Tbl_LeavePolicyDetails lpd
	inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 
	where LeaveType_Id=@LeaveTypeId and lp.IsDeleted=0    
 END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType_LeaveApp]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLeaveType_LeaveApp  
Description : Check for  Leave type mapping in Leave application  
Tables Included : TA_Tbl_LeaveApplication  
Created By : Arun Vinoth.T  
Created On : 12 Aug 07  
Modified By :  
Modified On :
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveType_LeaveApp] 
@LeaveTypeId INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT COUNT(LeaveType_Id) as LType  FROM TA_Tbl_LeaveApplication WHERE LeaveType_Id=@LeaveTypeId and IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		manikandan.R
-- Create date: 09-June-2012
-- Description:	To check whether the leave types are used or not
-- =============================================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]
	-- Add the parameters for the stored procedure here
	@id varchar(500)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(2000)
	set @sql='select COUNT(leavetype_id)as Ltype from TA_Tbl_LeavePolicyDetails where LeaveType_Id in('+@id+')'
	Execute(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveWithPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name		:	Proc_TA_CheckLeaveWithPermission '02/19/2008','02/20/2014',29
Description		:	Check Permission Count for Leave Dates
Tables Included		:	TA_Tbl_Permision
Created By		:	Prabakaran
Created On		:	15-Mar-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveWithPermission] 
@LeaveFromDate datetime,
@LeaveToDate datetime,
@EmployeeId int
as
BEGIN
	SET NOCOUNT ON;
	select count(Permission_Id) as PermissionCount from TA_Tbl_Permission where (Permission_Date between @LeaveFromDate and @LeaveToDate) 
	and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>'Rejected'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLevelName  
Description : check level name
Tables Included : Ta_Tbl_levelDetails  
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLevelName]
(
@parentId int,
@LevelId int,
@LevelName varchar(50)
)
AS
Begin
	SELECT COUNT(*) AS Expr1
	FROM   Ta_Tbl_levelDetails
	WHERE  parentID=@parentId and levelId =@LevelId AND replace(name,' ','') = replace(@LevelName,' ','')
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelNameUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckLevelNameUpdate  
Description : check level name while update
Tables Included : Ta_Tbl_levelDetails  
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLevelNameUpdate]
(
@parentId int,
@LevelId int,
@Id int,
@LevelName varchar(50)
)
AS
SELECT COUNT(*) AS Expr1
FROM   Ta_Tbl_levelDetails
WHERE  parentId=@parentId and name = @LevelName and id!= @Id
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckMandatoryPage]
AS
BEGIN
	select MandatoryChecking from TA_Tbl_PageMandatoryFlag
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPageStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 -- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMandatoryPageStandard]  
AS  
BEGIN  
 select MandatoryChecking from TA_Tbl_PageMandatoryFlagStandard  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckManualEntry  '105','2009/04/02','04:06:37 PM',' ',' '  
Description : check manual entry    
Tables Included : TA_Tbl_ManualTimeEntry    
Created By : Kumuthini.L    
Created On : 17-Aug-2007  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35)
)
AS  
BEGIN
	Set NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')  
  BEGIN  
		SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
		SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0  
	END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')  
  BEGIN  
		SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
		SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0  
	END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
  BEGIN  
		SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
    SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
    SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and    
		((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		OR   
		((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))   
	END   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckManualEntry_Group
Description : check manual entry    
Tables Included : TA_Tbl_ManualTimeEntry    
Created By : Sashma   
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntry_Group]
(
@ManualInDate varchar(15),
@ManualInTime varchar(35),
@ManualOutDate varchar(15),
@ManualOutTime varchar(35),
@xml xml
)  
AS  
BEGIN
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	Declare @Index int
	Set @Index = 0;
	IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')  
	   BEGIN  
		 SET @InDateTime = @ManualInDate + ' ' + @ManualInTime 
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
		 SELECT xm.EmpID as EmployeeAutoId  FROM TA_Tbl_ManualTimeEntry
		 INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId varchar(50) 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
		 WHERE (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0  
		  Exec sp_xml_removedocument @Index
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')  
	   BEGIN  
	  SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
	   SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_ManualTimeEntry 
	   INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId varchar(50) 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
	   WHERE (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0  
	   Exec sp_xml_removedocument @Index
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
	   BEGIN  
	   SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
	   SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
		   SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_ManualTimeEntry 
		   INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId varchar(50) 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
		   WHERE Isdeleted=0 and    
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		  OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))   
	  Exec sp_xml_removedocument @Index
	   END 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryForImport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckManualEntry  '120','2010/03/31','04:06:37 PM',' ',' ',' '  
Description : check manual entry for import perpose   
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Karthikeyan.R
Created On : 09-Apr-2015
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntryForImport](
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35),
	@PunchType varchar(50))  
AS  
BEGIN
SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')  
	   BEGIN  
	 SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
	 SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0 and ManualTimeEntry_InPunchType=@PunchType
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')  
	   BEGIN  
	  SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
	 SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0 and ManualTimeEntry_OutPunchType=@PunchType
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
	   BEGIN  
			SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
			SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and    
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime) and ManualTimeEntry_InPunchType=@PunchType) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime) and ManualTimeEntry_InPunchType=@PunchType))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) and ManualTimeEntry_InPunchType=@PunchType) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) and ManualTimeEntry_InPunchType=@PunchType)))   
	   END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckManualEntryUpdate  1,'105','8/29/2008','08:37 AM','8/29/2008','04:22 PM'
Description : check manual entry while update 
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : Kumuthini.L  
Created On : 17-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntryUpdate](
@MID int,
@EmpCode varchar(10),
@ManualInDate varchar(15),
@ManualInTime varchar(25),
@ManualOutDate varchar(15),
@ManualOutTime varchar(25))
AS
BEGIN
select 0  as ManualEntry
/*
DECLARE @Isdel int
DECLARE @InDateTime VARCHAR(50)
DECLARE @OutDateTime VARCHAR(50)
SET @Isdel=0
IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')
   BEGIN
	SET @InDateTime = @ManualInDate + ' ' + @ManualInTime
	SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=@Isdel and ManualTimeEntry_Id <> @MID
   END
ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')
   BEGIN
	 SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
	SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=@Isdel and ManualTimeEntry_Id <> @MID
   END
ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')
   BEGIN
        SET @InDateTime = @ManualInDate + ' ' + @ManualInTime
        SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
        SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=@Isdel and  
		((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR 
		((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) 
		and ManualTimeEntry_Id <> @MID 
   END
   */
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_CheckManualODEntry '609620','02/05/2014','11:30 PM','02/06/2014','12:30 AM'
--Modified by A.Amsaveni on 07/10/2013 to allow to save continous days of night shift 
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35)
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	 IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
	 BEGIN  
		SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
		SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  	
		if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status in ('Forwarded','Pending','Approved') and  
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
	  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status = 'Approved'  and 
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
	  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status = 'Approved' and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ ' ' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + ' ' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ ' ' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + ' ' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		End 
	  else
		  Begin
		   select 0 as ManualEntry
		  End
	  END  
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryForODUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_CheckManualODEntryForODUpdate]  3,'100','2016-03-15','09:00:00 AM','2016-03-15','06:00:00 PM'
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntryForODUpdate]
(
	@OD int,
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)
	DECLARE @OutDateTime VARCHAR(50)
	IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')
	   BEGIN
			SET @InDateTime = @ManualInDate + ' ' + @ManualInTime
			SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
			if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and  
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
		  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and 
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ ' ' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + ' ' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ ' ' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + ' ' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		  End 
		  else
			  Begin
			   select 0 as ManualEntry
			  End
	   END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_CheckManualODEntryUpdate]  19,'a006','02/Oct/2012','10:47:28 AM','',''
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntryUpdate]
(
	@MID int,
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)
	DECLARE @OutDateTime VARCHAR(50)
	 IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')
	   BEGIN
			SET @InDateTime = @ManualInDate + ' ' + @ManualInTime
			SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
			if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status in ('Forwarded','Pending') and  
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
		  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status = 'Approved'  and 
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status = 'Approved' and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ ' ' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + ' ' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ ' ' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + ' ' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		  End 
		  else
		  Begin
		   select 0 as ManualEntry
		  End
	   END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMaxHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckMaxHoliday    
Description : check maximun holidays  
Tables Included : TA_Tbl_HolidaySettings, TA_tbl_YearSetting    
Created By : Janakaraj.P   
Created On : 20-Aug-2007  
Modified By :    
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMaxHoliday]
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM TA_Tbl_HolidaySettings hs 
	inner join TA_tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId where ys.IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMinTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckMinTime  
Description : check minimum time entry  
Tables Included : TA_Tbl_Clk_RawData,  
Created By : Kumuthini.L  
Created On : 17-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMinTime]
	-- Add the parameters for the stored procedure here
	(@EmployeeID VarChar(50))
AS
BEGIN
	Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 ClkID VarChar(255),	
	 MinTime Varchar(225),
	 MaxTime Varchar(225),
	 ADate varchar(50)
	)
	Declare @TestDate as Varchar(50)
	Declare @MinTime as Varchar(50)
	Declare @MaxTime as Varchar(50)
	Declare @Noon as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select distinct CLK_DATE From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID
	OPEN c 
	FETCH NEXT FROM c INTO @TestDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Select @MinTime = Min(CONVERT(DateTime, CLK_TIME, 118)) From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID And CLK_DATE = @TestDate
	Select @MaxTime = Max(CONVERT(DateTime, CLK_TIME, 118)) From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID And CLK_DATE = @TestDate
	Select @MinTime =
	(Case len (datepart(hh, @MinTime))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(datepart(hh, @MinTime)) + ':' +
	Case len (datepart(mi, @MinTime))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(datepart(mi, @MinTime))), 
	@MaxTime =
	(Case len (datepart(hh, @MaxTime))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(datepart(hh, @MaxTime)) + ':' +
	Case len (datepart(mi, @MaxTime))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(datepart(mi, @MaxTime)))  
	Insert InTo #TempReportTable (ClkID, MinTime, MaxTime, ADate) values (@EmployeeID, @MinTime, @MaxTime, @TestDate)
	FETCH NEXT FROM c INTO @TestDate
	END 
	Select ClkID, MinTime, MaxTime, ADate From #TempReportTable
	CLOSE c 
	DEALLOCATE c
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosure_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*      
Procedure Name : Proc_TA_CheckMonthClosure_Insert   1,'01/01/2009 00:00:00.000','01/31/2009 00:00:00.000'   
Description : check month closure before insert, is alredy there or not       
Tables Included : TA_Tbl_MonthClosure      
Created By : Kumuthini.L      
Created On : 05-Aug-2007     
Modified By :      
Modified On :      
*/      
CREATE  PROCEDURE [dbo].[Proc_TA_CheckMonthClosure_Insert]     
(    
@Org_LevelId INT,    
@StartDate varchar(30),    
@EndDate varchar(30)     
)    
AS    
BEGIN    
SELECT COUNT(MonthClosure_Id) AS MID FROM TA_Tbl_MonthClosure     
WHERE OrgLevel_Id=@Org_LevelId  AND      
MonthClosure_StartDate=@StartDate AND  
MonthClosure_EndDate=@EndDate  
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosureProcessFlag]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckMonthClosureProcessFlag  
Description : check month closure process flag   
Tables Included : TA_Tbl_MonthClosure  
Created By : Kumuthini.L  
Created On : 05-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMonthClosureProcessFlag]
 (
    @MonthClosureId int
 )
AS
BEGIN
   Select MonthClosure_Id from TA_Tbl_MonthClosure where Process = 'P' and MonthClosure_Id = @MonthClosureId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_CheckOtType]
	@OtType as varchar(25),
	@OtValue as varchar(25),
	@CompanyID as int,
	@OtTypeID as int,
	@opr as varchar(1)
AS
BEGIN	
	if (@opr='I')
		Begin
			select count(*) as RecCount from TA_Tbl_OtType
				where (OtType=@OtType or
				OtValue=@OtValue) and 
				CompanyID = @CompanyID 
				--and isdeleted=0				
		End
	Else
		Begin
				select count(*) as RecCount from TA_Tbl_OtType
				where 
					(OtType=@OtType or
				OtValue=@OtValue) and
				CompanyID = @CompanyID and
				OtTypeID!=@OtTypeID --and
				--isdeleted=0
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPageExistsInLicense]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
/*
Modified By : Mani  and Thilak
Modified Date : 26-Nov-2013
Reason : Need to check the demo and Express Version
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPageExistsInLicense](@PageID int)
AS
BEGIN
	SET NOCOUNT ON;
    if exists( Select * from TA_Tbl_Demo Where DemoType in ('Standard','Express'))
		Begin
		   SELECT COUNT(*) as ExistCount from TA_Tbl_Page where pageId = @PageID and pageId not in (20,24,25,69,96,97,98,108,110,133,174,228) 
		End    
    Else
	    Begin
			SELECT COUNT(*) as ExistCount from TA_Tbl_Page where pageId = @PageID
		End   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPassword]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckPassword  
Description : check password validation  
Tables Included : TA_Tbl_Employee  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckPassword]
(
@username NVARCHAR(10),
@password NVARCHAR(50)
)
AS
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	SELECT Count(UserName)as UID FROM TA_Tbl_Employee WHERE Employee_Id=@username AND Emp_password=@password 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermanentDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==============================================================
-- Author:		Manikandan.R
-- Create date: 11-June-2012
-- Description:	Checking Whether it is used or not in Designation
-- ==============================================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermanentDelete]
(
	@Grade varchar(200)
)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select count(*) from ta_tbl_Title where GradeID in(@Grade) And Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_CheckPermissionBeforeAfterWithLeave '02/19/2008','02/20/2008','PermissionOnLeave',5
Description		:	Check Leave Count for Before or After Permission Dates
Tables Included	:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	14-Feb-08
Modified By		:	Thilakraj On : 14-Oct-2013
Modified On		:	
*/
/*
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] '04/01/2008','04/01/2008','PermissionAfterLeave','1221'
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] '04/01/2008','04/01/2008','PermissionBeforeLeave','1221'
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] '04/01/2013','04/01/2013','PermissionOnLeave','1221'
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave] 
	@PermissionFromDate datetime,
	@PermissionToDate datetime,
	@PermissionType nvarchar(50),
	@EmployeeId int,
	@ShiftDate datetime
as
BEGIN
	SET NOCOUNT ON;
	if(@PermissionType='PermissionBeforeLeave')
		BEGIN
			select * from ta_tbl_leaveApplication
			where Leave_FromDate=DATEADD( day ,1,@PermissionToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>'Rejected'
		END
	else if(@PermissionType='PermissionAfterLeave')
		BEGIN
			select * from ta_tbl_leaveApplication
			where Leave_ToDate=DATEADD( day ,-1,@PermissionFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>'Rejected'
		END 
	else if(@PermissionType='PermissionOnLeave')
		BEGIN
			select * from ta_tbl_leaveApplication
			where ((@ShiftDate between Leave_FromDate and Leave_ToDate) or (@ShiftDate between Leave_FromDate and Leave_ToDate)) 
			and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>'Rejected'
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckPermissionForManualEntry  '1001','9/03/2008','10:06:45 AM','',''  
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Kumuthini.L    
Created On : 02-Sep-2008  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry](
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)  
	DECLARE @OutDateTime VARCHAR(50)  
	IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')  
	   BEGIN  
		 SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
		 SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
		 INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
		 WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND   
		 ((P.Permission_FromTime) <= Cast(@InDateTime as DateTime) AND (P.Permission_ToTime) > Cast(@InDateTime as DateTime))  
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')  
	   BEGIN  
		  SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
		  SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
		  INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
		  WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
		  ((P.Permission_FromTime) < Cast(@OutDateTime as DateTime) AND (P.Permission_ToTime) >= Cast(@OutDateTime as DateTime))   
	   END  
	ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
	   BEGIN  
			SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
			SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime  
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
			WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
			((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND (P.Permission_ToTime))))   
	   END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckPermissionForManualEntry_Group
Description : Checking whether the Permission is within the Manual Time Entry for a group of employees  
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Sashma.S    
Created On : 02-May-2011  
Modified By		:  Manjula.P  
Modified On		:  18-Feb-2014
Descriptinos	:	To avoid could not find prepared statement with handle 0  error : handle EXEC sp_xml_preparedocument @Index OUTPUT, @xml
				:	and  Exec sp_xml_removedocument @Index for all if constions
Proc_TA_CheckPermissionForManualEntry_Group '2014/01/03','09:00 AM','2014/01/03','06:00 PM' ,'<NewDataSet>
  <Table>
    <EmpID>46</EmpID>
    <EmployeeId>26</EmployeeId>
    <EmployeeName>Manjula P  Valparai Door No Fifty Five </EmployeeName>
    <LoginEmployeeId>1</LoginEmployeeId>
  </Table>
</NewDataSet>' 
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]
(
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25),
	@xml xml
)  
AS  
	Begin
	SET NOCOUNT ON;
	DECLARE @Isdel int  
	DECLARE @InDateTime VARCHAR(50)  
	DECLARE @OutDateTime VARCHAR(50)  
	SET @Isdel=0  
	Declare @Index int
	Set @Index = 0;
		IF(@ManualInDate <> ' '  and @ManualInTime <> ' ' and @ManualOutDate = ' ' and @ManualOutTime = ' ')  
		BEGIN  
		 SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		 SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_Permission P  
		 INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId Bigint 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmpID = P.Employee_Id  
		 WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = @Isdel AND   
		 ((P.Permission_FromTime) <= Cast(@InDateTime as DateTime) AND (P.Permission_ToTime) > Cast(@InDateTime as DateTime))  
		 Exec sp_xml_removedocument @Index
		END  
		ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate = ' '  and @ManualInTime = ' ')  
		   BEGIN  
		  SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
		  --Added by MAnjula.P on 18-Feb-2014   
		  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  --*************************************
		  SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_Permission P  
		  INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId Bigint 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmpID = P.Employee_Id   
		  WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = @Isdel AND   
		  ((P.Permission_FromTime) < Cast(@OutDateTime as DateTime) AND (P.Permission_ToTime) >= Cast(@OutDateTime as DateTime))
		  --Added by MAnjula.P on 18-Feb-2014     
		  Exec sp_xml_removedocument @Index
		  --*************************
		   END  
		ELSE IF (@ManualOutDate <> ' ' and @ManualOutTime <> ' ' and @ManualInDate <> ' ' and @ManualInTime <> ' ')  
		   BEGIN  
			  SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
			  SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
			  --Added by MAnjula.P on 18-Feb-2014  
			  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
			  --************************************8
			  --select * from OpenXML(@Index, '/NewDataSet/Table')
			  SELECT ISNULL(xm.EmpID,0) as EmployeeAutoId FROM TA_Tbl_Permission P  
			  INNER JOIN  OpenXML(@Index, '/NewDataSet/Table') With (EmployeeId Bigint 'EmployeeId',EmpID Bigint 'EmpID') as xm on xm.EmpID = P.Employee_Id  			  WHERE P.Permission_Status = 'Approved' AND P.IsDeleted = @Isdel AND  
			  ((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			  ((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND (P.Permission_ToTime))))   
			  --Added by MAnjula.P on 18-Feb-2014  
			  Exec sp_xml_removedocument @Index
			  --************************************
		   END  
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : 
Proc_TA_CheckPermissionForManualEntry_OD  '595436','02/15/2014','12:15:00 AM','02/15/2014','02:31:00 AM' 
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Kumuthini.L    
Created On : 02-Sep-2008  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)    
AS  
	BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel int  
	DECLARE @InDateTime datetime
	DECLARE @OutDateTime datetime
	SET @Isdel=0 
	SET @InDateTime = @ManualInDate + ' ' + @ManualInTime  
	SET @OutDateTime = @ManualOutDate + ' ' + @ManualOutTime
	Declare @PermissionFromTime datetime
	Declare @PermissionToTime datetime
	
	SELECT @PermissionFromTime=Permission_FromTime,@PermissionToTime=Permission_ToTime FROM TA_Tbl_Permission P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE  P.IsDeleted = @Isdel AND E.Employee_Code_Id = @EmpCode and
	(((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) 
	AND Cast(@OutDateTime as DateTime))) and P.Permission_Status != 'Rejected'
	
	 if	(
			(@PermissionFromTime>=CONVERT(datetime,cast(@InDateTime as datetime),114) and @PermissionFromTime<=CONVERT(datetime,cast(@InDateTime as datetime),114)) 
			or 
			(@PermissionToTime>=CONVERT(datetime,cast(@OutDateTime as datetime),114) and @PermissionToTime<=CONVERT(datetime,cast(@OutDateTime as datetime),114))
		)
		begin
			select 1 as ManualEntry		
		end
	else if	(
			@PermissionFromTime=CONVERT(datetime,cast(@InDateTime as datetime),114) 
			or 
			@PermissionToTime=CONVERT(datetime,cast(@InDateTime as datetime),114)
		)
		begin
			select 0 as ManualEntry		
		end
	else if	(
			@PermissionFromTime=CONVERT(datetime,cast(@OutDateTime as datetime),114) 
			or 
			@PermissionToTime=CONVERT(datetime,cast(@OutDateTime as datetime),114)
		)
		begin
			select 0 as ManualEntry			
		end
	else
		begin
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
			WHERE  P.IsDeleted = @Isdel AND E.Employee_Code_Id = @EmpCode AND
			((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) 
			AND (P.Permission_ToTime)))) and P.Permission_Status != 'Rejected'
		end
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForProcessing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name	:	Proc_TA_CheckPermissionForProcessing
Created By		:	Kumuthini.L
Created On		:	16-Sep-08
Description		:	Used to get approved permission details for particular Employee and Date
*/
CREATE   PROCEDURE [dbo].[Proc_TA_CheckPermissionForProcessing]
(
	@SwipeCardNo nvarchar(25),
	@Date nvarchar(15)
)
AS
begin
SET NOCOUNT ON;
	SELECT P.Permission_FromTime,P.Permission_ToTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo=@SwipeCardNo AND P.Permission_Date = @Date AND P.Permission_Status='Approved' AND P.IsDeleted=0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckPermissionHours  
Description		: For Checking the Permission Date already Exists
Tables Included : TA_Tbl_Permission  
Created By		: Prabakaran.P  
Created On		: 14-Aug-2007 
Modified By		:  
Modified On		:  
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_CheckPermissionHours]
(
	@Employee_Id int,
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime
)
 AS
begin
	set nocount on;
	select COUNT(*) as CS from TA_Tbl_Permission 
	where Employee_Id =@Employee_Id And IsDeleted=0 And Permission_Date=@PermissionDate and Permission_Status !='Rejected'
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckPermissionUpdate  
Description : For Checking the Permission Date already Exists
Tables Included : TA_Tbl_Permission  
Created By : Prabakaran.P  
Created On : 14-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckPermissionUpdate]
(
	@Employee_Id int,
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime
)
AS
begin
	set nocount on;
	select COUNT(*) as CS from TA_Tbl_Permission where Employee_Id =@Employee_Id And IsDeleted=0 And Permission_Date=@PermissionDate
	And (( Permission_FromTime  between @Permission_FromTime And @Permission_EndTime) or (Permission_ToTime between @Permission_FromTime And @Permission_EndTime))
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckProcessedData  
Description : check process data  
Tables Included : TA_Tbl_ProcessedData  
Created By : Kumuthini.L  
Created On : 05-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcessedData]
(
  @SwipeCardNo nvarchar(20),
  @Date DateTime
)
AS
SELECT [Date] FROM TA_Tbl_ProcessedData where Employee_Code_Id = @SwipeCardNo and [Date] = @Date
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedManualEntryId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckProcessedManualEntryId  
Description : To check whether the manual time entry has already been processed by passing Manual Time Entry Id
Tables Included : TA_Tbl_ManualTimeEntry  
Created By :  Kumuthini 
Created On : 26-Jan-2008
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcessedManualEntryId]
(@ManualTimeEntryId int)
AS
BEGIN
	SELECT COUNT(*) AS Count FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Id = @ManualTimeEntryId AND Clk_Process = 'Y'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
	Procedure Name : Proc_TA_CheckProcName  
	Description : check for shift roaster while insert   
	Tables Included : TA_Tbl_ShiftRoaster  
	Created By : Janakaraj  
	Created On : 30-Nov-07  
	Modified By :  A.K.T.MOORTHI
	Modified On :  17-Dec-2013
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcName](
	@companyId INT,
	@RoasterName NVARCHAR(50))
AS
BEGIN
	DECLARE @sql NVARCHAR(3000)
	--SELECT COUNT(*) FROM TA_Tbl_ShiftRoaster where ShiftRoaster_Name=@RoasterName AND IsDeleted=0
	SET @sql ='SELECT COUNT(IsDeleted) FROM TA_Tbl_ShiftRoaster WHERE IsDeleted = 0 AND ShiftRoaster_Name = N''' + @RoasterName + ''' AND Level_Id = ' + CAST(@companyId AS NVARCHAR(8))
	EXEC(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcNameUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_CheckProcNameUpdate  
Description		:	check for shift roaster while update   
Tables Included :	TA_Tbl_ShiftRoaster  
Created By		:	Janakaraj  
Created On		:	30-Nov-07  
Modified By		:  A.K.T.MOORTHI
Modified On		:  17-Dec-2013
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcNameUpdate](
	@companyId INT,
	@RoasterName NVARCHAR(50),
	@ShiftRoasterId INT)
AS
BEGIN
	DECLARE @sql NVARCHAR(3000)
	--SELECT COUNT(*) FROM TA_Tbl_ShiftRoaster where ShiftRoaster_Name=@RoasterName AND IsDeleted=0 and ShiftRoaster_Id <> @ShiftRoasterId
    SET @sql = 'SELECT COUNT(ShiftRoaster_Name) FROM TA_Tbl_ShiftRoaster WHERE IsDeleted = 0 AND ShiftRoaster_Name = N''' + @RoasterName + ''' AND ShiftRoaster_Id <> ' + CAST(@ShiftRoasterId AS NVARCHAR(25)) + ' AND Level_Id = ' + CAST(@companyId AS NVARCHAR(8))
    EXEC(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_CheckPunchTypeForDiscrepancy] 787,'Shift In'
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]
(
	@TerminalId varchar(50),
	@punchType varchar(50)
)
AS  
BEGIN 
	SET NOCOUNT ON;
	declare @Status varchar(max)
	set @Status=''
	Declare @Terminal_Id int
	declare @Type varchar(10)
	declare @EntranceId int
	Declare @count int
	declare @Readerid varchar(max)
	declare @i int
	set @i=1
	set @Readerid=''
	select @Terminal_Id=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@TerminalId and IsDeleted=0
	if((select COUNT(*)from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id)=1)
		begin	 
			select @Type=Type,@EntranceId=Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
			Create table #Temp(id int identity(1,1),Readerid int)
			if(@Type='In')
				begin
					select @count=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type='Out'
					insert into #Temp select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type='Out'
					while @i<=@count
						begin
							if @Readerid=''
								begin
									set @Readerid=(select Readerid from #Temp where id=@i)
								end
							else
								begin
									set @Readerid=@Readerid+','+(select Readerid from #Temp where id=@i)
								end
							set @i=@i+1
						end
				end
			else
				begin
					select  @count=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type='In'
					insert into #Temp select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type='In'
					while @i<=@count
						begin
							if @Readerid=''
								begin
									set @Readerid=(select Readerid from #Temp where id=@i)
								end
							else
								begin
									set @Readerid=@Readerid+','+(select Readerid from #Temp where id=@i)
								end
							set @i=@i+1
						end
				end
		end
	else
		begin			
			SELECT @Readerid=COALESCE(convert(varchar(max),@Readerid)+',','')+CONVERT(varchar(20),Reader_Id) FROM TA_Tbl_Entrance_INOUTDetails 
			where Entrance_Id=(SELECT top 1 Entrance_Id FROM TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id)
			select @Readerid=right(@Readerid,LEN(@readerid)-1)			
		end
	
	if(@TerminalId='787')
	begin
		if(@punchType='Shift In')
		begin
			select 'Shift Out' as status
		end
		if(@punchType='Shift Out')
		begin
			select 'Shift In' as status
		end
	end
	if(@TerminalId='788')
	begin
		if(@punchType='Shift In')
		begin
			select 'Shift Out' as status
		end
		if(@punchType='Shift Out')
		begin
			select 'Shift In' as status
		end
	end
		
	if(@TerminalId!='787' and @TerminalId!='788')
	begin
		if(@punchType='In')
			begin
			   exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Out'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')
			end
		else if(@punchType='Break In')
			begin
			   exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Break Out'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')
			end 
		else if(@punchType='Shift In')
			begin
				exec('(select PunchType as status from TA_tbl_PunchTypes where PunchType in(''Shift Out'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')
			end
		else if(@punchType='Out')
			begin
				exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''In'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')
			end
		else if(@punchType='Shift Out')
			begin
				exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Shift In'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')			
			end
		else if(@punchType='Break Out')
			begin
				exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Break In'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')			
			end
		else if(@punchType='Lunch Out')
			begin		   
			   exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Lunch In'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')			
			end
		else if(@punchType='Lunch In')
			begin
			   exec('(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''Lunch Out'') and Isdeleted=0 and Terminal_Id in('+ @Readerid+'))')			
			end
		else	
			begin
				select @Status as status
			end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Available]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <28-May-2019 03:02 PM>
-- Description:	<Verifying particular punch types is exists or not of web clock in and out>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Available]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT ShiftIn=COUNT('Shift In'),
	ShiftOut=COUNT('Shift Out'),
	LunchOut=COUNT('Lunch Out'),
	LunchIn=COUNT('Lunch In'),
	BreakOut=COUNT('Break Out'),
	BreakIn=COUNT('Break In'),
	PunchType
	from TA_Tbl_PunchTypes	where Isdeleted=0 group by PunchType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : Proc_TA_CheckPunchTypes_Delete  
Description : Save year settings details into table  
Tables Included : TA_Tbl_PunchTypes, TA_Tbl_ManualTimeEntry  
Created By : Arun vinoth.T  
Created On : 31-Oct-2007   
Modified By :  R.Manikandan
Modified On :  23-11-2016
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Delete]
(
   @PunchTypeId INT
)
AS
BEGIN 	
	SELECT COUNT(M.ManualTimeEntry_Id) as PunchTypesMappingCount FROM TA_Tbl_PunchTypes P,TA_Tbl_ManualTimeEntry M WHERE P.PunchType_Id = @PunchTypeId AND ((P.Terminal_Id = M.ManualTimeEntry_InReaderID AND 
	P.PunchType = M.ManualTimeEntry_InPunchType) OR (P.Terminal_Id = M.ManualTimeEntry_OutReaderID AND P.PunchType = M.ManualTimeEntry_OutPunchType))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRawFormat]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckRawFormat  
Description : check raw data format  
Tables Included : TA_tbl_TerminalDatatype  
Created By : Kumuthini.L  
Created On : 13-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckRawFormat](@Rawdataformat varchar(60))
as
 SELECT COUNT(*) FROM TA_tbl_TerminalDatatype   where Raw_Data_Format =@Rawdataformat
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReferranceReligion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Rukmnai Devi.P
-- Create date: 12-oct-2011
-- Description:	to check the check boxes.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckReferranceReligion] 
	-- Add the parameters for the stored procedure here
 @ID int 
As          
--DECLARE @Isdel INT          
--SET @Isdel=0          
BEGIN   
	declare @RecCont as bigint
	set @RecCont=(select count(ID)as Rcount from TA_Tbl_religion TR inner join TA_Tbl_Employee TE on TE.Religion =  TR.ID 
					where TR.ID = @ID and TE.IsDeleted=0) 
	set @RecCont=@RecCont + (select count(ID)as Rcount from TA_Tbl_religion TR 
							inner join TA_Tbl_leavetype LT on LT.Religion =  TR.ID 
							where TR.ID = @ID and LT.IsDeleted=0)
	select @RecCont as Rcount  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReligion_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_CheckReligion_Insert]
( 
@mode int= 1,
@ID int =0, 
 @Name NVARCHAR(50),
 @Description NVARCHAR(255)
)   
As  
 BEGIN 
 DECLARE @err_message nvarchar(255) 
  if(@mode = 1)
  Begin
  if Exists(SELECT ID as count FROM TA_Tbl_Religion WHERE Name=@Name) 
  begin
SET @err_message = 'Record already Exist'
	RAISERROR (@err_message,0,0)
End
  else
   begin
   INSERT INTO TA_Tbl_Religion(Name,Description,IsDeleted) VALUES (''+ @Name + '',''+ @Description + '',0)
   end
  End
   if(@mode=2)
  Begin
  if Exists(Select Name as Ltype from TA_Tbl_Religion where ID<>'' + cast(@ID as nvarchar(20)) +'' And Name='' + @Name + '' )
   begin
SET @err_message = 'Record already Exist'
	RAISERROR (@err_message,0,0)
End
  else
  begin
 UPDATE TA_Tbl_Religion SET Name ='' +  @Name + '',Description='' + @Description + '' WHERE ID='' + cast(@ID as nvarchar(20)) + ''
  end 
  end
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckreligionType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_CheckreligionType]
(        
 @ID int        
)         
As        
DECLARE @Isdel INT        
SET @Isdel=0        
 BEGIN 
	/*      
		Select Count(LeaveType_Id)as LType from TA_Tbl_LeavePolicyDetails        
		where LeaveType_Id=@LeaveTypeId     
	*/ 
    select count(ID) as LType from TA_Tbl_Religion 
	where ID=@ID and IsDeleted=0    
 END   
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReportingPerson]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckReportingPerson]
	@EmpID as int
AS
BEGIN
	Select count(*) from ta_tbl_employee where Reporting_To=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreEntrance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name  : Proc_TA_CheckRestoreEntrance 
Description 	: Check Entrance before restore, is already there or not  
Tables Included : TA_Tbl_Entrance
Created By 	: Kumuthini.L  
Created On 	: 8-Feb-2008  
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreEntrance]
(        
	@EntranceId INT
)         
AS  
BEGIN
	SET NOCOUNT ON
	Declare @EntranceName NVARCHAR(50)
	select @EntranceName=Entrance_Name FROM TA_Tbl_Entrance where Entrance_Id=@EntranceId
	SELECT COUNT(Entrance_Id) AS EntranceCount FROM TA_Tbl_Entrance WHERE Entrance_Id<>@EntranceId AND Entrance_Name = @EntranceName         
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : Proc_TA_CheckRestoreLeaveType
Description : check leave policy before restoring, is already there or not  
Tables Included : TA_Tbl_LeavePolicy
Created By : Kumuthini.L  
Created On : 6-Feb-2008  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreLeavePolicy]
(        
  @LeavePolicyId INT        
)         
As        
BEGIN        
	SET NOCOUNT ON;
	Declare @PolicyName nVarchar(200)   
	Declare @LeaveTypeIsDeleted int
	Declare @Count int
	Declare @Count1 int
	Select @PolicyName= PolicyName FROM TA_Tbl_LeavePolicy WHERE Policy_Id = @LeavePolicyId
	select @Count=COUNT(IsDeleted) from TA_Tbl_LeaveType where LeaveType_Id in(select LeaveType_Id from TA_Tbl_LeavePolicyDetails where Policy_Id=@LeavePolicyId) 
	and IsDeleted<>0
	SELECT @Count1=COUNT(Policy_Id)  FROM TA_Tbl_LeavePolicy WHERE PolicyName = @PolicyName AND Policy_Id <> @LeavePolicyId AND IsDeleted = 0
	select @count as [Count],@Count1 AS [Count1]
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : Proc_TA_CheckRestoreLeaveType
Description : check leave type before insert, is already there or not  
Tables Included : TA_Tbl_LeaveType
Created By : Kumuthini.L  
Created On : 5-Feb-2008  
Modified By :  
Modified On :  
*/
CREATE Procedure [dbo].[Proc_TA_CheckRestoreLeaveType]
(        
  @LeaveTypeId INT       
)         
As          
BEGIN        
	SET NOCOUNT ON;
	Declare @LeaveType nVarchar(200)
	Select @LeaveType=Leavetype from TA_Tbl_LeaveType where LeaveType_Id= @LeaveTypeId
	SELECT COUNT(LeaveType_Id) AS LType FROM TA_Tbl_LeaveType WHERE LeaveType = @LeaveType AND LeaveType_Id <> @LeaveTypeId AND IsDeleted = 0
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestorePunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckRestorePunchTypes
Description : check Punch type before insert, is already there or not  
Tables Included : TA_Tbl_LeaveType
Created By : Kumuthini.L  
Created On : 6-Feb-2008  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestorePunchTypes]
(        
	@PunchTypeId INT  
)         
As
BEGIN
	SET NOCOUNT ON
	Declare @TerminalId INT
	Declare @PunchType nVarchar(50)      
	Select @TerminalId=Terminal_id,@PunchType=PunchType from TA_Tbl_PunchTypes where PunchType_Id=@PunchTypeId 
	SELECT COUNT(PunchType_Id) AS [RestoreCount] FROM TA_Tbl_PunchTypes       
	WHERE Terminal_Id = @TerminalId AND PunchType = @PunchType AND PunchType_Id <> @PunchTypeId AND IsDeleted = 0         
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreReligion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_CheckRestoreReligion]  
(          
  @ID INT 
)           
As
BEGIN
	Declare @Name nVarchar(200)
	Select @Name=Name from TA_Tbl_Religion where ID=@ID 
	SELECT COUNT(ID) AS LType FROM TA_Tbl_Religion WHERE Name = @Name AND ID <> @ID AND IsDeleted = 0             
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminal]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckRestoreTerminal  
Description : Check Terminal before Restoring, is already there or not    
Tables Included : TA_Tbl_Terminal  
Created By : Kumuthini.L    
Created On : 7-Feb-2008    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreTerminal]
(        
	@TerminalId INT  
)         
As        
BEGIN        
	Declare @TerminalReaderId nVarchar(50)
	Declare @TerminalName nVarchar(50)    
	Select @TerminalReaderId=Terminal_ReaderID,@TerminalName=Terminal_Name from TA_Tbl_Terminal where Terminal_Id=@TerminalId
	SELECT COUNT(Terminal_Id) AS [Count] FROM TA_Tbl_Terminal       
	WHERE ((Terminal_ReaderID = @TerminalReaderId) OR (Terminal_Name = @TerminalName)) AND Terminal_Id <> @TerminalId AND IsDeleted = 0
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminalDataType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
Procedure Name : Proc_TA_CheckRestoreTerminalDataType  
Description : Check Terminal Data Type before restoring, is already there or not    
Tables Included : TA_Tbl_TerminalDataType  
Created By : Kumuthini.L    
Created On : 7-Feb-2008    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreTerminalDataType]
(        
  @TerminalDataTypeId INT        
)         
As
BEGIN
	Declare @RawDataFormat nVarchar(50)
	Declare @FileType nVarchar(25)
	Select @RawDataFormat=Raw_Data_Format,@FileType =FileType from TA_tbl_TerminalDatatype where TerminalDatatype_ID=@TerminalDataTypeId
	SELECT COUNT(TerminalDatatype_ID) AS [Count] FROM TA_Tbl_TerminalDataType
	WHERE Raw_Data_Format = @RawDataFormat AND FileType = @FileType AND TerminalDatatype_ID <> @TerminalDataTypeId  AND IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	31-Dec-2013
Descriptions	:	Adding levelid and shiftid condition because changed the fucntionality with multiple closing time with single date
Proc_TA_CheckRestoreWeekday 5
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreWeekday]
(        
  @weekDayId INT         
)         
As        
  BEGIN 
   declare @weekFromDate as NVARCHAR(30)
   declare @weekToDate as NVARCHAR(30)
   --Added by Manjula.P on 31-Dec-2013
   declare @ShiftId as nvarchar(max);
   create table #LevelId ( LevelId int)
   insert into #LevelId 
   select LevelId from Ta_Tbl_Temporary_WeeklyOff_Levels where TempWeekday_Id=@weekDayId
   create table #ShiftId(ShiftId nvarchar(max) )
   --********************************
   select @weekFromDate = TempWeekday_FromDate,@weekToDate = TempWeekday_ToDate,@ShiftId=ShiftId from ta_tbl_Temweekday 
   where TempWeekday_Id = @weekDayId   
   --Added by Manjula.P on 31-Dec-2013
   insert into #ShiftId
   select value from Split((Select * from (select @ShiftId as ShiftId) A), ',')    
   SELECT COUNT(*) AS WeekDateCount FROM TA_Tbl_TemWeekday  TW
   --Added by Manjula.P on 31-Dec-2013
   inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWL.TempWeekday_Id=TW.TempWeekday_Id
   inner join #LevelId on #LevelId. LevelId=TWL.LevelId
   inner join #ShiftId on #ShiftId.ShiftId in (select Value from dbo.Split(TW.ShiftId,','))
   WHERE TempWeekday_FromDate=convert(datetime,@WeekFromdate,103) and TempWeekday_ToDate=convert(datetime,@weekTodate,103) AND TW.TempWeekday_Id <> @weekDayId AND IsDeleted = 0
   --Added by Manjula.P on 31-Dec-2013
   drop table #LevelId
   drop table #ShiftId
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckRestoreWeekoff 
Description : check weekoff before restore, is already there or not  
Tables Included : TA_Tbl_Additional_WeeklyOff
Created By : Christopher S  
Created On : 8-Feb-2008  
Modified By		:	Manjula.P	
Modified On		:	05-Oct-2013
Descriptions	:	Checking Restore option with already inserted levels of additional weekly off Mantis : 0019292 
Proc_TA_CheckRestoreWeekOff 21,'','','R' 
*/  
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreWeekOff]
(        
  @weekOffId INT,     
  @weekDay nVarchar(15) ,
  @weekOffWeek nvarchar(15),
  @Type varchar(2)
)         
As        
  BEGIN        
   if(@Type = 'V')
	   BEGIN   
		   SELECT COUNT(Addl_WeeklyOff_Id) AS WeekOffCount FROM TA_Tbl_Additional_WeeklyOff       
		   WHERE  Addl_WeekOff_Day=@weekDay AND Addl_WeekOff_Week=@weekOffWeek AND Addl_WeeklyOff_Id <> @weekOffId 
		   AND IsDeleted = 0
	   END
   else 
       BEGIN
		   declare @Day nvarchar(15)
		   declare @Week nvarchar(15)
		   --select @Day = Addl_WeekOff_Day,@Week = @weekOffWeek  from TA_Tbl_Additional_WeeklyOff
		   --where Addl_WeeklyOff_Id = @weekOffId
		   --Added by Manjula.P on 05-Oct-2013 
		   declare @Levels nvarchar(2000);
		   select @Day = Addl_WeekOff_Day,@Week = Addl_WeekOff_Week,@Levels = isnull(@Levels,0)+','+cast((AWL.LevelId)as varchar)  from TA_Tbl_Additional_WeeklyOff AW
		   inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
		   where AW.Addl_WeeklyOff_Id = @weekOffId
           SELECT COUNT(AW.Addl_WeeklyOff_Id) AS WeekOffCount FROM TA_Tbl_Additional_WeeklyOff  AW
           inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id     
		   WHERE  Addl_WeekOff_Day=@Day AND Addl_WeekOff_Week=@Week AND Aw.Addl_WeeklyOff_Id <> @weekOffId 
		   AND IsDeleted = 0 and AWL.LevelId in (select Value from  dbo.Split (@Levels,','))
		   --(@Levels)
		   --End *********************************
       END	   
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckRoute  
Description : check route
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRoute]     
(      
-- @RouteName NVARCHAR(50),      
 @RouteId int      
)       
As      
DECLARE @Isdel INT      
SET @Isdel=1      
 BEGIN      
   Select Count(RouteId)as RName from TA_Tbl_Transportation_Mapping      
   where RouteId=@RouteId  AND Isdeleted=@Isdel   --And RouteName=@RouteName    
 END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_ForModification]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckRoute_ForModification]
	@RouteName NVARCHAR(50),      
	@RouteId int      
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)
	set @sql = 'Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>'+cast(@RouteId as nvarchar(25))+' And Route_Name=N'''+@RouteName+''' AND Isdeleted=0'
	exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckRoute_Insert  
Description : check route before insert, is already there or not
Tables Included : TA_Tbl_RouteMaster  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckRoute_Insert]      
(      
@intVehicleID int,   
@RouteName NVARCHAR(50)      
)       
AS      
declare @sql as nvarchar(3000)
Declare @Isdel int      
--SET @Isdel=1      
 BEGIN      
  --SELECT COUNT(Route_Name) AS RName FROM TA_Tbl_RouteMaster WHERE Route_Name=@RouteName AND Isdeleted=0     
  set @sql = 'SELECT COUNT(Route_Name) AS RName FROM TA_Tbl_RouteMaster WHERE Route_Name=N'''+@RouteName+''' AND Isdeleted=0'
  exec(@sql)
 END      
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckRoute_Update    
Description : check route before update, is already there or not  
Tables Included : TA_Tbl_RouteMaster    
Created By : Arun Vinoth    
Created On : 14-Aug-2007  
Modified By :    
Modified On :  
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRoute_Update]      
( 
	@RouteId int      
)       
As      
	DECLARE @sql as nvarchar(3000)    
	DECLARE @RouteName NVARCHAR(50)      
	BEGIN      
		--Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>@RouteId And Route_Name=@RouteName AND Isdeleted=0    
		select @RouteName=Route_Name from TA_Tbl_RouteMaster where Id=@RouteId
		set @sql = 'Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>'+cast(@RouteId as nvarchar(25))+' And Route_Name=N'''+@RouteName+''' AND Isdeleted=0'
		exec(@sql)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSanctioningPerson]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckSanctioningPerson]
	@EmpID as int
AS
BEGIN
	Select count(*) from ta_tbl_employee where Leave_Sanc_Authority=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckShift  
Description : check shift name before insert, is already there or not
Tables Included : TA_Tbl_Shift  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
Proc_TA_CheckShift 151,'test10'
*/  
-- select * from ta_tbl_leveldetails
-- Proc_TA_CheckShift 1,'Testing'
CREATE PROCEDURE [dbo].[Proc_TA_CheckShift]
(
	@companyId int,
	@ShiftName nvarchar(50)
)
AS
BEGIN
    SELECT COUNT(Shift_Name) AS SCount from TA_Tbl_Shift WHERE Shift_Name=@ShiftName
	and Level_Id=cast(@companyId as nvarchar(8))	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : [Proc_TA_CheckShiftAllocation]  
Description : check shift allocation 
Tables Included : TA_Tbl_PermanentShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
               SELECT EmployeeId  FROM TA_Tbl_PermanentShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name	: Proc_TA_CheckShiftDelete    
Description	: check shift Delete   
Tables Included : Ta_tbl_PermanentShiftAllocation, Ta_tbl_TemporaryShiftAllocation, TA_Tbl_ShiftPattern    
Created By 	: Prabakaran    
Created On 	: 30-Jul-07    
Modified By 	:
Modified On 	:
*/  
CREATE       PROCEDURE [dbo].[Proc_TA_CheckShiftDelete] 
@ShiftId int
as
	declare @loop as int
	declare @count as int
	declare @count1 as int
	declare @count2 as int
	declare @query as varchar(2000)
	create table #Temp(Result int)
	set @loop=1
	set @count=0
	set @count1=0
	set @count2=0
	/* For getting count from Ta_tbl_PermanentShiftAllocation */
	while @loop<=31
		begin
			set @query='select count(*) as Result  from Ta_tbl_PermanentShiftAllocation where Day' + Cast(@loop as Varchar(3)) + 'Shift=' + Cast(@ShiftId as varchar(2000))
			insert into #Temp EXEC(@query)
			set @loop=@loop+1
		end
	set @count=(select sum(Result) from #Temp)
	delete from #Temp
	set @loop=1
	/*------------------*/
	/* For getting count from Ta_tbl_TemporaryShiftAllocation */
	--while @loop<=31
	--
	--begin
	--set @query='select count(*) as Result  from Ta_tbl_TemporaryShiftAllocation where Day' + Cast(@loop as Varchar(3)) + 'Shift=' + Cast(@ShiftId as varchar(2000)) 
	--
	--insert into #Temp EXEC(@query)
	--
	--
	--set @loop=@loop+1
	--end
	--
	--set @count1=(select sum(Result) from #Temp)
	delete from #Temp
	set @loop=1
	/*------------------*/
	/* For getting count from TA_Tbl_ShiftPattern */
	while @loop<=31
		begin
			set @query='select count(*) as Result  from TA_Tbl_ShiftPattern where Day' + Cast(@loop as Varchar(3)) + '_Shift=' + Cast(@ShiftId as varchar(2000))
			 --Isdeleted=0 and 
			insert into #Temp EXEC(@query)
			set @loop=@loop+1
		end
	set @count2=(select sum(Result) from #Temp)
	drop table #Temp
/*------------------*/
	set @count=@count+ @count1+ @count2
	if(@count>1)
		begin
			set @count=1
		end
	declare @LevelId as int
	set @LevelId=(select Level_Id FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftId)
	if(@LevelId=0)
		begin
			set @count=1
		end
	select @count as ShiftCount
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftExchangeEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckShiftExchangeEmployee  
Description : To Check the Employees
Tables Included : ta_tbl_employee,ta_tbl_employeelevel,ta_tbl_leveldetails
Created By : Sasireka  
Created On : 15-Jan-2009 
Modified By :  
Modified On :  
Proc_TA_CheckShiftExchangeEmployee '1,2,3,47,113,132,133,134,135,137,138,140,150','3'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftExchangeEmployee]
(
	@levels nvarchar(500),
	@EmployeeId int
)
AS
BEGIN 
--set @levels = '1,2,3,47,113,132,133,134,135,137,138,140,150'
declare @sql as varchar(6000)
set @sql= 'select count(*) as RecCount from ta_tbl_employee inner join ta_tbl_employeelevel on ta_tbl_employee.Employee_Id = ta_tbl_employeelevel.employeeid'
set @sql = @sql + ' inner join ta_tbl_leveldetails on ta_tbl_leveldetails.id=ta_tbl_employeelevel.levelid'
set @sql = @sql + ' where ta_tbl_employeelevel.levelid in (' + @levels + ') and ta_tbl_employee.Employee_Id= ' + cast (@EmployeeId as nvarchar(10))
--select @sql as lev
exec (@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckShiftName  
Description : check shift name 
Tables Included : TA_Tbl_ShiftPattern  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftName]  
   AS
	BEGIN
		SELECT * FROM TA_Tbl_ShiftPattern
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: 27-May-2011
-- Description:	To check whether shift overlaps which shift re-allocating.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]
(
	@ShiftID as int,
	@LoggedInemployeeId bigint,
	@xml xml
)
AS
BEGIN
    Declare @Index int
	Set @Index = 0;
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
    --Deletes the employee in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" whom are not available in the xml data
	DELETE from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where not exists
	(select xm.EmployeeAutoID from  OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') as xm
	where xm.EmployeeAutoID=TA_Tbl_EmployeeShiftId_ForShiftReAllocation.EmployeeAutoId and TA_Tbl_EmployeeShiftId_ForShiftReAllocation.LoggedInEmployeId = @LoggedInemployeeId)
	Exec sp_xml_removedocument @Index
	declare @FromDate datetime
	set @FromDate = (select MIN(date) from TA_Tbl_EmployeeShiftId_ForShiftReAllocation)
	declare @ToDate datetime
	set @ToDate = (select MAX(Date) from TA_Tbl_EmployeeShiftId_ForShiftReAllocation)
    --Updates the current shift Id.
	update TA_Tbl_EmployeeShiftId_ForShiftReAllocation 
	set CurrentShiftId = @ShiftID where LoggedInEmployeId = @LoggedInemployeeId
	and Date between DATEADD(dd,1,@FromDate) and DATEADD(dd,-1,@ToDate)
	if(DATEADD(dd,1,@FromDate) <> DATEADD(dd,-1,@ToDate))
	BEGIN
		update A set A.PreviousDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on A.Date = dateadd(dd,-1,B.Date)
		where A.Date between DATEADD(dd,1,@FromDate) and @ToDate and A.EmployeeAutoId=B.EmployeeAutoId
		update A set A.NextDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on A.Date = dateadd(dd,1,B.Date)
		where A.Date between @FromDate and DATEADD(dd,-1,@ToDate) and A.EmployeeAutoId=B.EmployeeAutoId
	END
	declare @ToDateTemp datetime
	 set @ToDateTemp=@ToDate
	While(@ToDateTemp>@FromDate)
	begin
		update A set A.PreviousDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date = dateadd(dd,-1,@ToDateTemp)
		where A.Date =@ToDateTemp and A.EmployeeAutoId=B.EmployeeAutoId
		set @ToDateTemp=dateadd(dd,-1,@ToDateTemp)
	end
	declare @FromDateTemp datetime
	set @FromDateTemp=@FromDate
	While(@FromDateTemp<@ToDate)
	begin
		update A set A.NextDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date = dateadd(dd,1,@FromDateTemp)
		where A.Date = @FromDateTemp  and A.EmployeeAutoId=B.EmployeeAutoId		
		set @FromDateTemp=dateadd(dd,1,@FromDateTemp)
	end	
		--Updates the flag to 1 if the current shift overlaps the previous shift.
		update TA_Tbl_EmployeeShiftId_ForShiftReAllocation set Flag=1 
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_tbl_shift A on A.Shift_Id= ES.CurrentShiftId
		inner join ta_tbl_shift B on B.Shift_Id = ES.PreviousDayShift
		where cast(A.Shift_StartTime as datetime) <= cast(B.Shift_EndTime as datetime) and charindex('PM',B.Shift_StartTime)>0 and charindex('AM',B.Shift_EndTime)>0
		--Updates the flag to 1 if the current shift overlaps the next day shift.
		update TA_Tbl_EmployeeShiftId_ForShiftReAllocation set Flag=1 
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_tbl_shift A on A.Shift_Id= ES.CurrentShiftId
		inner join ta_tbl_shift B on B.Shift_Id = ES.NextDayShift
		where cast(A.Shift_EndTime  as datetime) >= cast(B.Shift_StartTime as datetime) and charindex('PM',A.Shift_StartTime)>0 and charindex('AM',A.Shift_EndTime)>0
		--select the employees for whom the shift overlaps
		select E.Employee_Code_Id,E.Employee_FirstName,ES.Date from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeAutoId
		where Flag=1 and LoggedInEmployeId = @LoggedInemployeeId
		declare @String varchar(max)
		set @String = (select E.Employee_Code_Id + '- (' + (convert(varchar(10),ES.Date,103)) + ') ' + ',' from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeAutoId
		where Flag=1 and LoggedInEmployeId = @LoggedInemployeeId for xml path(''))
		SET @String = LEFT(@String, LEN(@String) - 1)
		select @String
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckShiftPattern  
Description : check for shift pattern while insert   
Tables Included : TA_Tbl_ShiftPattern  
Created By : Janakaraj  
Created On : 10-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckShiftPattern]
(
@companyId int,
@ShiftPattern nvarchar(50)
)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
	--SELECT COUNT(Pattern_Name) AS SCount from TA_Tbl_ShiftPattern WHERE Pattern_Name=@ShiftPattern and Isdeleted=@Isdel
    set @sql ='SELECT COUNT(Pattern_Name) AS SCount from TA_Tbl_ShiftPattern WHERE Pattern_Name=N'''+@ShiftPattern+''' and Level_Id='+cast(@companyId as nvarchar(8))
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name 	: Proc_TA_CheckShiftPatternDelete
Description 	: check for shift pattern while delete
Tables Included : Ta_tbl_PermanentShiftAllocation, Ta_tbl_TemporaryShiftAllocation  
Created By 	: Janakaraj  
Created On 	: 10-Aug-2007
Modified By 	:  
Modified On 	:  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckShiftPatternDelete] 
@ShiftId int
as
declare @loop as int
declare @count as int
declare @count1 as int
declare @query as varchar(2000)
create table #Temp(Result int)
set @loop=1
set @count=0
set @count1=0
/* For getting count from Ta_tbl_PermanentShiftAllocation */
while @loop<=31
begin
set @query='select count(*) as Result  from Ta_tbl_PermanentShiftAllocation where Day' + Cast(@loop as Varchar(3)) + 'Shift=' + Cast(@ShiftId as varchar(2000))
insert into #Temp EXEC(@query)
set @loop=@loop+1
end
set @count=(select sum(Result) from #Temp)
delete from #Temp
set @loop=1
/*------------------*/
/* For getting count from Ta_tbl_TemporaryShiftAllocation */
while @loop<=31
begin
set @query='select count(*) as Result  from Ta_tbl_TemporaryShiftAllocation where Day' + Cast(@loop as Varchar(3)) + 'Shift=' + Cast(@ShiftId as varchar(2000))
insert into #Temp EXEC(@query)
set @loop=@loop+1
end
set @count1=(select sum(Result) from #Temp)
delete from #Temp
set @count=@count+ @count1
if(@count>1)
begin
set @count=1
end
select @count as ShiftCount
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternNameUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckShiftPatternNameUpdate  
Description : check for shift pattern while update   
Tables Included : TA_Tbl_ShiftPattern  
Created By : Janakaraj  
Created On : 10-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftPatternNameUpdate] 
	-- Add the parameters for the stored procedure here
	@shhiftPatternId INT,
    @shiftPatternName NVARCHAR(50)
AS
 DECLARE @Isdel int
 declare @sql as nvarchar(3000)
 SET @Isdel=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
--	SELECT count(ShiftPattern_Id)  AS PatternID FROM TA_Tbl_ShiftPattern 
--	WHERE Pattern_Name=@shiftPatternName and ShiftPattern_Id<>@shhiftPatternId and Isdeleted=@Isdel
    set @sql =  'SELECT count(ShiftPattern_Id)  AS PatternID FROM TA_Tbl_ShiftPattern WHERE Pattern_Name=N'''+@shiftPatternName+''' and ShiftPattern_Id<>'+cast(@shhiftPatternId as nvarchar(25))+' '
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternOverlapping]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckShiftPatternOverlapping '125','106'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftPatternOverlapping]
	@Shift1ID as int,
	@Shift2ID as int
AS
BEGIN
 set nocount on;
		declare @Shift1StartTime as dateTime
		declare @Shift1EndTime as dateTime
		declare @Shift2StartTime as dateTime
		declare @Shift2EndTime as dateTime
		declare @Flag as int
		declare @CheckPM as int
		declare @checkAM as int
		set @Flag = 0;
		declare @Shift1Name as varchar(5)
		declare @Shift2Name as varchar(5)
		set @Shift1Name = ''
		set @Shift2Name = ''
		select @CheckPM = charindex('PM',shift_starttime), @checkAM = charindex('AM',shift_Endtime) from ta_tbl_shift where shift_id=@Shift1ID
		--select @CheckPM, @checkAM
		if (@CheckPM>0 and @checkAM>0)
		Begin
			select @Shift2StartTime=shift_starttime,@Shift2EndTime=shift_endtime, @Shift1Name=Shift_ShortName from ta_tbl_shift where shift_id = @Shift1ID 			
		    --select @Shift2StartTime,@Shift2EndTime
			select @Flag =count(*), @Shift2Name=Shift_ShortName from ta_tbl_shift  where Shift_ID=@Shift2ID and ((dateadd(day,1,cast(shift_starttime as datetime))  between @Shift2StartTime and dateadd(day,1,@Shift2EndTime) )) group by Shift_ShortName
			--select @Flag =count(*), @Shift1Name=Shift_ShortName from ta_tbl_shift  where @Shift1ID=@Shift1ID and ((cast(shift_starttime as datetime)  between @Shift2StartTime and @Shift2EndTime ) or (cast(shift_Endtime as datetime)  between @Shift2StartTime and @Shift2EndTime  )) group by Shift_ShortName
		End
		select @Flag as ShiftOverLapping, @Shift1Name as Shift1,@Shift2Name as Shift2
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternRestore]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name	: Proc_TA_CheckShiftPatternRestore 88 
Description	: While Restore Shift Pattern, Checking duplicate shift Pattern Name 
Tables Included : Ta_tbl_ShiftPattern
Created By 	: Prabakaran  
Created On 	: 06-FEB-08  
Modified By 	: Prabakaran.P 
Modified On 	:  27-Feb-08
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftPatternRestore] 
@ShiftPatternId int
as
declare @ShiftPatternCount as int
declare @PatternDays as int
declare @shiftIds as int
declare @shiftname as nvarchar(50)
declare @shiftCount as int
declare @shiftTotalCount as int
declare @incrementval as int
declare @sql as nvarchar(200)
set @sql=''
begin
	set @ShiftPatternCount=(select count(Pattern_Name)as ShiftPatternCount from TA_Tbl_ShiftPattern
	where lower(Pattern_Name)in (select lower(Pattern_Name) from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId) and ShiftPattern_Id<>@ShiftPatternId and Isdeleted = 0)
	set @PatternDays =(select Shift_days from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId)
	set @shiftCount=0
	set @shiftTotalCount=0
	set @incrementval=1
	while(@incrementval<=@PatternDays)
		begin
			set @shiftname = 'Day' + convert(nvarchar(50),@incrementval) + '_Shift'
			set @sql='select ' + @shiftname + ' as shiftId from TA_Tbl_ShiftPattern where ShiftPattern_Id=' + convert(nvarchar(50),@ShiftPatternId)
			--set @shiftIds=(select @shiftname as shiftId from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId)
				create table #tempshiftNew 
				(
					shiftIds int
				)  
				insert into #tempshiftNew exec(@sql) 
				set @shiftIds=(select * from #tempshiftNew)
				drop table #tempshiftNew
			set @shiftCount=(select count(Shift_Id) from TA_Tbl_Shift where Shift_Id=@shiftIds and IsDeleted=1)
			set @shiftTotalCount=@shiftTotalCount+@shiftCount
			set @incrementval=@incrementval+1
		end
set @ShiftPatternCount=@ShiftPatternCount+@shiftTotalCount
select @ShiftPatternCount as ShiftPatternCount
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftRestore]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name	: Proc_TA_CheckShiftRestore  
Description	: While Restore Shift, Checking duplicate shift Name 
Tables Included : Ta_tbl_Shift
Created By 	: Prabakaran  
Created On 	: 06-FEB-08  
Modified By 	:  
Modified On 	:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftRestore] 
@ShiftId int
as
select count(Shift_Name)as ShiftCount from TA_Tbl_Shift
where lower(Shift_Name)in (select lower(Shift_Name) from TA_Tbl_Shift where Shift_Id=@ShiftId) and Shift_Id<>@ShiftId AND Isdeleted = 0
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckShift    
Description : check shift name before insert, is already there or not  
Tables Included : TA_Tbl_Shift    
Created By :  Janakaraj.P    
Created On : 19-Aug-2007  
Modified By :    
Modified On :    
Proc_TA_CheckShift 151,'test10'  
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftShortName]  
(  
@companyId int,  
@ShiftShortName nvarchar(50)  
)  
AS  
DECLARE @Isdel int  
declare @sql as nvarchar(3000)  
SET @Isdel=0  
BEGIN  
 --SELECT COUNT(Shift_Name) AS SCount from TA_Tbl_Shift WHERE Shift_Name=@ShiftName and Isdeleted=@Isdel  
    set @sql = 'SELECT COUNT(*) AS SCount from TA_Tbl_Shift WHERE Shift_ShortName=N'''+ @ShiftShortName +''''  
 set @sql = @sql +' and Level_Id='+cast(@companyId as nvarchar(8))   
    exec(@sql)  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortNameUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckShiftShortNameUpdate    
Description 	: check shift short name before update, is already there or not  
Tables Included : TA_Tbl_Shift    
Created By : Prabakaran.P    
Created On : 02-June-09
Modified By :    
Modified On :    
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftShortNameUpdate]    
(  
@companyId int,  
@ShiftId int,  
@ShiftShortName nvarchar(50)  
)  
AS  
declare @sql as nvarchar(3000)  
BEGIN  
 --SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> @ShiftId and Shift_Name=@ShiftName and Isdeleted=1  
    set @sql = 'SELECT COUNT(*) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> '+cast(@ShiftId as nvarchar(25))+' and Shift_ShortName=N'''+ @ShiftShortName +''' and Level_Id='+cast(@companyId as nvarchar(20))   
    exec(@sql)  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftTime]
	@ShiftID as int
AS
BEGIN	
	select shift_StartTime,shift_EndTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_BreakStartTime1,Shift_BreakEndTime1,
	Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_BreakStartTime3,Shift_BreakEndTime3,[24HrsShift] from ta_tbl_shift where  shift_ID=@ShiftID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckShiftUpdate  
Description : check shift name before update, is already there or not
Tables Included : TA_Tbl_Shift  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftUpdate]  
(
@companyId int,
@ShiftId int,
@ShiftName nvarchar(50)
)
AS
declare @sql as nvarchar(3000)
BEGIN
	--SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> @ShiftId and Shift_Name=@ShiftName and Isdeleted=1
    set @sql = 'SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> '+cast(@ShiftId as nvarchar(25))+' and Shift_Name=N'''+@ShiftName+''' and Level_Id='+cast(@companyId as nvarchar(8))	
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckStateCityInsertUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckStateCityInsertUpdate  
Description : check state and city while insert and update 
Tables Included : Ta_tbl_lookup  
Created By : P.Prabakaran    
Created On : 27-10-2007   
Modified By :  
Modified On :  
*/       
CREATE PROCEDURE [dbo].[Proc_TA_CheckStateCityInsertUpdate]  
@Mode char(1),      
@ID int,      
@Title nvarchar(50),      
@Parent int,
@TypeId int      
as      
declare @sql as nvarchar(3000)
/* For Insert */      
if(@Mode='I')      
begin      
  set @sql = 'select count(*) as StateCityCount  from Ta_tbl_lookup where Type='+cast(@TypeId as nvarchar(25))+' and Title=N'''+@Title+''' and Parent='+cast(@Parent as nvarchar(25))+''      
  exec(@sql)
end      
/* For Modify */      
if(@Mode='M')      
begin      
   set @sql = 'select count(*) as StateCityCount  from Ta_tbl_lookup where Type='+cast(@TypeId as nvarchar(25))+' and Title=N'''+@Title+''' and Parent='+cast(@Parent as nvarchar(25))+' and ID<>'+cast(@ID as nvarchar(25))+''      
   exec(@sql)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSuperAdminUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_CheckSuperAdminUser
Description		:	validates the user is a super admin user
Tables Included	:	TA_Tbl_Employee, TA_Tbl_UserGroup
Created By		:	Prabakaran.P
Created On		:	24-July-09
Modified By		:
Modified On		:
Proc_TA_CheckSuperAdminUser '',''
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckSuperAdminUser]
@Username varchar(50),
@PassWord varchar(200)
as
BEGIN
select count(*) as UserCount from TA_Tbl_Employee e
inner join TA_Tbl_UserGroup ug
on ug.groupId=e.UserGroup_Id
where e.UserName=@Username and e.Emp_Password=@PassWord and 
ug.groupName='SuperAdmin' and e.isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTemporaryShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_CheckTemporaryShiftAllocation  
Description : check temporary shift allocation 
Tables Included : TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTemporaryShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
               SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckTempShiftAllocation  
Description : check temporary shift allocation 
Tables Included : TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTempShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
        SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDay_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	19-Dec-2013
Descriptions	:	Adding this param to allowing multiple entries for single date because of various shift
-- Proc_TA_CheckTempWeekDay_Insert '2013/01/30','2013/01/30','<DocumentElement>  <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>3</LevelId> </Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels> <LevelId>4</LevelId> </Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>5</LevelId></Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>24</LevelId></Ta_Tbl_Temporary_WeeklyOff_Levels></DocumentElement>','10:00 AM','2,3'
*/
CREATE  PROCEDURE [dbo].[Proc_TA_CheckTempWeekDay_Insert]
(
	@WeekFromdate NVARCHAR(15)='',
	@WeekTodate NVARCHAR(15)='',
	@XMLdata xml,
	--Adding this param to allowing multiple entries for single date because of various shift by Manjula.P on 19-Dec-2013
	@ClosingTime nvarchar(15),
	--Adding ShiftId param to check if already exist.
	@ShiftId nvarchar(max)
)
AS
BEGIN
	DECLARE @Index int
	set @Index = 0 		   
	create table #GiveShiftId(GivenShiftId nvarchar(max))
	declare @ParamShiftId nvarchar(max);
	set @ParamShiftId=(@ShiftId);
	insert into #GiveShiftId
	select value from  Split(@ParamShiftId,',') 
	--select * from #GiveShiftId
	EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
	--Added below line for creatinf temp table for getting shiftId for the temp weekday by MAnjula.P on 28-Dec-2013
	create table #temp(tempShiftId nvarchar(max))
	declare @TableShiftId nvarchar(max);
	create table #TableActualShiftId(Id int identity(1,1) not null,ShiftId nvarchar(max))
	insert into #TableActualShiftId
	SELECT distinct TWD.ShiftId FROM TA_Tbl_TemWeekday TWD
	inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWD.TempWeekday_Id = TWL.TempWeekday_Id
	inner join #GiveShiftId on #GiveShiftId.GivenShiftId in ( select value from dbo.Split(TWD.ShiftId,',')) 
	--inner join (select xm.LevelId from OPENXML(@Index, '/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels')with (LevelId int 'LevelId') as xm) as A on  A.LevelId = TWL.LevelId	
	WHERE ((TWD.TempWeekday_FromDate between @WeekFromdate and @WeekTodate)or(TWD.TempWeekday_ToDate between @WeekFromdate and @WeekTodate)
	or (@WeekFromdate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate) 
	or (@WeekTodate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate))
	and IsDeleted = 0 
	and #GiveShiftId.GivenShiftId in (select Value from dbo.Split (@ShiftId,','))
	--and  twl.LevelId in (select GivenShiftId from #GiveShiftId )	
	--and ClosingTime=@ClosingTime	
	group by TWD.ShiftId 
	DECLARE @MaxCount INTEGER
	DECLARE @Count INTEGER
	DECLARE @Txt VARCHAR(MAX)
	SET @Count = 1
	SET @Txt = ''
	SET @MaxCount = (select COUNT(Id) from #TableActualShiftId)
	WHILE @Count<=@MaxCount
    BEGIN
    IF @Txt!=''
        SET @Txt=@Txt+',' + (SELECT ShiftId FROM #TableActualShiftId WHERE Id=@Count)
    ELSE
        SET @Txt=(SELECT ShiftId FROM #TableActualShiftId WHERE Id=@Count)
    SET @Count=@Count+1
    END
	set @TableShiftId=(SELECT @Txt AS Txt)
	insert into #temp
	select value from Split((Select * from (select @TableShiftId as ShiftId) A), ',') 
	--select * from #temp	
	--*************************************************************************************************************
	SELECT COUNT(*) AS WeekDateCount FROM TA_Tbl_TemWeekday TWD inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWD.TempWeekday_Id = TWL.TempWeekday_Id
	inner join (select xm.LevelId from OPENXML(@Index, '/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels')with (LevelId int 'LevelId') as xm) as A on  A.LevelId = TWL.LevelId
	inner join #temp on #temp.tempShiftId in (select value from dbo.Split(TWD.ShiftId,','))
	WHERE ((TWD.TempWeekday_FromDate between @WeekFromdate and @WeekTodate)or(TWD.TempWeekday_ToDate between @WeekFromdate and @WeekTodate)
	or (@WeekFromdate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate) 
	or (@WeekTodate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate))
	and IsDeleted = 0 
	--and ClosingTime=@ClosingTime 
	and #temp.tempShiftId in (select Value from dbo.Split (@ShiftId,','))
	drop table #temp
	drop table #GiveShiftId
	drop table #TableActualShiftId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]
(
	@weekDayId int,
	@WeekFromdate NVARCHAR(15)='',
	@weekTodate NVARCHAR(15)='',
	@Type varchar(2),
	@levelid varchar(max) =null
)
AS
BEGIN
	if(@Type = 'I')
		BEGIN
			SELECT COUNT(Holiday_Id) AS WeekDateHolidayCount FROM TA_Tbl_Holiday 
			WHERE (( Holiday_FromDate>=@WeekFromdate and Holiday_ToDate<=@WeekFromdate)
			or (Holiday_FromDate>=@weekTodate  and Holiday_ToDate<=@weekTodate)) and Holiday_Type='G' and IsDeleted = 0
			and (levelid in (select value from dbo.split(@levelid,',')) or levelid=0)			
		END
	ELSE
		BEGIN
			declare @FromDate as NVARCHAR(30)
			declare @ToDate as NVARCHAR(30)
			select @FromDate = TempWeekday_FromDate,@ToDate = TempWeekday_ToDate from ta_tbl_Temweekday 
			where TempWeekday_Id = @weekDayId 
			SELECT COUNT(Holiday_Id) AS WeekDateHolidayCount FROM TA_Tbl_Holiday 
			WHERE (( Holiday_FromDate>=@WeekFromdate and Holiday_ToDate<=@WeekFromdate)
			or (Holiday_FromDate>=@weekTodate  and Holiday_ToDate<=@weekTodate)) and Holiday_Type='G' and IsDeleted = 0			
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalDatatype]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/********************************************************************
    Purpose  - To Check Duplicates for Terminal DataTypes
    Author     - Kumuthini.L 
  Proc_TA_CheckTerminalDatatype 'U',0,'RDBMS','RDBMS','','',0,'','','','',0,'','','','',0,0,0,0,0,0,0,0,0,0,0,0,0,'server=Angler38','Timecheck','','',0,'','','','','ReaderNo','CardNo',1,'','','DateTime','Type'
**********************************************************************/
CREATE PROCEDURE 	 [dbo].[Proc_TA_CheckTerminalDatatype]
(
	@Type Char(1),
	@TerminalDatatypeId INT=0,
	@RawDataFormat NVARCHAR(25),
	@FileType NVARCHAR(15), 
	@FileSourcePath NVARCHAR(2000), 
	@FileBackupPath NVARCHAR(2000), 
	@NoOfFields int, 
	@Delimiter CHAR(5),  
	@StringEnclosedBy CHAR(5),  
	@Del_ReaderNo NVARCHAR(10),  
	@Del_CardNo NVARCHAR(10),  
	@Del_DateTimeBit int,  
	@Del_Date NVARCHAR(10),  
	@Del_Time NVARCHAR(10),  
	@Del_DateTime NVARCHAR(10),  
	@Del_Type NVARCHAR(10),  
	@FL_ReaderNoFrom int,  
	@FL_ReaderNoTo int,   
	@FL_CardNoFrom int,  
	@FL_CardNoTo int,  
	@FL_DateTimeBit int,  
	@FL_DateFrom int,  
	@FL_DateTo int,  
	@FL_TimeFrom int,  
	@FL_TimeTo int,  
	@FL_DateTimeFrom int,  
	@FL_DateTimeTo int,  
	@FL_TypeFrom int,  
	@FL_TypeTo int,  
	@ConnectionString  NVARCHAR(2000),  
	@TableName NVARCHAR(50),  
	@MDB_ReaderNo NVARCHAR(25),  
	@MDB_CardNo NVARCHAR(25),  
	@MDB_DateTimeBit int,  
	@MDB_Date NVARCHAR(25),   
	@MDB_Time NVARCHAR(25),  
	@MDB_DateTime NVARCHAR(25),  
	@MDB_Type NVARCHAR(25),  
	@RDBMS_ReaderNo NVARCHAR(25),  
	@RDBMS_CardNo NVARCHAR(25),  
	@RDBMS_DateTimeBit int,
	@RDBMS_Date NVARCHAR(25), 
	@RDBMS_Time NVARCHAR(25),
	@RDBMS_DateTime NVARCHAR(25), 
	@RDBMS_Type NVARCHAR(25),
	@RDBMS_MDB_Flag NVARCHAR(25)
)
AS
BEGIN
	DECLARE @sql nvarchar(2000)
	IF(@Type = 'I')
	BEGIN
		set @sql='SELECT TerminalDatatype_ID FROM  TA_tbl_TerminalDatatype WHERE (File_SourcePath=N''' + @FileSourcePath + ''' AND File_BackupPath=N''' + @FileBackupPath + ''' AND Delimiter_NoOfFields=' + cast(@NoOfFields as nvarchar(20)) + ' AND Delimiter_Delimiter=''' + @Delimiter + '''
		AND Delimiter_StringEnclosedBy=''' + @StringEnclosedBy + ''' AND Delimiter_ReaderNo=''' + cast(@Del_ReaderNo as nvarchar(20)) + ''' AND Delimiter_CardNo=''' + cast(@Del_CardNo as nvarchar(20)) + '''AND Delimiter_DateTimeBit=''' + cast(@Del_DateTimeBit as nvarchar(20)) + ''' AND Delimiter_Date=N''' + @Del_Date + ''' AND 
		Delimiter_Time=N''' + @Del_Time + ''' AND Delimiter_DateTime=N''' + @Del_DateTime + ''' AND Delimiter_Type=''' + @Del_Type + ''' AND FixedLength_ReaderNoFrom=''' + cast(@FL_ReaderNoFrom as nvarchar(20)) + ''' AND FixedLength_ReaderNoTo=''' + cast(@FL_ReaderNoTo as nvarchar(20)) + ''' AND 
		FixedLength_CardNoFrom=''' + cast(@FL_CardNoFrom as nvarchar(20)) + ''' AND FixedLength_CardNoTo=''' + cast(@FL_CardNoTo as nvarchar(20)) + ''' AND FixedLength_DateTimeBit=''' + cast(@FL_DateTimeBit as nvarchar(20)) + ''' AND FixedLength_DateFrom=''' + cast(@FL_DateFrom as nvarchar(20)) + '''  AND FixedLength_DateTo=''' + cast(@FL_DateTo as nvarchar(20)) + '''
		AND FixedLength_TimeFrom=' + cast(@FL_TimeFrom as nvarchar(20)) + ' AND FixedLength_TimeTo=' + cast(@FL_TimeTo as nvarchar(20)) + ' AND FixedLength_DateTimeFrom=' + cast(@FL_DateTimeFrom as nvarchar(20)) + ' AND FixedLength_DateTimeTo=' + cast(@FL_DateTimeTo as nvarchar(20)) + ' AND
		FixedLength_TypeFrom=''' + cast(@FL_TypeFrom as nvarchar(20)) + ''' AND FixedLength_TypeTo=''' + cast(@FL_TypeTo as nvarchar(20)) + ''' AND ConnectionString=N''' + @ConnectionString + ''' AND TableName=N''' + @TableName + ''' AND MDB_ReaderNo=''' + cast(@MDB_ReaderNo as nvarchar(20)) + ''' AND MDB_CardNo=''' + cast(@MDB_CardNo as nvarchar(20)) + '''
		AND MDB_DateTimeBit=''' + cast(@MDB_DateTimeBit as nvarchar(20)) + ''' AND MDB_Date=''' + cast(@MDB_Date as nvarchar(20)) + ''' AND MDB_Time=N''' + @MDB_Time + ''' AND MDB_DateTime=N''' + @MDB_DateTime + ''' AND MDB_Type=N''' + @MDB_Type + ''' AND RDBMS_ReaderNo=''' + cast(@RDBMS_ReaderNo as nvarchar(20)) + '''
		AND RDBMS_CardNo=''' + cast(@RDBMS_CardNo as nvarchar(20)) + ''' AND RDBMS_DateTimeBit=''' + cast(@RDBMS_DateTimeBit as nvarchar(20) )+ ''' AND RDBMS_Date=N''' + @RDBMS_Date  + ''' AND RDBMS_Time=N''' + @RDBMS_Time + ''' AND RDBMS_DateTime=N''' + @RDBMS_DateTime + '''
		AND RDBMS_Type=N''' + @MDB_Type + ''' AND RDBMS_MDB_Flag=''' + @RDBMS_MDB_Flag + ''' AND FileType=N''' + @FileType + ''' AND Raw_Data_Format <> N''' + @RawDataFormat + ''' AND IsDeleted=0) OR (Raw_Data_Format = N''' + @RawDataFormat + ''')'
	END
	ELSE IF(@Type = 'U')
	BEGIN
		set @sql='SELECT TerminalDatatype_ID FROM  TA_tbl_TerminalDatatype WHERE (File_SourcePath=N''' + @FileSourcePath + ''' AND File_BackupPath=N''' + @FileBackupPath + ''' AND Delimiter_NoOfFields=' + cast(@NoOfFields as nvarchar(20)) + ' AND Delimiter_Delimiter=''' + @Delimiter + '''
		AND Delimiter_StringEnclosedBy=''' + @StringEnclosedBy + ''' AND Delimiter_ReaderNo=''' + cast(@Del_ReaderNo as nvarchar(20)) + ''' AND Delimiter_CardNo=''' + cast(@Del_CardNo as nvarchar(20)) + ''' AND Delimiter_DateTimeBit=' + cast(@Del_DateTimeBit as nvarchar(20)) + ' AND Delimiter_Date=N''' + @Del_Date + ''' AND 
		Delimiter_Time=N''' + @Del_Time + ''' AND Delimiter_DateTime=N''' + @Del_DateTime + ''' AND Delimiter_Type=''' + @Del_Type + ''' AND FixedLength_ReaderNoFrom=''' + cast(@FL_ReaderNoFrom as nvarchar(20)) + ''' AND FixedLength_ReaderNoTo=''' + cast(@FL_ReaderNoTo as nvarchar(20)) + ''' AND 
		FixedLength_CardNoFrom=''' + cast(@FL_TimeFrom as nvarchar(20)) + ''' AND FixedLength_CardNoTo=''' + cast(@FL_CardNoTo as nvarchar(20)) + ''' AND FixedLength_DateTimeBit=''' + cast(@FL_DateTimeBit as nvarchar(20)) + ''' AND FixedLength_DateFrom=''' + cast(@FL_DateTimeFrom as nvarchar(20)) + ''' AND FixedLength_DateTo=''' + cast(@FL_DateTimeTo as nvarchar(20)) + '''
		AND FixedLength_TimeFrom=''' + cast(@FL_TypeFrom as nvarchar(20)) + ''' AND FixedLength_TimeTo=''' + cast(@FL_TimeTo as nvarchar(20)) + ''' AND FixedLength_DateTimeFrom=''' + cast(@FL_DateTimeFrom as nvarchar(20)) + ''' AND FixedLength_DateTimeTo=''' + cast(@FL_DateTimeTo as nvarchar(20)) + ''' AND
		FixedLength_TypeFrom=''' + cast(@FL_TimeFrom as nvarchar(20)) + ''' AND FixedLength_TypeTo=''' + cast(@FL_TypeTo as nvarchar(20)) + ''' AND ConnectionString=N''' + @ConnectionString + ''' AND TableName=N''' + @TableName + ''' AND MDB_ReaderNo=''' + cast(@MDB_ReaderNo as nvarchar(20)) + ''' AND MDB_CardNo=''' + cast(@MDB_CardNo as nvarchar(20)) + '''
		AND MDB_DateTimeBit=''' + cast(@MDB_DateTimeBit as nvarchar(20)) + ''' AND MDB_Date=''' + cast(@MDB_Date as nvarchar(20)) + ''' AND MDB_Time=N''' + @MDB_Time + ''' AND MDB_DateTime=N''' + @MDB_DateTime + ''' AND MDB_Type=N''' + @MDB_Type + ''' AND RDBMS_ReaderNo=''' + cast(@RDBMS_ReaderNo as nvarchar(20)) + '''
		AND RDBMS_CardNo=''' + cast(@RDBMS_CardNo as nvarchar(20)) + ''' AND RDBMS_DateTimeBit=''' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + ''' AND RDBMS_Date=N''' + @RDBMS_Date + ''' AND RDBMS_Time=N''' + @RDBMS_Time + ''' AND RDBMS_DateTime=N''' + @RDBMS_DateTime + '''
		AND RDBMS_Type=N''' + @MDB_Type + ''' AND RDBMS_MDB_Flag=''' + @RDBMS_MDB_Flag + ''' AND FileType=N''' + @FileType + '''  AND Raw_Data_Format <> N''' + @RawDataFormat + ''' AND TerminalDatatype_ID <> ''' + cast(@TerminalDatatypeId as nvarchar(20)) + ''' AND IsDeleted=0) OR (Raw_Data_Format=N''' + @RawDataFormat + ''' AND TerminalDatatype_ID <> ''' + cast(@TerminalDatatypeId as nvarchar(20)) + ''')'
	END
	exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	:	Proc_TA_CheckTerminalName  
Description 	:	check terminal name before insert
Tables Included :	TA_Tbl_Terminal  
Created By 	:	kumuthini  
Created On 	:	14-Aug-2007
Modified By 	: 	Manikandan.R
Modified On 	:  	22-11-2016 15.17
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckTerminalName]
(
	@TerminalReaderId nvarchar(10)='',
	@TerminalName nvarchar(50)
)
AS
BEGIN
	SELECT count(Terminal_Id) AS TID FROM TA_Tbl_Terminal WHERE (Terminal_ReaderID=@TerminalReaderId OR Terminal_Name=@TerminalName) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName_Sync]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name 	:	Proc_TA_CheckTerminalName_Sync  
Description 	:	check terminal name before insert
Tables Included :	TA_Tbl_Terminal  
Created By 	:	karthikeyan.R
Created On 	:	05-Mar-2016
*/  
create  PROCEDURE [dbo].[Proc_TA_CheckTerminalName_Sync]
(
@TerminalReaderId nvarchar(50)=''
)
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
SELECT count(Terminal_Id) AS TID FROM TA_Tbl_Terminal 
WHERE Terminal_ReaderID=@TerminalReaderId
END
----------------------------------
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalNameUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckTerminalNameUpdate  
Description 	: check terminal name before update
Tables Included : TA_Tbl_Terminal  
Created By 	: kumuthini  
Created On 	: 14-Aug-2007
Modified By 	: Prabakaran.P
Modified On 	: 17-Mar-08
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckTerminalNameUpdate]
(
@TerminalID INT,
@TerminalReaderID NVARCHAR(50),
@TerminalName nvarchar(50)
)
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
	SELECT count(Terminal_Id)  AS TID FROM TA_Tbl_Terminal 
	WHERE (Terminal_ReaderID=@TerminalReaderID OR Terminal_Name=@TerminalName) and Terminal_Id<>@TerminalID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckTitle_Insert  'GH',5
Description : check title before insert  
Tables Included : TA_Tbl_Title  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTitle_Insert]  
(  
 @TitleName NVARCHAR(50),
 @LevelId int
)   
AS  
Declare @Isdel int  
declare @sql as nvarchar(max)
SET @Isdel=0  
 BEGIN    
   set @sql = 'SELECT COUNT(TitleName) AS TName FROM TA_Tbl_Title WHERE upper(TitleName)=upper(N'''+@TitleName+''') and LevelID in ('+cast(@LevelId as nvarchar)+') '  
   exec(@sql)
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*Procedure Name : Proc_TA_CheckTitle_Update    
Description : check title before update    
Tables Included : TA_Tbl_Title    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE Procedure [dbo].[Proc_TA_CheckTitle_Update]
(	
	@TitleId int
) 
As
	DECLARE @Isdel INT
	declare @sql as nvarchar(3000)
	Declare @TitleName NVARCHAR(50)
	SET @Isdel=0
	BEGIN
		set @TitleName=(Select TitleName from TA_Tbl_Title where TitleId=@TitleId)
		set @sql = 'Select Count(TitleName)as TName from TA_Tbl_Title where TitleId<>'+cast(@TitleId as nvarchar(25))+' And TitleName=N'''+@TitleName+''' '	
        exec(@sql)	
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Updates]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckTitle_Insert    
Description : check title before insert    
Tables Included : TA_Tbl_Title    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTitle_Updates]
(  
	@TitleName NVARCHAR(50),
	@TitleID int,
	@LevelId int
)   
AS  
Declare @Isdel int  
declare @sql as nvarchar(3000)
SET @Isdel=0  
BEGIN
	set @sql = 'SELECT COUNT(TitleName) AS TName FROM TA_Tbl_Title WHERE upper(TitleName)=upper(N'''+@TitleName+''') and TitleId<>'+cast(@TitleID as	nvarchar(250))+' and LevelID in ('+cast(@LevelId as nvarchar)+')'  
	exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_CheckTitleName]
(@CompanyId INT,@RegionId INT,@BranchId INT,@DepartmentId INT,@Section INT,@TitleId INT)
as
BEGIN
	SELECT COUNT(TitleId) as TId  FROM TA_Tbl_TitleMapping WHERE Company_Id=@CompanyId 
		and Region_Id=@RegionId and Branch_Id=@BranchId and Department_Id=@DepartmentId And Section_Id=@Section AND TitleId=@TitleId AND IsDeleted=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleNameBYID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckTitleNameBYID  
Description : check title by id
Tables Included : TA_Tbl_TitleMapping  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckTitleNameBYID]    
(    
 --@TitleName NVARCHAR(50),    
 @TitleId int    
)     
As    
DECLARE @Isdel INT    
SET @Isdel=1    
 BEGIN    
   Select Count(TitleId)as TName from TA_Tbl_TitleMapping    
   where TitleId=@TitleId AND Isdeleted=@Isdel --And TitleName=@TitleName     
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDelete]
	@TypeID as int
AS
BEGIN
	select count(*) as RecCount from ta_tbl_employeeType
		where TypeId=@TypeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicate]
	@Opr as nvarchar(1),
	@TypeName as nvarchar(50),
	@TypeID as int
AS
BEGIN
	if (@Opr='I')
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName 
		End
	Else
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and TypeId<>@TypeId 
		End	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicateForRestore]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicateForRestore]
	@Opr as nvarchar(1),	
	@TypeID as int
AS
BEGIN
	Declare @TypeName as nvarchar(50)
	set @TypeName=(select TypeName from TA_Tbl_Type where TypeId=@TypeID)
	if (@Opr='I')
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and Isdeleted=0
		End
	Else
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and TypeId<>@TypeId and Isdeleted=0
		End	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUnProcessedDataExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/***************************************************************************
    Purpose  - Checking in the Processed Data whether records are processed
    Author     - Kumuthini.L 
    Proc_TA_CheckUnProcessedDataExists	'','',''
****************************************************************************/
CREATE PROCEDURE [dbo].[Proc_TA_CheckUnProcessedDataExists]
(
	@SwipeCardNo nVarchar(25),
	@FromDate datetime,
	@ToDate datetime
)
AS
BEGIN
	SELECT Count(*) AS Count FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id = @SwipeCardNo AND Date BETWEEN @FromDate AND @ToDate AND ProcessFlag = 0
END
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_CheckUserExists] 
(
@UserName VARCHAR(15)
)
AS
BEGIN
SELECT Count(UserName) as UserCount FROM TA_Tbl_Employee WHERE UserName=@UserName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckUserRights  
Description : Checking UserRights
Tables Included : ta_tbl_userRights  
Created By : senthil  
Created On : 11-oct-2007
Modified By :  
Modified On :  
[dbo].[Proc_TA_CheckUserRights] 18,2,1
exec Proc_TA_CheckUserRights @pageId=18,@groupId=2,@opr=' '
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckUserRights]
(
	@pageId int,
	@groupId int,
	@opr varchar(20)
)
AS
BEGIN

	if (@opr='')
		Begin
			select * from ta_tbl_userRights where (pageid=@pageId and groupid=@groupId and Isdeleted=0) and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)
			
		End
	Else
		Begin
			declare @sql as nvarchar(500)
			set @sql = 'select * from ta_tbl_userRights where (pageid=' + cast(@pageId as nvarchar(10)) + ' and groupid= ' + cast(@groupId as nvarchar(10)) + ' and Isdeleted=0) and (' + cast(@opr as nvarchar(20)) + '=1)'
			exec(@sql)

			print @sql
		End
END

--select * from ta_tbl_userRights where pageId=18 and groupId=2 and isdeleted=0 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckUserStatus  
Description : check user status 
Tables Included : TA_Tbl_ConcurrentUser  
Created By : S.Christopher 
Created On : 30-Oct-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckUserStatus] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_ConcurrentUser
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_ForModification]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [dbo].[Proc_TA_CheckVehicle_ForModification]'asdfas',7
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckVehicle_ForModification]
	@VehicleNo NVARCHAR(50),  
	@VehicleId int  
AS
declare @sql as nvarchar(3000)
DECLARE @Isdel INT  
SET @Isdel=0  
BEGIN  
   --Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>@VehicleId And VehicleNo=@VehicleNo AND Isdeleted=@Isdel
   set @sql = 'Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>'+cast(@VehicleId as nvarchar(25))+' And VehicleNo=N'''+@VehicleNo+''' AND Isdeleted='+cast(@Isdel as nvarchar(25))+''   
   exec(@sql)
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : Proc_TA_CheckVehicle_Insert  
Description : check vehicle before insert, is exist or not    
Tables Included : TA_Tbl_Transportation_Vehicle    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE PROCEDURE [dbo].[Proc_TA_CheckVehicle_Insert]  
(  
	@VehicleNo NVARCHAR(50)     
)   
AS
	declare @sql as nvarchar(3000)  
	--Declare @Isdel int  
	--SET @Isdel=0    
 BEGIN  
	--SELECT COUNT(VehicleNo) AS VNO FROM TA_Tbl_Transportation_Vehicle WHERE VehicleNo=@VehicleNo AND Isdeleted=@Isdel  
	set @sql ='SELECT COUNT(VehicleNo) AS VNO FROM TA_Tbl_Transportation_Vehicle WHERE VehicleNo=N'''+@VehicleNo+'''' 
	--AND Isdeleted='+cast(@Isdel as nvarchar(25))+''
	exec(@sql)
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name : Proc_TA_CheckVehicle_Update  
Description : check vehicle before update, is exist or not    
Tables Included : TA_Tbl_Transportation_Vehicle    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicle_Update]
(
	@VehicleId int
)   
As
	DECLARE @sql as nvarchar(3000)
	DECLARE @Isdel INT  
	SET @Isdel=0
	DECLARE @VehicleNo varchar(50)
	BEGIN  
		--Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>@VehicleId And VehicleNo=@VehicleNo AND Isdeleted=@Isdel
		Select @VehicleNo=VehicleNo  from TA_Tbl_Transportation_Vehicle where VehicleId=@VehicleId
		set @sql = 'Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>'+cast(@VehicleId as nvarchar(25))+' And VehicleNo=N'''+@VehicleNo+''' AND Isdeleted='+cast(@Isdel as nvarchar(25))+''
		exec(@sql)     
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckVehicleMapping_VehicleID_INSERT
Description : check vehicle mapping while insert
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]
(
	@VehicleId INT
) 
As
DECLARE @Isdel INT
SET @Isdel=1
	BEGIN
			SELECT count(VehicleId) AS VId FROM TA_Tbl_Transportation_Mapping WHERE VehicleId=@VehicleId AND Isdeleted=@Isdel
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_CheckVehicleMapping_VehicleID_Update
Description : check vehicle mapping while update
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]
(
	@VehicleId INT,
	@RouteId   INT
) 
As
DECLARE @Isdel INT
SET @Isdel=1
	BEGIN
			SELECT count(VehicleId) AS VId FROM TA_Tbl_Transportation_Mapping 
			WHERE VehicleId<>@VehicleId AND RouteId=@RouteId AND Isdeleted=@Isdel
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleNo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_CheckVehicleNo  
Description : check vehicle no    
Tables Included : TA_Tbl_RouteMaster    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  
*/
CREATE Procedure [dbo].[Proc_TA_CheckVehicleNo]       
(         
	@VehicleId NVARCHAR(100)        
)         
As	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	BEGIN                
		--Select Count(VehicleID)as VNO from TA_Tbl_RouteMaster where VehicleId=@VehicleId  AND Isdeleted=0
		SET @Query = 'Select Count(VehicleID)as VNO from TA_Tbl_RouteMaster where VehicleId IN ('+ @VehicleId +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosed]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
Procedure Name  :   
Description  :   
Tables Included :    
Created By  : Prabakaran.P  
Created On  : 08-Feb-08  
Modified By  :    
Modified On  :     
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckYearClosed]        
@EmployeeId int
AS        
BEGIN   
SELECT count(YearClosureId) as YearCount FROM TA_Tbl_YearClosure   
WHERE (YearClosed is not null and DateClosed is not null) 
and Year_SettingID =(Select YearSettings_Id from TA_Tbl_YearSetting WHERE IsActive=1)
and Employee_Id=@EmployeeId
END   
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]
	-- Add the parameters for the stored procedure here
	@yearSettingId int, @organizationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_YearClosure where Year_SettingID=@yearSettingId and OrgLevelId=@organizationId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureExistOrNot]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	28-Jan-2014
Descriptions	:	Checking whether the selected year closure is exist or not based on orgid and yearsettingsid
Proc_TA_CheckYearClosureExistOrNot 6,1
*/
CREATE proc [dbo].[Proc_TA_CheckYearClosureExistOrNot]
(
@OrgLevelId int=0,
@Year_SettingID int=0
)
as
begin
declare @Count as int;
set @Count=0;
set @Count=(select COUNT(*) from TA_Tbl_YearClosure where OrgLevelId=@OrgLevelId and Year_SettingID=@Year_SettingID and isnull(YearClosed,'')<>'' and ISNULL(DateClosed,'')<>'');
select isnull(@Count,0) as count
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CheckYearSettingExists   '','','A',35
Description : Save year settings details into table  
Tables Included : TA_Tbl_YearSetting  
Created By : Prabakaran  
Created On : 21-Nov-07  
Modified By :  Gopinath.k
Modified On :  09-Nov-16 for wrongly fetching of shift allocation from next year also while creating year in between months.
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckYearSettingExists]   
@FromDate varchar(30),
@ToDate varchar(30),
@YearType char(1),
@YearSettings_Id int
as  
if( @YearType='P')
begin
	SELECT count(*) as YearCount FROM TA_Tbl_YearSetting as Count 
	where (FromDate between @FromDate and @ToDate) or (ToDate between @FromDate and @ToDate)
	or (@FromDate between FromDate and ToDate) or (@ToDate between FromDate and ToDate)
end
else if (@YearType='A')
begin
	declare @count as int  
	declare @RecordExiststing as int  
	set @count=0   
	begin
		set @RecordExiststing=(SELECT count(elp.LeavePolicy_Id) FROM ta_tbl_Emp_LeavePolicy elp inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId where elp.isdeleted=0 and ys.YearSettings_Id=@YearSettings_Id)  
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'Leavepolicy'
	end
	begin
		set @RecordExiststing=(SELECT count(Holiday_Id) FROM ta_tbl_holiday h inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id where h.isdeleted=0 and ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'Holiday'
	end
	begin
		set @RecordExiststing=(SELECT count(Holiday_Id) FROM ta_tbl_holidaysettings hs inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'Holiday Settings'
	end
	/* This code commented because year closure count checked in Proc_Ta_deleteYearSetting  */
	/*
	begin
	set @RecordExiststing=(SELECT count(YearClosureId) FROM ta_tbl_yearclosure yc inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=yc.Year_SettingID where ys.YearSettings_Id=@YearSettings_Id)
	if @RecordExiststing<>0 
	set @count=@count+@RecordExiststing
	end
	*/
	begin
		declare @StartMonth as int 
		declare @EndMonth as int 
		--declare @StartYear as int 
		--declare @EndYear as int 
		--Set @StartYear=(select StartYear from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		--Set @EndYear=(select EndYear from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		Set @StartMonth=(select datepart(month,convert(varchar(20),Startyear)+'-'+convert(varchar(20),StartMonth)+'-01')from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		Set @EndMonth=(select datepart(month,convert(varchar(20),Endyear)+'-'+convert(varchar(20),EndMonth)+'-01')from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		set @RecordExiststing=(select count(ps.year) from ta_tbl_permanentshiftAllocation ps 
		inner join  ta_tbl_yearsetting ys on (ys.StartYear=ps.Year and ps.Month>= @StartMonth) or (ys.EndYear=ps.Year and ps.Month<= @EndMonth)
		where ys.YearSettings_Id=@YearSettings_Id )
		--set @RecordExiststing=(select count(ps.year) from ta_tbl_permanentshiftAllocation ps 
		--inner join  ta_tbl_yearsetting ys on ys.StartYear=ps.Year or ys.EndYear=ps.Year 
		--where ys.YearSettings_Id=@YearSettings_Id and ps.Month>= @StartMonth and ps.Month<= @EndMonth)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'permanentshiftAllocation'
	end
	begin
		set @RecordExiststing=(select count(ts.year) from TA_Tbl_TemporaryShiftAllocation ts inner join  ta_tbl_yearsetting ys on ys.StartYear=ts.Year or ys.EndYear=ts.Year where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'TemporaryShiftAllocation'
	end
	begin
		set @RecordExiststing=(select count(mc.MonthClosure_Id) from ta_tbl_monthclosure mc inner join  ta_tbl_yearsetting ys on ys.StartYear=mc.MonthClosure_Year or ys.EndYear=mc.MonthClosure_Year where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'Monthclosure'
	end 
	begin
		set @RecordExiststing=(SELECT count(YearSettings_Id) FROM TA_Tbl_YearSetting where IsActive=1 and YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,'Year Setting'
	end
	if (@count>0)
	begin
		set @count=1
	end
		SELECT @count as YearCount
	end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckYearSettingExistsWhileYearClosing '1/1/2007','12/31/2008','35,18'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]
	-- Add the parameters for the stored procedure here
	@fromDate nvarchar(30),
	@toDate nvarchar(30),
	@yearSettingId nvarchar(1000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @query nvarchar(2000)
	set @query = ''
	set @query = '(SELECT count(*) FROM TA_Tbl_YearSetting where (FromDate between CONVERT(DATETIME, '''+cast(@toDate as nvarchar(30))+''', 102) and CONVERT(DATETIME, '''+cast(@fromDate as nvarchar(30))+''', 102) or ToDate between CONVERT(DATETIME, '''+cast(@toDate as nvarchar(30))+''', 102) and CONVERT(DATETIME, '''+cast(@fromDate as nvarchar(30))+''', 102)) and yearsettings_id not in ('+@yearSettingId+'))'
	exec (@query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Child_Levels_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Child_Levels_Insert] 
(
	@opr nvarchar(1),
	@levelId int,
	@levelName nvarchar(100),
	@parentLevelId int,	
	@description nvarchar(255),
	@city nvarchar(100),
	@state nvarchar(100),
	@country nvarchar(100),
	@zip nvarchar(50),
	@phone1 nvarchar(50),
	@phone2 nvarchar(50),
	@fax1 nvarchar(50),
	@fax2 nvarchar(50),
	@email nvarchar(100),
	@web nvarchar(100),
	@id int,
	@logo image,
	@emp_id as nvarchar(25),
	@TimezoneId int
)
AS
Begin
	declare @sql as nvarchar(3000)  
	declare @groupId as bigint
	select @groupId=GroupId from ta_tbl_usergroup where groupName='SuperAdmin'
	if(@parentLevelId!=0)
	Begin

		Select @TimezoneId=Case when levelId=1 then @TimezoneId ELSE TimezoneId End 
		From Ta_Tbl_levelDetails where id=@parentLevelId

		if(@opr!='I')
		begin
			update Ta_Tbl_levelDetails set TimezoneId=@TimezoneId where id in (Select * From dbo.[fn_TA_GetParentChild]('superadmin',@id))
		End

		--Else @TimezoneId End From Ta_Tbl_levelDetails where id=@parentLevelId
		 --CASE WHEN  levelId!=1 ELSE TimezoneId  END 
	End

	if (@opr='I')
		Begin
			insert into Ta_tbl_levelDetails (levelid,parentId,name,description,city,state,country,zip,phone1,phone2,fax1,fax2,email,webaddress,emp_id,TimezoneId) 
			values (cast (@levelId as nvarchar(25)),
			cast(@parentLevelId as nvarchar(25)),
			@levelname,
			@description,
			@city,
			@state,
			@country,
			@zip,
			@phone1,
			@phone2,
			@fax1,
			@fax2,
			@email ,@web,@emp_id,@TimezoneId)			
			declare @nextId as int
			set @nextId = (select @@identity)
			update Ta_tbl_leveldetails set logo=@logo where id = @nextId
			--Added By manikandan.R
			--For Inserting the default values to reduce the unwanted redirection.
			--Added on 19-11-2013 03:57 PM
			--This option is not in the below version like 1.0,1.1,1.2,1.3.
			if(@parentLevelId=0)
				begin
				--Added last arguments as 0 for ODEntry in  TA_Tbl_ApprovalSettings column
					insert into TA_Tbl_ApprovalSettings values(@nextId,0,0,0,0,1,0,0,0,0,0,0)
					--select 1
				end

			--IF EXISTS(SELECT Grade_ID FROM TA_Tbl_Grade WHERE Grade_Level=4)
			--BEGIN
			--	DECLARE @Grade_ID int
			--	SELECT @Grade_ID =Grade_ID FROM TA_Tbl_Grade WHERE Grade_Level=4
			--	IF(ISNULL(@Grade_ID,0)!=0)
			--	BEGIN
			--		INSERT INTO TA_Tbl_Title VALUES('Manager','Manager',@nextId,0,@Grade_ID,1,0,GETDATE())
			--	END
			--END	
			--Inserts the Level wise rights
			--Below line commented by Manikandan.R on 14-July-2020 on 12:38 pM after relesing of iffco project
			--insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) values (@groupId,@nextId,@emp_Id)
			goto UpdateRights;
			
		End
	Else
		Begin
			update ta_tbl_levelDetails set levelid=@levelId,parentId=@parentLevelId,name=@levelName,description=@description,city=@city,state=@state,country=@country,zip=@zip,phone1=@phone1,phone2=@phone2,fax1=@fax1,fax2=@fax2,email=@email,webaddress=@web,logo=@logo,emp_id=@emp_id,TimezoneId=@TimezoneId where id=@id			
		End
	UpdateRights:
		--select 1
		Declare @TotalUsergroup int
			Declare @start int
			set @start=1
			Create table #Tempusergroup(Autoid int identity(1,1),groupID bigint)
			Insert into #Tempusergroup
			select groupId from TA_Tbl_Usergroup 
			select @TotalUsergroup= COUNT(*) from TA_Tbl_Usergroup 
			Declare @parentID bigint
			Declare @TotallevelCount int
			Declare @TotallevelRightsCount int
			select @TotallevelCount=count(*) from Ta_Tbl_levelDetails where parentId=@parentLevelId and id!=@nextId
			while @start<=@TotalUsergroup
			begin
				select @groupId=groupId  from #Tempusergroup where Autoid=@start				
				select @TotallevelRightsCount=count(*) from Ta_Tbl_levelDetails LD 
				left outer join TA_Tbl_LevelRights LR on LD.id=LR.LevelId
				where GroupId=@groupId and LD.parentId=@parentLevelId and isnull(LR.LevelId,0)!=0
				if(@TotallevelCount=@TotallevelRightsCount)
				begin					
					insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) values (@groupId,@nextId,@emp_Id)		
				end
				set @start=@start+1
			end
End

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Show Employee info in Grid - CMI Tech>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	Delete from Ta_Tbl_ImportMasterData

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectCompany]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <22-Jan-2020>
-- Description:	<CMITech Select Company dropdown in grid>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CMITechSelectCompany] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @LastLevel int
	Declare @LastLevelcount int
	Declare @LastLevelBefore int
	
	 set @LastLevel = (select MAX(levelID) from ta_tbl_level where isDeleted = 0)
	 set @LastLevelcount = (select count(*) from Ta_Tbl_levelDetails where levelId = @LastLevel)	 
	 if(@LastLevelcount = 0)
	 Begin	
		create table #LevelTemp (LevelId int)
		insert into #LevelTemp select top 2 levelID from ta_tbl_level  where isDeleted = 0 order by levelid desc;
		set @LastLevelBefore = (select top 1 levelID from #LevelTemp order by levelid asc)
		Select isnull(id,0) as id, isnull(name,'') as name 
		from Ta_Tbl_levelDetails where levelId = @LastLevelBefore
		order by id asc	
	 End
	 Else
	 Begin
		Select isnull(id,0) as id, isnull(name,'') as name 
		from Ta_Tbl_levelDetails where levelId = @LastLevel
		order by id asc	
	 End
	 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectDesignation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <22-Jan-2020>
-- Description:	<CMITech Select Designation dropdown in grid>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CMITechSelectDesignation] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Select isnull(TitleId,0) as TitleId, (isnull(TitleName,'') + ' - ' + c.name) as TitleName, b.Grade_Level as Grade_Level
	--from ta_tbl_title a
	--inner join Ta_Tbl_levelDetails c on c.id = a.LevelID 
	--inner join TA_Tbl_Grade b on b.Grade_ID = a.GradeID
	
	Select isnull(TitleId,0) as TitleId, (isnull(TitleName,'')) as TitleName, b.Grade_Level as Grade_Level
	from ta_tbl_title a	
	inner join TA_Tbl_Grade b on b.Grade_ID = a.GradeID
	
 
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectRBMSRawDataForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 23-05-2015
-- Description:	Getting The RDBMSRaw data details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CollectRBMSRawDataForService]
	-- Add the parameters for the stored procedure here
	@FileType nvarchar(30),
	@TerminalDatatype_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ConnectionString,TableName,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_DateTime,DateTimeFormat,RDBMS_Date,DateFormat,RDBMS_Time,TimeFormat,
	RDBMS_Type,RDBMS_MDB_Flag,RDBMS_TransactionIdentifier,TransactionIdentifierBit,TransactionIdentifierValue,IsEncrypted from TA_Tbl_TerminalDataType 
	where FileType = @FileType and TerminalDatatype_ID = @TerminalDatatype_ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectTerminalDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 23-05-2015
-- Description:	Getting The terminal details for processing
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CollectTerminalDetailsForService]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select TD.TerminalDatatype_ID,TD.FileType,TB.KeyValue from TA_Tbl_TerminalDatatype TD 
	inner join TA_Tbl_TerminalBrand TB on TD.BrandID=TB.BrandID where TD.IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationEntryByID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan
-- Create date: 22-Mar-2017
-- Description:	Delete the compensation entry by ID check the compoff taken any leave, If yes then entry can't deleted.
-- Proc_TA_CompensationEntryByID 253
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CompensationEntryByID]
	-- Add the parameters for the stored procedure here
	@CompOff_ID as bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LeaveApplication as nvarchar(50)
	SELECT @LeaveApplication=LeaveApplicationId FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@CompOff_ID
	if(@LeaveApplication is null or @LeaveApplication='')
		Begin
			update TA_Tbl_ProcessedData set OvertimeStatus='Canceled' where Process_Rec_ID in (select Process_Rec_ID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@CompOff_ID)
			update TA_Tbl_OverTimeStatus set isdelete=1,OverTimeStatus='Canceled' where ExtraTime_Id=@CompOff_ID
			Select '1'
		END
	else
		BEGIn
			Select 'Availed'
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  Karthikeyan.R
-- Create date: 08-Feb-2017
-- Description: <Description,,>  
-- Proc_TA_CompensationListing null,null,'01/01/1900','01/01/1900','Management',0,3
-- select * from TA_Tbl_OverTimeStatus
 -- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CompensationListing]  
 -- Add the parameters for the stored procedure here  
 @EmployeeFirstName nvarchar(MAX),  
 @EmployeeId nvarchar(MAX),  
 @fromdate nvarchar(40),  
 @ToDate nvarchar(40),
 @UserGroupName nvarchar(250),
 @ParentID int,
 @EmpAutoID int
AS  
BEGIN
	SET NOCOUNT ON;  
	Declare @sqlQuery nvarchar(Max)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	declare @ELTodate as datetime
	if(@ToDate='01/01/1900')
	begin
		set @ELTodate=getdate()
	end
	else
	begin
		set @ELTodate=@ToDate
	end
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	 SET @sqlEmpLevel=
      'INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
      from  (
      SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
      from TA_Tbl_EmployeeLevel el
      INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
      INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId '
      set @sqlEmpLevel= @sqlEmpLevel +' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
      INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ELTodate as nVARCHAR(50))+''', 102) and EL.LevelId is not null'      
	EXECUTE(@sqlEmpLevel)
	--select * from #LevelRights
	--select * from #EmpLevel
	set @sqlQuery=''  
	set @sqlQuery='select  OT.ExtraTime_Id ''Compensation_Id'',E.Employee_Code_Id as ''Employee_ID'',E.Employee_FirstName + '' ''+ isnull(E.Employee_LastName,'''') as Employee_FirstName ,
	case when '+CONVERT(varchar,@dateFormat)+' =106 then
		REPLACE(CONVERT(VARCHAR, OT.ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
	else CONVERT(VARCHAR, OT.ApplicationDate, '+CONVERT(varchar,@dateFormat)+') end as ApplicationDate,
	case when '+CONVERT(varchar,@dateFormat)+' =106 then
		REPLACE(CONVERT(VARCHAR, OT.Date,'+CONVERT(varchar,@dateFormat) + '),'' '',''-'') 
	else CONVERT(VARCHAR, OT.Date, '+CONVERT(varchar,@dateFormat)+') end as FromDate,'''' Type,OT.Reason,OT.OverTimeStatus ''Status'',
	case	when OT.InTime<>''00:00'' then	case	when ('''+CONVERT(varchar,@TimeFormat)+ ''') =''hh:mm'' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.InTime,0)), 114)
															else SUBSTRING(OT.InTime,13,5)+'' '' + SUBSTRING(OT.InTime,18,2)
													end 
						else ''''
				end	InTime
	,
	case	when OT.OutTime<>''00:00'' then	case	when ('''+CONVERT(varchar,@TimeFormat)+ ''') =''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.OutTime,0)), 114)
															else	SUBSTRING(OT.OutTime,13,5)+'' '' + SUBSTRING(OT.OutTime,18,2) 
													end 
						else ''''
				end	OutTime
,OT.HrsExtra ''WorkedHours'',OT.DaysWorked ''DayWorked'',OT.OverTimeStatus ''Comp_Status'',Ta_Tbl_levelDetails.name as LevelName
	from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on OT.Employee_Id=E.Employee_Id  '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId where OT.isRequest=1 and OT.isDelete=0 '
	if(@EmployeeFirstName<>'')  
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName +'' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeFirstName+'%' as nvarchar(100)) + ''')'
		End
	if(@EmployeeId<> '')  
		Begin
			set @sqlQuery = @sqlQuery + ' and e.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(50)) + ''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and e.Employee_ID IN (select * from #EmployeeIds) '  
            END
	If not(@fromdate = '01/01/1900' and @ToDate = '01/01/1900')
		begin
			set @sqlQuery= @sqlQuery + ' and OT.Date>=CONVERT(DATETIME,'''+cast(@fromdate as nvarchar(50))+''',102) '  
			set @sqlQuery= @sqlQuery + ' and OT.Date<=CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''',102) '  
		end
	set @sqlQuery= @sqlQuery + ' order by OT.ExtraTime_Id desc'
	--print @sqlQuery
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListingByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  Karthikeyan.R
-- Create date: 08-Feb-2017
-- Description: <Description,,>  
-- Proc_TA_CompensationListing null,null,'01/01/1900','01/01/1900','Superadmin',0
 -- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CompensationListingByEmpId]  
@Employee_Id int,
@GradeLevel varchar(20),
@fromdate datetime = '01/01/1900', 
@ToDate datetime = '01/01/1900',
@UserGroupName varchar(250),
@ParentId int
AS  
BEGIN
	SET NOCOUNT ON;  
	Declare @sqlQuery nvarchar(Max)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	declare @ELTodate as datetime
	if(@ToDate='01/01/1900')
	begin
		set @ELTodate=getdate()
	end
	else
	begin
		set @ELTodate=@ToDate
	end
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	 SET @sqlEmpLevel=
      'INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
      from  (
      SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
      from TA_Tbl_EmployeeLevel el
      INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
      INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId '
      set @sqlEmpLevel= @sqlEmpLevel +' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
      INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ELTodate as nVARCHAR(50))+''', 102) and EL.LevelId is not null'      
	EXECUTE(@sqlEmpLevel)
	set @sqlQuery=''  
	set @sqlQuery='select OT.ExtraTime_Id ''Compensation_Id'',E.Employee_Code_Id as ''Employee_ID'',E.Employee_FirstName + '' ''+ isnull(E.Employee_LastName,'''') as Employee_FirstName ,
	case when '+CONVERT(varchar,@dateFormat)+' =106 then
		REPLACE(CONVERT(VARCHAR, OT.ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
	else CONVERT(VARCHAR, OT.ApplicationDate, '+CONVERT(varchar,@dateFormat)+') end as ApplicationDate,
	case when '+CONVERT(varchar,@dateFormat)+' =106 then
		REPLACE(CONVERT(VARCHAR, OT.Date,'+CONVERT(varchar,@dateFormat) + '),'' '',''-'') 
	else CONVERT(VARCHAR, OT.Date, '+CONVERT(varchar,@dateFormat)+') end as FromDate,'''' Type,OT.Reason,OT.OverTimeStatus ''Status'',case	when OT.InTime<>''00:00'' then	case	when ('''+CONVERT(varchar,@TimeFormat)+ ''') =''hh:mm'' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.InTime,0)), 114)
															else	SUBSTRING(OT.InTime,13,5)+'' '' + SUBSTRING(OT.InTime,18,2) 
													end 
						else ''''
				end	InTime
	,
	case	when OT.OutTime<>''00:00'' then	case	when ('''+CONVERT(varchar,@TimeFormat)+ ''') =''hh:mm'' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.OutTime,0)), 114)
															else SUBSTRING(OT.OutTime,13,5)+'' '' + SUBSTRING(OT.OutTime,18,2)
													end 
						else ''''
				end	OutTime,OT.HrsExtra ''WorkedHours'',OT.DaysWorked ''DayWorked'',OT.OverTimeStatus ''Comp_Status'',Ta_Tbl_levelDetails.name as LevelName
	from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on OT.Employee_Id=E.Employee_Id 
	INNER JOIN TA_Tbl_EmployeeDesignation ON E.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId 
	INNER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId where OT.isRequest=1 and OT.isDelete=0 and E.Employee_Id = ''' + cast(@Employee_Id as nvarchar(100))  + ''' AND TA_Tbl_Grade.Grade_Level >=' + cast(@GradeLevel as nvarchar(100))  
	If not(@fromdate = '01/01/1900' and @ToDate = '01/01/1900')
		begin
			set @sqlQuery= @sqlQuery + ' and OT.Date>=CONVERT(DATETIME,'''+cast(@fromdate as nvarchar(50))+''',102) '  
			set @sqlQuery= @sqlQuery + ' and OT.Date<=CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''',102) '  
		end
	set @sqlQuery= @sqlQuery + '  order by OT.ExtraTime_Id desc'
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompOffCalculation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <27-Dec-2012>
-- Description:	<Comp off Calculation>
-- Proc_TA_CompOffCalculation '01/Jan/2012','22/Jan/2013','',0,'','0,3',0,0,'SuperAdmin','0','All','',0,0,'Both','CompOff'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CompOffCalculation]
(
	-- Add the parameters for the stored procedure here
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @SanctionType varchar(25)
 )   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  --Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--select * from #LevelRights
CREATE TABLE #TempProcessedData
(
	[Employee_Code_Id] nvarchar(20),
	[Date] datetime,
	[Shift_Id] int,
	[HrsWork] nvarchar(10),
	[HrsOT] nvarchar(10),
	[NormOT] nvarchar(10),
	[WorkHrs] nvarchar(10),
	[HrsExtra] nvarchar(10),
	[ExtraMins] float,
	[OtMins] float,
	[OvertimeStatus] nvarchar(50),
	[Status] nvarchar(50),
	[HrsCompOff] nvarchar(20),
	[CompOffMins] int
)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
insert into #TempProcessedData
select PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.WorkHrs,PD.HrsExtra,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.Status,HrsCompOff,CompoffMins
from TA_Tbl_ProcessedData as PD 
inner join ta_tbl_employee e on e.SwipeCardNo=PD.Employee_Code_Id
inner join #EmpLevel el on el.employeeid=e.employee_id
where
(PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)) and compoffMins<>0
--select * from #TempProcessedData 
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + ' select * from ('
	set @sqlQuery = @sqlQuery + ' select TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,'
	set @sqlQuery = @sqlQuery + ' case LP.OtHourWise when ''0'' then case LP.OtDayWise when ''1'' then ''Day wise :(HD-'' + isnull(LP.OtMinHrs,''00:00'') + '' Hrs,FD-'' + isnull(LP.FullDayCompOffHrs,''00:00'') +'' Hrs)'' else ''Not Defined'' end when ''1'' then ''Hour wise : (HD-'' + isnull(LP.OtMinHrs,''00:00'') + '' Hrs,FD-'' + isnull(LP.FullDayCompOffHrs,''00:00'') + '' Hrs)'' else ''Not Defined'' end as CompOffHourDayWise,'
	set @sqlQuery = @sqlQuery + ' LP.OtHourWise,LP.OtDayWise,LP.OtMinHrs,DATEPART(hh,LP.OtMinHrs) * 60 + DATEPART(MI,LP.OtMinHrs) as OTHRsMins,
	LP.FullDayCompOffHrs,DATEPART(hh,LP.FullDayCompOffHrs) * 60 + DATEPART(MI,LP.FullDayCompOffHrs) as CompOffHrMins,
	ISNULL(ta_tbl_shift.Shift_ShortName,''Off'') as ShiftName, isnull(ta_tbl_shift.Shift_TotalWorkingHours,''00:00'') as DefinedWorkingHours,#TempProcessedData.OtMins,'
	set @sqlQuery = @sqlQuery + ' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],ISNULL(#TempProcessedData.OverTimeStatus,''Pending'') as OverTimeStatus,0 as SelectedRecords,Ta_Tbl_Employee.SwipeCardNo,replace(Ta_tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender,0 as compoffDays,#TempProcessedData.HrsCompOff,#TempProcessedData.CompOffMins from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo'
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'	 
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on  #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join TA_Tbl_Emp_LeavePolicy ELP on ELP.EmployeeId=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELP.LeavePolicy_Id '
	--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.employeeid=TA_Tbl_Employee.Employee_Id '
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
	--set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	--set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' where #TempProcessedData.compoffMins <> 0  '
	if(@SanctionType = 'CompOff')
		begin
			set @sqlQuery = @sqlQuery + 'AND Ta_Tbl_Employee.CompOff_Eligible=1 '
		end
	ELSE if(@SanctionType = 'OverTime')
		begin
			set @sqlQuery = @sqlQuery + 'AND Ta_Tbl_Employee.OT_Eligible=1 '
		end
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end
	if(@shift<>0) 
	begin
		set @sqlQuery = @sqlQuery + ' And #TempProcessedData.Shift_Id=' + cast (@shift as nvarchar(50))  
	end 
	set @sqlQuery = @sqlQuery + ' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1'
	if not(@EmployeeName='')
	begin
		--set @sqlQuery = @sqlQuery + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End 
	if not (@empId='')
	begin
		set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
	end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
	 if(@Gender<>'Both')
		begin
		   set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not(@status='' or @status='All')
	begin
	 	IF(@status = 'Pending')
			BEGIN
				set @sqlQuery = @sqlQuery + ' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = ''' + @status + ''')'
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + ' AND #TempProcessedData.OvertimeStatus = ''' + @status + ''''
			END
    end 
	set @sqlQuery = @sqlQuery + ' ) OverTime order by OverTime.Employee_Code_Id , OverTime.Date'
create table #tempHourwise(Employee_code_Id varchar(50),date datetime,shift_Id int,CompOffHourDaywise varchar(50),OtHourWise int,
OtDayWise int,OtMinsHrs varchar(25),OTHRsMins int,FullDayCompOffHrs varchar(25),FullDayCompOffMins int,ShiftName varchar(50),
DefinedworkingHours varchar(20),otMins int,HrsWork varchar(50),HrsOT varchar(20),
Employee_FirstName varchar(100),LevelName varchar(50),OverTimeStatus varchar(20),
SelectedRecords int,SwipeCardNo varchar(50),TitleName varchar(25),Gender varchar(10),compOffDays1 float,HrsCompOff varchar(50),CompOffMins int)
insert into #tempHourwise
exec (@sqlQuery)
--select * from #tempHourwise
update #tempHourwise set compOffDays1= case when CompOffMins >= FullDayCompOffMins then 1 when CompOffMins >= OTHRsMins then 0.5 else 0 end 
where  OtDayWise=1 and OverTimeStatus='Approved'
--select * from #tempHourwise
update #tempHourwise set compOffDays1= A.compOffDays from 
(select sum(compOffDays1) as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtDayWise=1 and OverTimeStatus='Approved' 
group by Employee_code_Id,shift_Id) as A
inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
--update #tempHourwise set compOffDays1= A.compOffDays from 
--(select (SUM(CompOffMins)/FullDayCompOffMins) + case  when ((SUM(CompOffMins)%FullDayCompOffMins)/OTHRsMins) >= 1 then 0.5 else 0 end as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtHourWise=1 and OverTimeStatus='Approved' group by
--Employee_code_Id,OTHRsMins,shift_Id,FullDayCompOffMins) as A 
--inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
update #tempHourwise set compOffDays1= A.compOffDays from 
(select (cast((SUM(CompOffMins)/OTHRsMins) as float)/2) as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtHourWise=1 and OverTimeStatus='Approved' group by
Employee_code_Id,OTHRsMins,shift_Id,FullDayCompOffMins) as A 
inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
select * from #tempHourwise
--insert into #tempDaywise
--select * from #tempHourwise  where OtDayWise=1
--delete from #tempHourwise where OtDayWise=1
--insert into #tempNOHourDaywise
--select * from #tempHourwise  where OTHRsMins=''
--insert into #tempFinalCompOff
--select * from #tempNOHourDaywise
--	union all
--select COUNT(Employee_code_Id) as compOffDays,Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender from #tempDaywise group by
--Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender having otMins >= OTHRsMins
--	union all
--select SUM(otMins)/OTHRsMins as compOffDays,Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender from #tempHourwise where CompOffHourDaywise <> ''
--group by
--Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender
--update #tempFinalCompOff set compOffDays1=0 where CompOffHourDaywise = ''
--select * from #tempFinalCompOff
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
drop table #tempHourwise
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ConveyancePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Maria Prasanth>
-- Create date: <25-Nov-2022>
-- Description:	<This Procedure has to create Conveyance allowance Policy Procedure>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ConveyancePolicy]
	-- Add the parameters for the stored procedure here
	@tag varchar(20),
	@companyID int=null,
	@Employee_Id INT=null,
	@EmployeeCategory INT=null,
	@EmployeeType INT=null,
	@Gender nvarchar(10)=null,
	@CAPolicyName varchar(20)=null,
	@CAType	nvarchar(20)=null,
	@CAPolicyid int=null,
	@CAFixAmount bigint=null,
	@CAPercentage float=null,
	@CAAmount bigint=null,
	@LevelID int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here Amount
	if(@tag='I')
	Begin
		Insert Into TA_Tbl_ConveyanceAllowance (ConPolicyName,Con_type,conAmount,conPercentage,LimitAmount,CompanyId,EmployeeCategory,EmployeeType,Gender,Created_BY,Created_Date,Modify_Date) 
		Values(@CAPolicyName,@CAType,@CAAmount,@CAPercentage,@CAFixAmount,@companyID,@EmployeeCategory,@EmployeeType,@Gender,@Employee_Id,GETDATE(),null) 
	End
	Else if(@tag='policyName')
	Begin
		Select ConPolicyName From TA_Tbl_ConveyanceAllowance where ConPolicyName=@CAPolicyName
	End
	else if(@tag='U')
	Begin
		Update TA_Tbl_ConveyanceAllowance set ConPolicyName=@CAPolicyName,Con_type=@CAType,conAmount=@CAAmount,conPercentage=@CAPercentage,LimitAmount=@CAFixAmount,CompanyId=@companyID,EmployeeCategory=@EmployeeCategory,EmployeeType=@EmployeeType,Gender=@Gender,Modify_Date=getDate()  where C_Id=@CAPolicyid
	End
	Else if(@tag='D')
	Begin
		if(@CAPolicyid!=' ')
		begin
			Delete From TA_Tbl_ConveyanceAllowance where C_Id=@CAPolicyid
			select '1' as D_count
		End
		else
		begin
			select '0' as D_count
		end
	End
	else if(@tag='S')
	Begin
		If (isNull(@CAPolicyid,0)=0)
		Begin
			Select ConPolicyName,C_Id,1 as flag From TA_Tbl_ConveyanceAllowance where CompanyId=dbo.Func_TA_GetParentIds(@LevelID)
		End
		Else
		Begin
			Select conPolicyName,C_Id,ConAmount,conPercentage,LimitAmount,CompanyId,Gender,EmployeeCategory,EmployeeType  From TA_Tbl_ConveyanceAllowance where C_Id=@CAPolicyid
		End
	End

	else if(@tag='SL')
	begin
		Select ConPolicyName,C_Id,1 as flag From TA_Tbl_ConveyanceAllowance
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CounShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_Ta_CounShift] (@ShiftId int)
AS
	BEGIN
		SELECT COUNT(*) FROM TA_Tbl_Shift where Shift_Id=@ShiftId and Isdeleted=1
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGlobalHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CountGlobalHoliday  
Description : counting global holiday
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CountGlobalHoliday]  
AS  
BEGIN
	select SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1) as 'Days' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type='G' and h.Isdeleted=0  and ys.IsActive=1
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGrade]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : Proc_TA_CountGrade    
Description : counting total grade   
Tables Included : ta_tbl_Title    
Created By : Arun  Vinoth
Created On : 30-Jul-07  
Modified By :  
Modified On :*/  
CREATE procedure [dbo].[Proc_TA_CountGrade]
(@Grade INT)
as
Select count(*) from ta_tbl_Title where GradeID=@Grade-- And Isdeleted=0
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountTitle]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : [Proc_TA_CountTitle]    
Description : counting total title   
Tables Included : TA_tbl_Employee    
Created By : Arun vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE  procedure [dbo].[Proc_TA_CountTitle]
(@Title INT)
as
--select count(*) from TA_tbl_Employee where Designation_Id=@Title and isdeleted=0
select count(*) from TA_tbl_EmployeeDesignation where DesignationID=@Title
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CountTotInAndOutPunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 14:24PM>
-- Description:	<Count the total number of in and out punches>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CountTotInAndOutPunches]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(50),
	@strOutDateTime varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Count(*) AS Count FROM TA_Tbl_ClockDetails 
	WHERE (Clk_InDate+Clk_InTime) > cast(@strOutDateTime as datetime) AND (Clk_InDate+Clk_InTime) < cast(@strOutDateTime as datetime) 
	AND Clk_EmpId = @inClk_EmpId  AND Clk_OutDate IS NULL AND IsVoid = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountYearlyHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_CountYearlyHoliday  
Description : counting total yearly holiday 
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CountYearlyHoliday]  
AS
BEGIN  
	select SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1) as 'Days' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type='Y' and h.Isdeleted=0  and ys.IsActive=1
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateTrigger]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Senthil Kumar NP
-- Create date: 04.Jan.08
-- Description:	creating trigger dynamically for specified tables and fields
--<Description,,> Proc_TA_CreateTrigger 'TA_Tbl_Entrance','Entrance_Name,Entrance_Description','Entrance_Description','Entrance_Description'
--Proc_TA_CreateTrigger 'TA_Tbl_NewsEvents','NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id','LeftNewsEvent,RightNewsEvent','NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent'
--Proc_TA_CreateTrigger 'TA_Tbl_NewsEvents','NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id','NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id','NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id'
--	Modified By		:	Manjula.P
--	Modified On		:	05-Sep-2013
--	Descriptions	:	Adding if(@NewId is not null and @NewId<>'''') Condition in dynamiz query for checking whether the Identity value is null or not :
--					:	To avoid insert statement fails error while importing a file when checking audit trail 
--					:	2.to avoiding the subquery returns more than one value error when enabling audit trail Changing in Dynamic query
--					:	  For Inser Trigger
--					:	Proc_TA_CreateTrigger 'TA_Tbl_Terminal', 'Terminal_ReaderID,Terminal_Name', 'Terminal_ReaderID,Terminal_Name', 'Terminal_ReaderID,Terminal_Name'
--	Modified By		:	K.Gopinath
--	Modified On		:	03-Jan-2014 & 10-Jan-2014
--	Descriptions	:	To avoid redudant data while inserting operation in Audit Trial and Fieldsizes of inserting data and added query for check employeeID
--	Proc_TA_CreateTrigger 'TA_Tbl_EmployeeShiftId_ForShiftReAllocation','EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift','EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift','EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CreateTrigger]
	@tableName as nvarchar(100),
	--@fieldName as nvarchar(3000),	
	@InsertFields as nvarchar(3000)=null,
	@UpdateFields as nvarchar(3000)=null,
	@DeleteFields as nvarchar(3000)=null
AS
BEGIN
	declare @sql as varchar(8000)
	declare @sql1 as varchar(8000)
	declare @triggerName as nvarchar(100)
	declare @idColumn as nvarchar(50)
	declare @concat as nvarchar(100)
	declare @pos as int
	declare @flag as int
	declare @tableId as int
	declare @fieldId as int
	set @idColumn = ''
	set @idColumn = (select name from syscolumns where colstat=1 and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
	set @sql1=''
	set @sql =''
--Delete Insert Trigger
	set @triggerName = 'InsertTrig' + @tableName  
	set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @triggerName + ' ]'') and OBJECTPROPERTY(id, N''IsTrigger'') = 1)'
	set @sql = @sql + ' drop trigger [dbo].[' + @triggerName + ']'
	exec(@sql)
--Delete Update Trigger
	set @triggerName = 'UpdateTrig' + @tableName  
	set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @triggerName + ' ]'') and OBJECTPROPERTY(id, N''IsTrigger'') = 1)'
	set @sql = @sql + ' drop trigger [dbo].[' + @triggerName + ']'
	exec(@sql)
--Delete Delete Trigger
	set @triggerName = 'DeleteTrig' + @tableName  
	set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @triggerName + ' ]'') and OBJECTPROPERTY(id, N''IsTrigger'') = 1)'
	set @sql = @sql + ' drop trigger [dbo].[' + @triggerName + ']'
	exec(@sql)
	set @tableId = (select TableID from ta_tbl_AuditTable where TableName=@tableName)	
--set Employee Id
declare @empCount as int
declare @empField as nvarchar(25)
set @empField = ''
set @empCount =0
set @empCount = (select count(*) as tot from syscolumns where name='emp_id' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
if (@empCount>0)
	Begin
		set @empField = 'emp_id'
	End
Else
	Begin
		set @empCount = (select count(*) as tot from syscolumns where name='empid' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
		if (@empCount>0)
			Begin
				set @empField = 'empid'
			End
-- Added by Gopinath for Check field as name='employeeid' on Jan10th
		Else
		Begin
			set @empCount = (select count(*) as tot from syscolumns where name='employeeid' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
            if (@empCount>0)
				Begin
					set @empField = 'employeeid'
				End
			Else
			-- Added by Gopinath for Check field as name='EmployeeAutoId' on April14th
			Begin
			set @empCount = (select count(*) as tot from syscolumns where name='EmployeeAutoId' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
            if (@empCount>0)
				Begin
					set @empField = 'EmployeeAutoId'
				End
		End
		End
	End
--set @empField = 'emp_id'
--set @empCount = (select count(*) as tot from syscolumns where name='employee_id' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
--if (@empCount>0)
--	Begin
--		set @empField = 'employee_id'
--	End
--Else
--	Begin
--		set @empCount = (select count(*) as tot from syscolumns where name='employeeid' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
--		if (@empCount>0)
--			Begin
--				set @empField = 'employeeid'
--			End
--		Else
--			Begin
--					set @empCount = (select count(*) as tot from syscolumns where name='empid' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
--					if (@empCount>0)
--						Begin
--							set @empField = 'empid'
--						End
--					Else
--						Begin
--							set @empCount = (select count(*) as tot from syscolumns where name='emp_id' and id=(select id from sysobjects WHERE xtype='U' and name = @tableName ))
--							if (@empCount>0)
--								Begin
--									set @empField = 'emp_id'
--								End
--							Else
--								Begin
--									set @empField=''
--								End
--						End
--			End
--	End
--End of set Employee Id
	if (@InsertFields Is not null and @InsertFields != '')
	Begin
	--create Insert Trigger	
		set @triggerName = 'InsertTrig' + @tableName		
		set @sql = ' CREATE TRIGGER ' + @triggerName + ' ON '+ @tableName
		set @sql = @sql + ' FOR INSERT AS '
		--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
		--set @sql = @sql + ' DECLARE @newValue as nVARCHAR(3000)'
		--set @sql = @sql + ' DECLARE @newId as int'
		--set @sql = @sql + ' DECLARE @employeeId as int'
		--set @sql = @sql + ' SELECT @newId = (SELECT ' + @idColumn + ' FROM Inserted)'	
		if (@InsertFields is null or @InsertFields='')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX(',',@InsertFields)
				if (@pos=0)
					Begin
						select @concat = @InsertFields
						set @InsertFields=''
					End
				else
					Begin
						select @concat = substring(@InsertFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
				--set @sql1 = @sql1 + ' SELECT @newValue = (SELECT '+ @concat +' FROM Inserted)'		
				if (@empField !='')
					Begin
						--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
						--set @sql1 = @sql1 + ' SELECT @employeeId = (SELECT '+ @empField +' FROM Inserted)'
						--set @sql1 = @sql1 + ' if(@NewId is not null and @NewId<>'''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr,EmployeeID) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@newValue,''Insert'',@employeeId)'
						--Adding By Manjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail 
						set @sql1=@sql1+' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr,EmployeeID) select '+ cast(@tableID as nvarchar(50)) +',' + cast(@FieldID as nvarchar(50)) + ',' + cast(@idColumn as nvarchar(50)) + ',' + cast(@concat as nvarchar(50)) + ',''Insert'',' + cast(@empField as nvarchar(50)) + ' from inserted '
						-- Commented By K.Gopinath on 03-Jan-2014 To avoid redudant data while inserting operation in Audit Trial
						-- I left join TA_Tbl_AuditOperation A on A.RecordID='+ cast(@idColumn as nvarchar(25))
					End
				Else
					Begin
						--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
						--set @sql1 = @sql1 + ' if(@NewId is not null and @NewId<>'''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@newValue,''Insert'')'
						--Adding By Manjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail 
						set @sql1=@sql1+' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr) select '+ cast(@tableID as nvarchar(50)) +',' + cast(@FieldID as nvarchar(50)) + ',' + cast(@idColumn as nvarchar(50)) + ',' + cast(@concat as nvarchar(50)) + ',''Insert'' from inserted '
						-- Commented By K.Gopinath on 03-Jan-2014 To avoid redudant data while inserting operation in Audit Trial
						--I left join TA_Tbl_AuditOperation A on A.RecordID='+ cast(@idColumn as nvarchar(25))
					End
				set @InsertFields = substring(@InsertFields,@pos+1,len(@InsertFields))
				if (@InsertFields is null or @InsertFields='')
					set @flag=0
				else
					set @flag=1			
			End		
		exec(@sql + ' ' + @sql1 )
	End
	if (@UpdateFields Is not null and @UpdateFields != '')
	Begin
	--create Update Trigger
		set @sql=''
		set @sql1=''
		declare @sql2 as varchar(8000)
		set @sql2=''
		set @triggerName = 'UpdateTrig' + @tableName
		set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @triggerName + ' ]'') and OBJECTPROPERTY(id, N''IsTrigger'') = 1)'
		set @sql = @sql + ' drop trigger [dbo].[' + @triggerName + ']'
		exec(@sql)
		set @sql = ' CREATE TRIGGER ' + @triggerName + ' ON '+ @tableName
		set @sql = @sql + ' FOR Update AS '
		set @sql = @sql + ' DECLARE @newValue as nVARCHAR(3000)'
		set @sql = @sql + ' DECLARE @oldValue as nVARCHAR(3000)'
		set @sql = @sql + ' DECLARE @newId as int'
		set @sql = @sql + ' DECLARE @employeeId as int'
		--set @sql = @sql + ' SELECT @newId = (SELECT ' + @idColumn + ' FROM Inserted)'
		if (@UpdateFields is null or @UpdateFields='')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX(',',@UpdateFields)
				if (@pos=0)
					Begin
						select @concat = @UpdateFields
						set @UpdateFields=''
					End
				else
					Begin
						select @concat = substring(@UpdateFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				set @sql2= ''
				--set @sql2 = @sql2 + ' SELECT @oldValue = (SELECT '+ @concat +' FROM Deleted)'
				--set @sql2 = @sql2 + ' SELECT @newValue = (SELECT '+ @concat +' FROM Inserted)'
				if (@empField !='')
					Begin
						set @sql2 = @sql2 + ' SELECT @employeeId = (SELECT distinct '+ @empField +' FROM Inserted)'
						--set @sql2 = @sql2 + ' if (@oldValue <> @newValue)'
						--set @sql2 = @sql2 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@oldValue,@newValue,''Update'',@employeeId)'
						set @sql2 = @sql2 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID)  select '+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',b.' + @idColumn + ', a.' + @concat + ',b.' + @concat + ',''Update'',@employeeId from Deleted a, Inserted b'
					End
				Else
					Begin
						--set @sql2 = @sql2 + ' if (@oldValue <> @newValue)'
						set @sql2 = @sql2 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',b.' + @idColumn + ',@oldValue,@newValue,''Update'')'
					End
				set @UpdateFields = substring(@UpdateFields,@pos+1,len(@UpdateFields))
				if (@UpdateFields is null or @UpdateFields='')
					set @flag=0
				else
					set @flag=1	
				set @sql1 = @sql1 + @sql2
			End			
		exec(@sql + ' ' + @sql1)
	End
	if (@DeleteFields Is not null and @DeleteFields != '')
	Begin
	--create Delete Trigger
		set @sql=''
		set @sql1=''
		declare @sql3 as varchar(8000)
		set @sql3=''
		set @triggerName = 'DeleteTrig' + @tableName 		
		set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[' + @triggerName + ' ]'') and OBJECTPROPERTY(id, N''IsTrigger'') = 1)'
		set @sql = @sql + ' drop trigger [dbo].[' + @triggerName + ']'
		exec(@sql)
		set @sql = ' CREATE TRIGGER ' + @triggerName + ' ON '+ @tableName
		set @sql = @sql + ' FOR Delete AS '		
		set @sql = @sql + ' DECLARE @oldValue as nVARCHAR(3000)'
		set @sql = @sql + ' DECLARE @newId as int'
		set @sql = @sql + ' DECLARE @employeeId as int'
		if (@DeleteFields is null or @DeleteFields='')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX(',',@DeleteFields)
				if (@pos=0)
					Begin
						select @concat = @DeleteFields
						set @DeleteFields=''
					End
				else
					Begin
						select @concat = substring(@DeleteFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				set @sql3 = ''
				--set @sql3 = @sql3 + ' SELECT @newId = (SELECT ' + @idColumn + ' FROM Deleted)'
				--set @sql3 = @sql3 + ' SELECT @oldValue = (SELECT ['+ @concat +'] FROM Deleted)'				
				if (@empField !='')
					Begin
						set @sql3 = @sql3 + ' SELECT @employeeId = (SELECT distinct '+ @empField +' FROM Deleted)'
						--set @sql3 = @sql3 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr,EmployeeID) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@oldValue,''Delete'',@employeeId)'
--						set @sql2 = @sql2 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID)  select '+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',b.' + @idColumn + ', a.' + @concat + ',b.' + @concat + ',''Update'',@employeeId from Deleted a, Inserted b'
						set @sql3 = @sql3 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr,EmployeeID)           select '+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',' + @idColumn + ','+ @concat+ ',''Delete'',@employeeId from Deleted'
					End
				Else
					Begin
						--set @sql3 = @sql3 + ' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@oldValue,''Delete'')'
						set @sql3 = @sql3 + 'if(@NewId is not null and @NewId<>'''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr) values ('+ cast(@tableID as nvarchar(25)) +',' + cast(@FieldID as nvarchar(25)) + ',@NewId,@oldValue,''Delete'')'
					End
				set @DeleteFields = substring(@DeleteFields,@pos+1,len(@DeleteFields))
				if (@DeleteFields is null or @DeleteFields='')
					set @flag=0
				else
					set @flag=1			
			set @sql1 = @sql1 + @sql3
			End				
			exec(@sql + ' ' + @sql1 )
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	06-SEP-2013
-- Description	:	Import the Employees
--	Modified By		:	Manjula.P
--	Modified On		:	15-Jan-14
--	Descriptinos	:	Adding this and ISNULL(TLD.LevelName,'')!='' condition to avoiding empty value that saved in levelname in level details tble
--						this issue was occurs when child level name is empty via import master
--Modified By		:	A.K.T.MOORTHI
--Date Of Modified	:	07-Apr-2014
--Description			:	Update IsDeleted = 1, InActiveDate = DateOfJoinDate, Employee_Status = 0, Report_Exclude = 1 When Employee Count Greater Then 5, Bze User Can Able To Create N Number Of User.
--								But They Can Access Only 5 Employee For Hole Application.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]
	@ApplnMode BIT
AS
BEGIN
	-- Update the LevelId with First Parent Level  
	UPDATE TA_Tbl_ImportMasterData SET ChildLevelId = Level1_Id  
-- Insert the Lower Child Level Id from Import Master Data Table into the Employee Level Table for each employee  
	DECLARE @LevelId INT, @LevelCount INT, @Inc INT
	DECLARE @Query nvarchar(MAX)
	DECLARE @TempLevel TABLE(Id INT IDENTITY(1, 1), LevelId INT)
	DECLARE @TempLevelDetails TABLE(LevelName nvarchar(MAX), LevelId INT, ParentId INT)
	INSERT INTO @TempLevel
		SELECT levelID FROM TA_Tbl_Level L WHERE L.isDeleted = 0 ORDER BY parentLevelID
	SELECT @LevelCount = COUNT(levelID) FROM TA_Tbl_Level L WHERE L.isDeleted = 0
	SET @Inc = 2
	WHILE(@LevelCount>=@Inc)
	BEGIN
		SELECT @LevelId = LevelId FROM @TempLevel WHERE Id = @Inc
		SET @Query = 'SELECT DISTINCT Level' + CAST(@Inc AS nvarchar(10)) + ', ' + CAST(@LevelId AS nvarchar(10)) + ', Level' + CAST(@Inc-1 AS nvarchar(10)) + '_Id FROM Ta_Tbl_ImportMasterData IMD '
		SET @Query = @Query + 'LEFT JOIN Ta_Tbl_levelDetails LD ON LD.parentId = IMD.Level' + CAST(@Inc-1 AS nvarchar(10)) + '_Id AND LD.name = IMD.Level' + CAST(@Inc AS nvarchar(10)) + ' AND LD.LevelId = ' + CAST(@LevelId AS nvarchar(10)) + ' '
		SET @Query = @Query + 'WHERE IMD.Level' + CAST(@Inc AS nvarchar(10)) + '_Id IS NULL  AND LD.LevelId IS NULL'
		INSERT INTO @TempLevelDetails
			EXEC(@Query)
		--Adding this and ISNULL(TLD.LevelName,'')!='' condition to avoiding empty value that saved in levelname in level details tble
		-- this issue was occurs when child level name is empty via import master
		INSERT INTO Ta_Tbl_levelDetails(levelId, parentId, name, [description])
			SELECT TLD.LevelId, TLD.ParentId, TLD.LevelName, TLD.LevelName FROM @TempLevelDetails TLD		
				WHERE TLD.LevelName NOT IN (SELECT TL.LevelName FROM @TempLevelDetails TL 
				INNER JOIN Ta_Tbl_levelDetails LD ON LD.name = TL.LevelName AND LD.parentId = TL.ParentId AND TLD.LevelId != @Inc  ) and ISNULL(TLD.LevelName,'')!=''
		SET @Query = 'UPDATE Ta_Tbl_ImportMasterData SET Level' + CAST(@Inc AS nvarchar(10)) + '_Id = LD.id FROM Ta_Tbl_ImportMasterData IMD '
		SET @Query = @Query + 'INNER JOIN Ta_Tbl_levelDetails LD ON LD.parentId = IMD.Level' + CAST(@Inc-1 AS nvarchar(10)) + '_Id AND LD.name = IMD.Level' + CAST(@Inc AS nvarchar(10))
		EXEC(@Query)
		DELETE FROM @TempLevelDetails
		SET @Inc = @Inc + 1
	END
	INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId, LevelId, EffectiveDate)
		SELECT 
			Emp.Employee_Id,
			(CASE
				WHEN IMD.Level10_Id IS NOT NULL THEN IMD.Level10_Id 
				WHEN IMD.Level9_Id IS NOT NULL THEN IMD.Level9_Id 
				WHEN IMD.Level8_Id IS NOT NULL THEN IMD.Level8_Id 
				WHEN IMD.Level7_Id IS NOT NULL THEN IMD.Level7_Id 
				WHEN IMD.Level6_Id IS NOT NULL THEN IMD.Level6_Id 
				WHEN IMD.Level5_Id IS NOT NULL THEN IMD.Level5_Id 
				WHEN IMD.Level4_Id IS NOT NULL THEN IMD.Level4_Id 
				WHEN IMD.Level3_Id IS NOT NULL THEN IMD.Level3_Id 
				WHEN IMD.Level2_Id IS NOT NULL THEN IMD.Level2_Id 
				WHEN IMD.Level1_Id IS NOT NULL THEN IMD.Level1_Id
				ELSE IMD.ChildLevelId END
			),
			IMD.DateOfJoining FROM Ta_Tbl_ImportMasterData IMD
			INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Code_Id = IMD.Employee_Code
		WHERE Emp.Employee_Id NOT IN (SELECT EmployeeId FROM TA_Tbl_EmployeeLevel)	
		--Added by Manjula.P on 30-Jan-2014 for inserting dummy values to yearclosure when the employee is imported
		create table #temp_Employee
		(
		Employee_Id int,
		LeaveTypeId int,
		MaxValue decimal(18,1),
		LevelId int,
		YearSettingsId int
		)
		--insert into #temp_Employee
		--select e.Employee_Id,LT.LeaveType_Id,0,EL.LevelId,(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1) from TA_Tbl_Employee e
		--cross join TA_Tbl_LeaveType LT
		--inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=e.Employee_Id
		--where e.Employee_Id not in (select Y.Employee_Id from TA_Tbl_YearClosure Y)
		--and Employee_Code_Id<>'18000000' and Employee_Status=1 and e.Isdeleted=0 and LT.IsDeleted=0
		--insert into TA_Tbl_YearClosure (Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID) 
		--select YearSettingsId,LevelId,Employee_Id,LeaveTypeId,MaxValue,MaxValue,Employee_Id from #temp_Employee
		--drop table #temp_Employee
		--**********************************************************************************************************
	DELETE Ta_Tbl_ImportMasterData FROM Ta_Tbl_ImportMasterData IMD
	INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Code_Id = IMD.Employee_Code
	--Added by Manikandan.R
	--On 05-02-2014 05.22PM
	declare @groupId as bigint
	set @groupId=(select GroupId from ta_tbl_usergroup where groupName='SuperAdmin')
	insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) 
	select @groupId,id,1 from Ta_Tbl_levelDetails where id not in(select levelId from TA_Tbl_LevelRights where @groupId=@groupId)
	--select * from TA_Tbl_LevelRights order by GroupId,LevelId 
	IF(@ApplnMode = 0)
	BEGIN
		/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
		UPDATE TA_Tbl_Employee SET
			Isdeleted = 1
			--,
			--Report_Exclude = 1
			--Employee_Status = 0,
			--InActiveDate = DATEADD(D, 1, DateOfJoining)
		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> '18000000') AND
			Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
		/* End */
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DashBoardAnalysisbyDepartment]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*	
Proc_TA_RptEmployeeInOutSummary @EmployeeId='',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',
@UserGroupName='superadmin',@GradeLevel='1',@EmpSwipeCard='',@ParentId=0,@Fromdate1='2022/11/01',@Todate1='2022/11/30',@DesignationID=0,@Gender='Both',@EmpAutoID=1


exec Proc_TA_RptEmployeeInOutSummary @DesignationID=N'0',@ToDate1=N'2024/02/05 00:00:00',@Gender=N'Both',
@EmployeeId=N'BB002',@EmpAutoId=N'0',@ParentId=N'37',@FromDate1=N'2024/02/05 00:00:00',@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@LevelID=N'37',@employeeType=N'0',@employeeCategory=N'0',@EmployeeName=N''

exec Proc_TA_DashBoardAnalysisbyDepartment @LevelID=N'0',
@ParentId=0,@Fromdate1=N'01/July/2024',@Todate1=N'04/July/2024'

*/
CREATE PROCEDURE [dbo].[Proc_TA_DashBoardAnalysisbyDepartment] 
	
	@LevelID NVARCHAR(1000), 	 
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50)
	
AS
BEGIN
	SET NOCOUNT ON;


	declare  @EmployeeId NVARCHAR(50)='',
	@EmployeeName NVARCHAR(50)='', 
	@employeeCategory NVARCHAR(50)='0',
	@employeeType NVARCHAR(50)='0'	,
	@UserGroupName NVARCHAR(250)='SuperAdmin',
	@GradeLevel NVARCHAR(20)='0'	,
	@EmpSwipeCard NVARCHAR(20)='',
	@DesignationID INT =0,
	@Gender NVARCHAR(10)='Both',
	@EmpAutoID INT =''


	--@EmployeeId NVARCHAR(50),
	--@EmployeeName NVARCHAR(50),  
	--@LevelID NVARCHAR(1000), 	 
	--@employeeCategory NVARCHAR(50),
	--@employeeType NVARCHAR(50)	,
	--@UserGroupName NVARCHAR(250),
	--@GradeLevel NVARCHAR(20)	,
	--@EmpSwipeCard NVARCHAR(20),
	--@ParentId INT,
	--@Fromdate1 NVARCHAR(50),
 --   @Todate1 NVARCHAR(50),
	--@DesignationID INT,
	--@Gender NVARCHAR(10),
	--@EmpAutoID INT

	--DECLARE @InputDate NVARCHAR(50) = @Fromdate1
	--DECLARE @InputDates NVARCHAR(50) = @Todate1
	--DECLARE @DateInDateTime DATETIME
	--DECLARE @DateInDateTimes DATETIME

 --Convert the input string to datetime
	--SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
	--SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
 --Convert the datetime to the desired format
	--Set @Fromdate1= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
	--Set @Todate1= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)

	print @Fromdate1
	Print @Todate1

	--Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	
	Declare @CountOfRecords int
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(50),FatherName NVARCHAR(50),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),Present NUMERIC(18,1),
		Absent NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
		F_Day1 NVARCHAR(100) DEFAULT '-',F_Day2 NVARCHAR(100) DEFAULT '-',F_Day3 NVARCHAR(100) DEFAULT '-',F_Day4 NVARCHAR(100) DEFAULT '-',F_Day5 NVARCHAR(100) DEFAULT '-',F_Day6 NVARCHAR(100) DEFAULT '-',F_Day7 NVARCHAR(100) DEFAULT '-',F_Day8 NVARCHAR(100) DEFAULT '-',F_Day9 NVARCHAR(100) DEFAULT '-',F_Day10 NVARCHAR(100) DEFAULT '-',F_Day11 NVARCHAR(100) DEFAULT '-',F_Day12 NVARCHAR(100) DEFAULT '-',F_Day13 NVARCHAR(100) DEFAULT '-',F_Day14 NVARCHAR(100) DEFAULT '-',F_Day15 NVARCHAR(100) DEFAULT '-',F_Day16 NVARCHAR(100) DEFAULT '-',F_Day17 NVARCHAR(100) DEFAULT '-',F_Day18 NVARCHAR(100) DEFAULT '-',F_Day19 NVARCHAR(100) DEFAULT '-',F_Day20 NVARCHAR(100) DEFAULT '-',F_Day21 NVARCHAR(100) DEFAULT '-',F_Day22 NVARCHAR(100) DEFAULT '-',F_Day23 NVARCHAR(100) DEFAULT '-',F_Day24 NVARCHAR(100) DEFAULT '-',F_Day25 NVARCHAR(100) DEFAULT '-',F_Day26 NVARCHAR(100) DEFAULT '-',F_Day27 NVARCHAR(100) DEFAULT '-',F_Day28 NVARCHAR(100) DEFAULT '-',F_Day29 NVARCHAR(100) DEFAULT '-',F_Day30 NVARCHAR(100) DEFAULT '-',F_Day31 NVARCHAR(100) DEFAULT '-',
	    A_Day1 NVARCHAR(100) DEFAULT '-',A_Day2 NVARCHAR(100) DEFAULT '-',A_Day3 NVARCHAR(100) DEFAULT '-',A_Day4 NVARCHAR(100) DEFAULT '-',A_Day5 NVARCHAR(100) DEFAULT '-',A_Day6 NVARCHAR(100) DEFAULT '-',A_Day7 NVARCHAR(100) DEFAULT '-',A_Day8 NVARCHAR(100) DEFAULT '-',A_Day9 NVARCHAR(100) DEFAULT '-',A_Day10 NVARCHAR(100) DEFAULT '-',A_Day11 NVARCHAR(100) DEFAULT '-',A_Day12 NVARCHAR(100) DEFAULT '-',A_Day13 NVARCHAR(100) DEFAULT '-',A_Day14 NVARCHAR(100) DEFAULT '-',A_Day15 NVARCHAR(100) DEFAULT '-',A_Day16 NVARCHAR(100) DEFAULT '-',A_Day17 NVARCHAR(100) DEFAULT '-',A_Day18 NVARCHAR(100) DEFAULT '-',A_Day19 NVARCHAR(100) DEFAULT '-',A_Day20 NVARCHAR(100) DEFAULT '-',A_Day21 NVARCHAR(100) DEFAULT '-',A_Day22 NVARCHAR(100) DEFAULT '-',A_Day23 NVARCHAR(100) DEFAULT '-',A_Day24 NVARCHAR(100) DEFAULT '-',A_Day25 NVARCHAR(100) DEFAULT '-',A_Day26 NVARCHAR(100) DEFAULT '-',A_Day27 NVARCHAR(100) DEFAULT '-',A_Day28 NVARCHAR(100) DEFAULT '-',A_Day29 NVARCHAR(100) DEFAULT '-',A_Day30 NVARCHAR(100) DEFAULT '-',A_Day31 NVARCHAR(100) DEFAULT '-',	
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)  
	)

	Create Table #Ta_Tbl_levelDetail (id int, name nvarchar(100))

	--Assign Variable into some values
	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=CONVERT(Datetime, @Fromdate1,105),@loca_Todate1=CONVERT(Datetime, @Todate1,105),@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
    IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN
		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	
	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
    INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
    --For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel     SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0
    
	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)
	
	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	INSERT INTO #EmpInOutDetails 
	SELECT	E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))
	
	---Updating OD Notation 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    
    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN 
											  END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	INSERT INTO #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar)
	SELECT DISTINCT Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar FROM #EmpInOutDetails 
	
	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance
	UPDATE #AllEmpInOutDetails set PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1, PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	
	SET @Count=1
	DECLARE @SQLUS NVARCHAR(max)
	DECLARE @SQLHeader NVARCHAR(max)
	WHILE(@Count <=31)
	BEGIN
		--Creating Table Header
		SET @SQLHeader=''
		SET @SQLUS=''
		SET @SQLHeader = @SQLHeader + ' UPDATE #TempHeader SET Day'+CAST(@Count as NVARCHAR(10)) + '=' + CAST (datepart(d,@loca_Fromdate1)as NVARCHAR(10)) + 'WHERE id=1'	
		EXEC(@SQLHeader)
		--Updating data of particular date.
		IF(@Count <=@Diff)
		BEGIN			
			SET @SQLUS = @SQLUS + ' UPDATE AD SET F_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceFN,A_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceAN'
			SET @SQLUS = @SQLUS + ' FROM  #EmpInOutDetails ED INNER JOIN #AllEmpInOutDetails AD on AD.Employee_code_id=	ED.Employee_code_id AND ED.date =   CONVERT(DATETIME, ''' + @loca_Fromdate1 + ''' , 102)'
			EXEC(@SQLUS)
		END		
		SET @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
		SET @Count=@Count +1
	END
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	

	


	
	SELECT	A.Employee_Code_Id,
			A.Name,
			Designation,
			--#Ta_Tbl_levelDetail.name,
			--#Ta_Tbl_levelDetail.id,
			CLAvailed,
			F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,
			F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
			FatherName,
			Present,
			Absent,
			Leave,
			Holiday,
			TotalOT,			
			DesignationID,
			Grade_Level,
			OrderBy,
			PD,
			AD,
			WOD,
			HD,
			LD,
			LOPD,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			TOTD,
			Aadhar,
			A_Day1,A_Day2,A_Day3,A_Day4,A_Day5,A_Day6,A_Day7,A_Day8,A_Day9,A_Day10,A_Day11,A_Day12,A_Day13,A_Day14,A_Day15,
			A_Day16,A_Day17,A_Day18,A_Day19,A_Day20,A_Day21,A_Day22,A_Day23,A_Day24,A_Day25,A_Day26,A_Day27,A_Day28,A_Day29,A_Day30,A_Day31,			
			AFDay1=REPLACE(F_Day1,'#','')+' / '+REPLACE(A_Day1,'#',''),
			AFDay2=REPLACE(F_Day2,'#','')+' / '+REPLACE(A_Day2,'#',''),
			AFDay3=REPLACE(F_Day3,'#','')+' / '+REPLACE(A_Day3,'#',''),
			AFDay4=REPLACE(F_Day4,'#','')+' / '+REPLACE(A_Day4,'#',''),
			AFDay5=REPLACE(F_Day5,'#','')+' / '+REPLACE(A_Day5,'#',''),
			AFDay6=REPLACE(F_Day6,'#','')+' / '+REPLACE(A_Day6,'#',''),
			AFDay7=REPLACE(F_Day7,'#','')+' / '+REPLACE(A_Day7,'#',''),
			AFDay8=REPLACE(F_Day8,'#','')+' / '+REPLACE(A_Day8,'#',''),
			AFDay9=REPLACE(F_Day9,'#','')+' / '+REPLACE(A_Day9,'#',''),
			AFDay10=REPLACE(F_Day10,'#','')+' / '+REPLACE(A_Day10,'#',''),
			AFDay11=REPLACE(F_Day11,'#','')+' / '+REPLACE(A_Day11,'#',''),
			AFDay12=REPLACE(F_Day12,'#','')+' / '+REPLACE(A_Day12,'#',''),
			AFDay13=REPLACE(F_Day13,'#','')+' / '+REPLACE(A_Day13,'#',''),
			AFDay14=REPLACE(F_Day14,'#','')+' / '+REPLACE(A_Day14,'#',''),
			AFDay15=REPLACE(F_Day15,'#','')+' / '+REPLACE(A_Day15,'#',''),
			AFDay16=REPLACE(F_Day16,'#','')+' / '+REPLACE(A_Day16,'#',''),
			AFDay17=REPLACE(F_Day17,'#','')+' / '+REPLACE(A_Day17,'#',''),
			AFDay18=REPLACE(F_Day18,'#','')+' / '+REPLACE(A_Day18,'#',''),
			AFDay19=REPLACE(F_Day19,'#','')+' / '+REPLACE(A_Day19,'#',''),
			AFDay20=REPLACE(F_Day20,'#','')+' / '+REPLACE(A_Day20,'#',''),
			AFDay21=REPLACE(F_Day21,'#','')+' / '+REPLACE(A_Day21,'#',''),
			AFDay22=REPLACE(F_Day22,'#','')+' / '+REPLACE(A_Day22,'#',''),
			AFDay23=REPLACE(F_Day23,'#','')+' / '+REPLACE(A_Day23,'#',''),
			AFDay24=REPLACE(F_Day24,'#','')+' / '+REPLACE(A_Day24,'#',''),
			AFDay25=REPLACE(F_Day25,'#','')+' / '+REPLACE(A_Day25,'#',''),
			AFDay26=REPLACE(F_Day26,'#','')+' / '+REPLACE(A_Day26,'#',''),
			AFDay27=REPLACE(F_Day27,'#','')+' / '+REPLACE(A_Day27,'#',''),
			AFDay28=REPLACE(F_Day28,'#','')+' / '+REPLACE(A_Day28,'#',''),
			AFDay29=REPLACE(F_Day29,'#','')+' / '+REPLACE(A_Day29,'#',''),
			AFDay30=REPLACE(F_Day30,'#','')+' / '+REPLACE(A_Day30,'#',''),
			AFDay31=REPLACE(F_Day31,'#','')+' / '+REPLACE(A_Day31,'#','')			
	FROM #AllEmpInOutDetails A 
	--inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = A.Employee_Code_Id
	--inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	--left Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
	ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),A.Name


	if(@LevelID != '0')
	begin 
	
	insert  into #Ta_Tbl_levelDetail
	Select l1.id,l2.name+' '+l1.name  From Ta_Tbl_levelDetails l1 inner join Ta_Tbl_levelDetails l2 on l1.parentId=l2.id inner Join Ta_Tbl_levelDetails l3 on l2.parentId=l3.id  where l3.id=@LevelID


	

 --   SELECT id, levelId, parentId, name, description into #RecursiveCTE
 --   FROM Ta_Tbl_levelDetails 
 --   WHERE id = @LevelID  

	-- SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetails
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #RecursiveCTE r ON t.parentId = r.id

	--SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetail
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #Ta_Tbl_levelDetails r ON t.parentId = r.id

	 SELECT
        #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0 ELSE Case when F_Day1='p' then 0.5 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0 ELSE Case when A_Day1='p' then 0.5 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0 ELSE Case when F_Day2='p' then 0.5 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0 ELSE Case when A_Day2='p' then 0.5 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0 ELSE Case when F_Day3='p' then 0.5 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0 ELSE Case when A_Day3='p' then 0.5 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0 ELSE Case when F_Day4='p' then 0.5 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0 ELSE Case when A_Day4='p' then 0.5 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0 ELSE Case when F_Day5='p' then 0.5 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0 ELSE Case when A_Day5='p' then 0.5 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0 ELSE Case when F_Day6='p' then 0.5 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0 ELSE Case when A_Day6='p' then 0.5 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0 ELSE Case when F_Day7='p' then 0.5 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0 ELSE Case when A_Day7='p' then 0.5 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0 ELSE Case when F_Day8='p' then 0.5 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0 ELSE Case when A_Day8='p' then 0.5 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0 ELSE Case when F_Day9='p' then 0.5 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0 ELSE Case when A_Day9='p' then 0.5 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0 ELSE Case when F_Day10='p' then 0.5 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0 ELSE Case when A_Day10='p' then 0.5 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0 ELSE Case when F_Day11='p' then 0.5 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0 ELSE Case when A_Day11='p' then 0.5 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0 ELSE Case when F_Day12='p' then 0.5 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0 ELSE Case when A_Day12='p' then 0.5 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0 ELSE Case when F_Day13='p' then 0.5 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0 ELSE Case when A_Day13='p' then 0.5 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0 ELSE Case when F_Day14='p' then 0.5 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0 ELSE Case when A_Day14='p' then 0.5 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0 ELSE Case when F_Day15='p' then 0.5 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0 ELSE Case when A_Day15='p' then 0.5 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0 ELSE Case when F_Day16='p' then 0.5 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0 ELSE Case when A_Day16='p' then 0.5 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0 ELSE Case when F_Day17='p' then 0.5 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0 ELSE Case when A_Day17='p' then 0.5 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0 ELSE Case when F_Day18='p' then 0.5 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0 ELSE Case when A_Day18='p' then 0.5 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0 ELSE Case when F_Day19='p' then 0.5 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0 ELSE Case when A_Day19='p' then 0.5 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0 ELSE Case when F_Day20='p' then 0.5 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0 ELSE Case when A_Day20='p' then 0.5 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0 ELSE Case when F_Day21='p' then 0.5 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0 ELSE Case when A_Day21='p' then 0.5 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0 ELSE Case when F_Day22='p' then 0.5 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0 ELSE Case when A_Day22='p' then 0.5 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0 ELSE Case when F_Day23='p' then 0.5 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0 ELSE Case when A_Day23='p' then 0.5 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0 ELSE Case when F_Day24='p' then 0.5 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0 ELSE Case when A_Day24='p' then 0.5 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0 ELSE Case when F_Day25='p' then 0.5 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0 ELSE Case when A_Day25='p' then 0.5 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0 ELSE Case when F_Day26='p' then 0.5 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0 ELSE Case when A_Day26='p' then 0.5 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0 ELSE Case when F_Day27='p' then 0.5 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0 ELSE Case when A_Day27='p' then 0.5 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0 ELSE Case when F_Day28='p' then 0.5 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0 ELSE Case when A_Day28='p' then 0.5 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0 ELSE Case when F_Day29='p' then 0.5 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0 ELSE Case when A_Day29='p' then 0.5 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0 ELSE Case when F_Day30='p' then 0.5 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0 ELSE Case when A_Day30='p' then 0.5 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0 ELSE Case when F_Day31='p' then 0.5 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0 ELSE Case when A_Day31='p' then 0.5 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount into #TempCountData
    FROM #AllEmpInOutDetails
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = #AllEmpInOutDetails.Employee_Code_Id
	inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	right Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
    GROUP BY #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id

	Declare @EmployeeCount Int
	Select @EmployeeCount=Count(*) from #TempCountData

 Select #TempCountData.id,#TempCountData.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge

from #TempCountData  where #TempCountData.id!=''
GROUP BY #TempCountData.id,#TempCountData.name

Select @CountOfRecords=Count(A1Count) From #TempCountData
Declare @Countdays nvarchar(10)
set @Countdays ='A'+CONVERT(Nvarchar(10),Day(Convert(DateTime,@loca_Fromdate1,108)))+'count'
Select @Countdays
Declare @Sql nvarchar(Max)
Set @Sql='
Select name,FORMAT(ROUND((Sum('+@Countdays+')/'+Convert(nvarchar(10),@CountOfRecords)+')*100,2),''N2'') As DayPercentage	  
	   From #TempCountData Group by '+@Countdays+',name'
	   --A1count,A2Count,A3Count,A4Count,A5Count,A6Count,A7Count,A8Count,A9count,A10Count,A11Count,A12Count,A13Count,A14Count,A15Count,A16Count,A17Count,A18Count,A19Count,A20count,A21Count,A22Count,A23Count,A24Count,A25Count,A26Count,A27Count,A28Count,A29Count,A30Count,A31Count,name
	   Select @Sql
	exec(@Sql)

	drop Table #TempCountData
	end 

	else 
	begin 

	--insert into #Ta_Tbl_levelDetail 
	--Select l1.id,l2.name+' '+l1.name From Ta_Tbl_levelDetails l1 inner join Ta_Tbl_levelDetails l2 on l1.parentId=l2.id inner Join Ta_Tbl_levelDetails l3 on l2.parentId=l3.id 


	--Select * From #Ta_Tbl_levelDetail


    SELECT id, levelId, parentId, name, description into #RecursiveCTEs
    FROM Ta_Tbl_levelDetails  

	 SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetailss
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #RecursiveCTEs r ON t.parentId = r.id

	SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetaill
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #Ta_Tbl_levelDetailss r ON t.parentId = r.id

	--Select * From #Ta_Tbl_levelDetaill

	 SELECT  #Ta_Tbl_levelDetaill.id,#Ta_Tbl_levelDetaill.name,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0 ELSE Case when F_Day1='p' then 0.5 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0 ELSE Case when A_Day1='p' then 0.5 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0 ELSE Case when F_Day2='p' then 0.5 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0 ELSE Case when A_Day2='p' then 0.5 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0 ELSE Case when F_Day3='p' then 0.5 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0 ELSE Case when A_Day3='p' then 0.5 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0 ELSE Case when F_Day4='p' then 0.5 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0 ELSE Case when A_Day4='p' then 0.5 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0 ELSE Case when F_Day5='p' then 0.5 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0 ELSE Case when A_Day5='p' then 0.5 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0 ELSE Case when F_Day6='p' then 0.5 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0 ELSE Case when A_Day6='p' then 0.5 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0 ELSE Case when F_Day7='p' then 0.5 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0 ELSE Case when A_Day7='p' then 0.5 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0 ELSE Case when F_Day8='p' then 0.5 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0 ELSE Case when A_Day8='p' then 0.5 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0 ELSE Case when F_Day9='p' then 0.5 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0 ELSE Case when A_Day9='p' then 0.5 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0 ELSE Case when F_Day10='p' then 0.5 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0 ELSE Case when A_Day10='p' then 0.5 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0 ELSE Case when F_Day11='p' then 0.5 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0 ELSE Case when A_Day11='p' then 0.5 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0 ELSE Case when F_Day12='p' then 0.5 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0 ELSE Case when A_Day12='p' then 0.5 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0 ELSE Case when F_Day13='p' then 0.5 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0 ELSE Case when A_Day13='p' then 0.5 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0 ELSE Case when F_Day14='p' then 0.5 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0 ELSE Case when A_Day14='p' then 0.5 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0 ELSE Case when F_Day15='p' then 0.5 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0 ELSE Case when A_Day15='p' then 0.5 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0 ELSE Case when F_Day16='p' then 0.5 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0 ELSE Case when A_Day16='p' then 0.5 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0 ELSE Case when F_Day17='p' then 0.5 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0 ELSE Case when A_Day17='p' then 0.5 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0 ELSE Case when F_Day18='p' then 0.5 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0 ELSE Case when A_Day18='p' then 0.5 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0 ELSE Case when F_Day19='p' then 0.5 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0 ELSE Case when A_Day19='p' then 0.5 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0 ELSE Case when F_Day20='p' then 0.5 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0 ELSE Case when A_Day20='p' then 0.5 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0 ELSE Case when F_Day21='p' then 0.5 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0 ELSE Case when A_Day21='p' then 0.5 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0 ELSE Case when F_Day22='p' then 0.5 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0 ELSE Case when A_Day22='p' then 0.5 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0 ELSE Case when F_Day23='p' then 0.5 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0 ELSE Case when A_Day23='p' then 0.5 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0 ELSE Case when F_Day24='p' then 0.5 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0 ELSE Case when A_Day24='p' then 0.5 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0 ELSE Case when F_Day25='p' then 0.5 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0 ELSE Case when A_Day25='p' then 0.5 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0 ELSE Case when F_Day26='p' then 0.5 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0 ELSE Case when A_Day26='p' then 0.5 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0 ELSE Case when F_Day27='p' then 0.5 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0 ELSE Case when A_Day27='p' then 0.5 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0 ELSE Case when F_Day28='p' then 0.5 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0 ELSE Case when A_Day28='p' then 0.5 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0 ELSE Case when F_Day29='p' then 0.5 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0 ELSE Case when A_Day29='p' then 0.5 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0 ELSE Case when F_Day30='p' then 0.5 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0 ELSE Case when A_Day30='p' then 0.5 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0 ELSE Case when F_Day31='p' then 0.5 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0 ELSE Case when A_Day31='p' then 0.5 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount ,#Ta_Tbl_levelDetaill.parentId into #TempCountDatas
    FROM #Ta_Tbl_levelDetaill
	Inner Join TA_Tbl_EmployeeLevel on #Ta_Tbl_levelDetaill.id= TA_Tbl_EmployeeLevel.LevelId
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	Left Join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_Code_Id=TA_Tbl_Employee.Employee_Code_Id
	--inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id

    GROUP BY #Ta_Tbl_levelDetaill.id,#Ta_Tbl_levelDetaill.name,#Ta_Tbl_levelDetaill.parentId
	--#AllEmpInOutDetails

	Select @EmployeeCount=Count(*) from #TempCountDatas



 Select #TempCountDatas.id,#TempCountDatas.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge
from #TempCountDatas where #TempCountDatas.id!=''
GROUP BY #TempCountDatas.id,#TempCountDatas.name



Select @CountOfRecords=Count(A1Count) From #TempCountDatas

--Select name,
--	   FORMAT(ROUND((Sum(A1count)/@CountOfRecords)*100,2),'N2') As Day1Percentage,
--	   FORMAT(ROUND((Sum(A2Count)/@CountOfRecords)*100,2),'N2') As Day2Percentage,
--	   FORMAT(ROUND((Sum(A3Count)/@CountOfRecords)*100,2),'N2') As Day3Percentage,
--	   FORMAT(ROUND((Sum(A4Count)/@CountOfRecords)*100,2),'N2') As Day4Percentage,
--	   FORMAT(ROUND((Sum(A5Count)/@CountOfRecords)*100,2),'N2') As Day5Percentage,
--	   FORMAT(ROUND((Sum(A6Count)/@CountOfRecords)*100,2),'N2') As Day6Percentage,
--	   FORMAT(ROUND((Sum(A7Count)/@CountOfRecords)*100,2),'N2') As Day7Percentage,
--	   FORMAT(ROUND((Sum(A8Count)/@CountOfRecords)*100,2),'N2') As Day8Percentage,
--	   FORMAT(ROUND((Sum(A9count)/@CountOfRecords)*100,2),'N2') As Day9Percentage,
--	   FORMAT(ROUND((Sum(A10Count)/@CountOfRecords)*100,2),'N2') As Day10Percentage,
--	   FORMAT(ROUND((Sum(A11Count)/@CountOfRecords)*100,2),'N2') As Day11Percentage,
--	   FORMAT(ROUND((Sum(A12Count)/@CountOfRecords)*100,2),'N2') As Day12Percentage,
--	   FORMAT(ROUND((Sum(A13Count)/@CountOfRecords)*100,2),'N2') As Day13Percentage,
--	   FORMAT(ROUND((Sum(A14Count)/@CountOfRecords)*100,2),'N2') As Day14Percentage,
--	   FORMAT(ROUND((Sum(A15Count)/@CountOfRecords)*100,2),'N2') As Day15Percentage,
--	   FORMAT(ROUND((Sum(A16Count)/@CountOfRecords)*100,2),'N2') As Day16Percentage,
--	   FORMAT(ROUND((Sum(A17Count)/@CountOfRecords)*100,2),'N2') As Day17Percentage,
--	   FORMAT(ROUND((Sum(A18Count)/@CountOfRecords)*100,2),'N2') As Day18Percentage,
--	   FORMAT(ROUND((Sum(A19Count)/@CountOfRecords)*100,2),'N2') As Day19Percentage,
--	   FORMAT(ROUND((Sum(A20count)/@CountOfRecords)*100,2),'N2') As Day20Percentage,
--	   FORMAT(ROUND((Sum(A21Count)/@CountOfRecords)*100,2),'N2') As Day21Percentage,
--	   FORMAT(ROUND((Sum(A22Count)/@CountOfRecords)*100,2),'N2') As Day22Percentage,
--	   FORMAT(ROUND((Sum(A23Count)/@CountOfRecords)*100,2),'N2') As Day23Percentage,
--	   FORMAT(ROUND((Sum(A24Count)/@CountOfRecords)*100,2),'N2') As Day24Percentage,
--	   FORMAT(ROUND((Sum(A25Count)/@CountOfRecords)*100,2),'N2') As Day25Percentage,
--	   FORMAT(ROUND((Sum(A26Count)/@CountOfRecords)*100,2),'N2') As Day26Percentage,
--	   FORMAT(ROUND((Sum(A27Count)/@CountOfRecords)*100,2),'N2') As Day27Percentage,
--	   FORMAT(ROUND((Sum(A28Count)/@CountOfRecords)*100,2),'N2') As Day28Percentage,
--	   FORMAT(ROUND((Sum(A29Count)/@CountOfRecords)*100,2),'N2') As Day29Percentage,
--	   FORMAT(ROUND((Sum(A30Count)/@CountOfRecords)*100,2),'N2') As Day30Percentage,
--	   FORMAT(ROUND((Sum(A31Count)/@CountOfRecords)*100,2),'N2') As Day31Percentage
--From #TempCountDatas Group by A1count,A2Count,A3Count,A4Count,A5Count,A6Count,A7Count,A8Count,A9count,A10Count,A11Count,A12Count,A13Count,A14Count,A15Count,A16Count,A17Count,A18Count,A19Count,A20count,A21Count,A22Count,A23Count,A24Count,A25Count,A26Count,A27Count,A28Count,A29Count,A30Count,A31Count,name





drop Table #TempCountDatas

	end

	--SELECT * FROM #TempHeader
	
	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
	Drop Table #Ta_Tbl_levelDetail

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DashBoardAnalysisbyDepartmentAbsent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec Proc_TA_DashBoardAnalysisbyDepartmentAbsent @LevelID=N'0',@ParentId=0,@Fromdate1=N'13/Aug/2024',@Todate1=N'13/Aug/2024'
-- exec Proc_TA_DashBoardAnalysisbyDepartmentAbsent @LevelID=N'0',@ParentId=0,@Fromdate1=N'21/08/2024',@Todate1=N'21/08/2024',@isflag=N'0'
-- exec Proc_TA_DashBoardAnalysisbyDepartmentAbsent @LevelID=N'0',@ParentId=37,@Fromdate1=N'20-Aug-2024',@Todate1=N'20-Aug-2024',@isflag=N'0'

Create PROCEDURE [dbo].[Proc_TA_DashBoardAnalysisbyDepartmentAbsent] 
	
	@LevelID NVARCHAR(1000), 	 
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50),
	@isflag nvarchar(10)
	
AS
BEGIN
	SET NOCOUNT ON;


	declare  @EmployeeId NVARCHAR(50)='',
	@EmployeeName NVARCHAR(50)='', 
	@employeeCategory NVARCHAR(50)='0',
	@employeeType NVARCHAR(50)='0'	,
	@UserGroupName NVARCHAR(250)='SuperAdmin',
	@GradeLevel NVARCHAR(20)='0'	,
	@EmpSwipeCard NVARCHAR(20)='',
	@DesignationID INT =0,
	@Gender NVARCHAR(10)='Both',
	@EmpAutoID INT =''


	--@EmployeeId NVARCHAR(50),
	--@EmployeeName NVARCHAR(50),  
	--@LevelID NVARCHAR(1000), 	 
	--@employeeCategory NVARCHAR(50),
	--@employeeType NVARCHAR(50)	,
	--@UserGroupName NVARCHAR(250),
	--@GradeLevel NVARCHAR(20)	,
	--@EmpSwipeCard NVARCHAR(20),
	--@ParentId INT,
	--@Fromdate1 NVARCHAR(50),
 --   @Todate1 NVARCHAR(50),
	--@DesignationID INT,
	--@Gender NVARCHAR(10),
	--@EmpAutoID INT

	--DECLARE @InputDate NVARCHAR(50) = @Fromdate1
	--DECLARE @InputDates NVARCHAR(50) = @Todate1
	--DECLARE @DateInDateTime DATETIME
	--DECLARE @DateInDateTimes DATETIME

 --Convert the input string to datetime
	--SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
	--SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
 --Convert the datetime to the desired format
	--Set @Fromdate1= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
	--Set @Todate1= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)

	print @Fromdate1
	Print @Todate1

	--Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	
	Declare @CountOfRecords int
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(50),FatherName NVARCHAR(50),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),Present NUMERIC(18,1),
		Absent NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
		F_Day1 NVARCHAR(100) DEFAULT '-',F_Day2 NVARCHAR(100) DEFAULT '-',F_Day3 NVARCHAR(100) DEFAULT '-',F_Day4 NVARCHAR(100) DEFAULT '-',F_Day5 NVARCHAR(100) DEFAULT '-',F_Day6 NVARCHAR(100) DEFAULT '-',F_Day7 NVARCHAR(100) DEFAULT '-',F_Day8 NVARCHAR(100) DEFAULT '-',F_Day9 NVARCHAR(100) DEFAULT '-',F_Day10 NVARCHAR(100) DEFAULT '-',F_Day11 NVARCHAR(100) DEFAULT '-',F_Day12 NVARCHAR(100) DEFAULT '-',F_Day13 NVARCHAR(100) DEFAULT '-',F_Day14 NVARCHAR(100) DEFAULT '-',F_Day15 NVARCHAR(100) DEFAULT '-',F_Day16 NVARCHAR(100) DEFAULT '-',F_Day17 NVARCHAR(100) DEFAULT '-',F_Day18 NVARCHAR(100) DEFAULT '-',F_Day19 NVARCHAR(100) DEFAULT '-',F_Day20 NVARCHAR(100) DEFAULT '-',F_Day21 NVARCHAR(100) DEFAULT '-',F_Day22 NVARCHAR(100) DEFAULT '-',F_Day23 NVARCHAR(100) DEFAULT '-',F_Day24 NVARCHAR(100) DEFAULT '-',F_Day25 NVARCHAR(100) DEFAULT '-',F_Day26 NVARCHAR(100) DEFAULT '-',F_Day27 NVARCHAR(100) DEFAULT '-',F_Day28 NVARCHAR(100) DEFAULT '-',F_Day29 NVARCHAR(100) DEFAULT '-',F_Day30 NVARCHAR(100) DEFAULT '-',F_Day31 NVARCHAR(100) DEFAULT '-',
	    A_Day1 NVARCHAR(100) DEFAULT '-',A_Day2 NVARCHAR(100) DEFAULT '-',A_Day3 NVARCHAR(100) DEFAULT '-',A_Day4 NVARCHAR(100) DEFAULT '-',A_Day5 NVARCHAR(100) DEFAULT '-',A_Day6 NVARCHAR(100) DEFAULT '-',A_Day7 NVARCHAR(100) DEFAULT '-',A_Day8 NVARCHAR(100) DEFAULT '-',A_Day9 NVARCHAR(100) DEFAULT '-',A_Day10 NVARCHAR(100) DEFAULT '-',A_Day11 NVARCHAR(100) DEFAULT '-',A_Day12 NVARCHAR(100) DEFAULT '-',A_Day13 NVARCHAR(100) DEFAULT '-',A_Day14 NVARCHAR(100) DEFAULT '-',A_Day15 NVARCHAR(100) DEFAULT '-',A_Day16 NVARCHAR(100) DEFAULT '-',A_Day17 NVARCHAR(100) DEFAULT '-',A_Day18 NVARCHAR(100) DEFAULT '-',A_Day19 NVARCHAR(100) DEFAULT '-',A_Day20 NVARCHAR(100) DEFAULT '-',A_Day21 NVARCHAR(100) DEFAULT '-',A_Day22 NVARCHAR(100) DEFAULT '-',A_Day23 NVARCHAR(100) DEFAULT '-',A_Day24 NVARCHAR(100) DEFAULT '-',A_Day25 NVARCHAR(100) DEFAULT '-',A_Day26 NVARCHAR(100) DEFAULT '-',A_Day27 NVARCHAR(100) DEFAULT '-',A_Day28 NVARCHAR(100) DEFAULT '-',A_Day29 NVARCHAR(100) DEFAULT '-',A_Day30 NVARCHAR(100) DEFAULT '-',A_Day31 NVARCHAR(100) DEFAULT '-',	
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)  
	)

	Create Table #Ta_Tbl_levelDetail (id int, name nvarchar(100))

	--Assign Variable into some values
	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=CONVERT(Datetime, @Fromdate1,105),@loca_Todate1=CONVERT(Datetime, @Todate1,105),@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
    IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN
		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	
	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
    INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
    --For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel     SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0
    
	Select * From #LevelRights


	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)
	
	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	INSERT INTO #EmpInOutDetails 
	SELECT	E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))
	
	---Updating OD Notation 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    
    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN 
											  END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	INSERT INTO #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar)
	SELECT DISTINCT Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar FROM #EmpInOutDetails 
	
	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance
	UPDATE #AllEmpInOutDetails set PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1, PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	
	SET @Count=1
	DECLARE @SQLUS NVARCHAR(max)
	DECLARE @SQLHeader NVARCHAR(max)
	WHILE(@Count <=31)
	BEGIN
		--Creating Table Header
		SET @SQLHeader=''
		SET @SQLUS=''
		SET @SQLHeader = @SQLHeader + ' UPDATE #TempHeader SET Day'+CAST(@Count as NVARCHAR(10)) + '=' + CAST (datepart(d,@loca_Fromdate1)as NVARCHAR(10)) + 'WHERE id=1'	
		EXEC(@SQLHeader)
		--Updating data of particular date.
		IF(@Count <=@Diff)
		BEGIN			
			SET @SQLUS = @SQLUS + ' UPDATE AD SET F_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceFN,A_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceAN'
			SET @SQLUS = @SQLUS + ' FROM  #EmpInOutDetails ED INNER JOIN #AllEmpInOutDetails AD on AD.Employee_code_id=	ED.Employee_code_id AND ED.date =   CONVERT(DATETIME, ''' + @loca_Fromdate1 + ''' , 102)'
			EXEC(@SQLUS)
		END		
		SET @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
		SET @Count=@Count +1
	END
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	

	


	
	SELECT	A.Employee_Code_Id,
			A.Name,
			Designation,
			--#Ta_Tbl_levelDetail.name,
			--#Ta_Tbl_levelDetail.id,
			CLAvailed,
			F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,
			F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
			FatherName,
			Present,
			Absent,
			Leave,
			Holiday,
			TotalOT,			
			DesignationID,
			Grade_Level,
			OrderBy,
			PD,
			AD,
			WOD,
			HD,
			LD,
			LOPD,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			TOTD,
			Aadhar,
			A_Day1,A_Day2,A_Day3,A_Day4,A_Day5,A_Day6,A_Day7,A_Day8,A_Day9,A_Day10,A_Day11,A_Day12,A_Day13,A_Day14,A_Day15,
			A_Day16,A_Day17,A_Day18,A_Day19,A_Day20,A_Day21,A_Day22,A_Day23,A_Day24,A_Day25,A_Day26,A_Day27,A_Day28,A_Day29,A_Day30,A_Day31,			
			AFDay1=REPLACE(F_Day1,'#','')+' / '+REPLACE(A_Day1,'#',''),
			AFDay2=REPLACE(F_Day2,'#','')+' / '+REPLACE(A_Day2,'#',''),
			AFDay3=REPLACE(F_Day3,'#','')+' / '+REPLACE(A_Day3,'#',''),
			AFDay4=REPLACE(F_Day4,'#','')+' / '+REPLACE(A_Day4,'#',''),
			AFDay5=REPLACE(F_Day5,'#','')+' / '+REPLACE(A_Day5,'#',''),
			AFDay6=REPLACE(F_Day6,'#','')+' / '+REPLACE(A_Day6,'#',''),
			AFDay7=REPLACE(F_Day7,'#','')+' / '+REPLACE(A_Day7,'#',''),
			AFDay8=REPLACE(F_Day8,'#','')+' / '+REPLACE(A_Day8,'#',''),
			AFDay9=REPLACE(F_Day9,'#','')+' / '+REPLACE(A_Day9,'#',''),
			AFDay10=REPLACE(F_Day10,'#','')+' / '+REPLACE(A_Day10,'#',''),
			AFDay11=REPLACE(F_Day11,'#','')+' / '+REPLACE(A_Day11,'#',''),
			AFDay12=REPLACE(F_Day12,'#','')+' / '+REPLACE(A_Day12,'#',''),
			AFDay13=REPLACE(F_Day13,'#','')+' / '+REPLACE(A_Day13,'#',''),
			AFDay14=REPLACE(F_Day14,'#','')+' / '+REPLACE(A_Day14,'#',''),
			AFDay15=REPLACE(F_Day15,'#','')+' / '+REPLACE(A_Day15,'#',''),
			AFDay16=REPLACE(F_Day16,'#','')+' / '+REPLACE(A_Day16,'#',''),
			AFDay17=REPLACE(F_Day17,'#','')+' / '+REPLACE(A_Day17,'#',''),
			AFDay18=REPLACE(F_Day18,'#','')+' / '+REPLACE(A_Day18,'#',''),
			AFDay19=REPLACE(F_Day19,'#','')+' / '+REPLACE(A_Day19,'#',''),
			AFDay20=REPLACE(F_Day20,'#','')+' / '+REPLACE(A_Day20,'#',''),
			AFDay21=REPLACE(F_Day21,'#','')+' / '+REPLACE(A_Day21,'#',''),
			AFDay22=REPLACE(F_Day22,'#','')+' / '+REPLACE(A_Day22,'#',''),
			AFDay23=REPLACE(F_Day23,'#','')+' / '+REPLACE(A_Day23,'#',''),
			AFDay24=REPLACE(F_Day24,'#','')+' / '+REPLACE(A_Day24,'#',''),
			AFDay25=REPLACE(F_Day25,'#','')+' / '+REPLACE(A_Day25,'#',''),
			AFDay26=REPLACE(F_Day26,'#','')+' / '+REPLACE(A_Day26,'#',''),
			AFDay27=REPLACE(F_Day27,'#','')+' / '+REPLACE(A_Day27,'#',''),
			AFDay28=REPLACE(F_Day28,'#','')+' / '+REPLACE(A_Day28,'#',''),
			AFDay29=REPLACE(F_Day29,'#','')+' / '+REPLACE(A_Day29,'#',''),
			AFDay30=REPLACE(F_Day30,'#','')+' / '+REPLACE(A_Day30,'#',''),
			AFDay31=REPLACE(F_Day31,'#','')+' / '+REPLACE(A_Day31,'#','')			
	FROM #AllEmpInOutDetails A 
	--inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = A.Employee_Code_Id
	--inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	--left Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
	ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),A.Name


	if(@LevelID != '0')
	begin 
	
	insert  into #Ta_Tbl_levelDetail
	Select l1.id,l2.name+' '+l1.name  From Ta_Tbl_levelDetails l1 inner join Ta_Tbl_levelDetails l2 on l1.parentId=l2.id inner Join Ta_Tbl_levelDetails l3 on l2.parentId=l3.id  where l3.id=@LevelID


 --   SELECT id, levelId, parentId, name, description into #RecursiveCTE
 --   FROM Ta_Tbl_levelDetails 
 --   WHERE id = @LevelID  

	-- SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetails
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #RecursiveCTE r ON t.parentId = r.id

	--SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetail
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #Ta_Tbl_levelDetails r ON t.parentId = r.id

	 SELECT
        #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0.5 ELSE Case when F_Day1='p' then 0 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0.5 ELSE Case when A_Day1='p' then 0 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0.5 ELSE Case when F_Day2='p' then 0 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0.5 ELSE Case when A_Day2='p' then 0 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0.5 ELSE Case when F_Day3='p' then 0 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0.5 ELSE Case when A_Day3='p' then 0 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0.5 ELSE Case when F_Day4='p' then 0 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0.5 ELSE Case when A_Day4='p' then 0 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0.5 ELSE Case when F_Day5='p' then 0 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0.5 ELSE Case when A_Day5='p' then 0 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0.5 ELSE Case when F_Day6='p' then 0 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0.5 ELSE Case when A_Day6='p' then 0 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0.5 ELSE Case when F_Day7='p' then 0 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0.5 ELSE Case when A_Day7='p' then 0 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0.5 ELSE Case when F_Day8='p' then 0 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0.5 ELSE Case when A_Day8='p' then 0 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0.5 ELSE Case when F_Day9='p' then 0 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0.5 ELSE Case when A_Day9='p' then 0 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0.5 ELSE Case when F_Day10='p' then 0 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0.5 ELSE Case when A_Day10='p' then 0 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0.5 ELSE Case when F_Day11='p' then 0 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0.5 ELSE Case when A_Day11='p' then 0 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0.5 ELSE Case when F_Day12='p' then 0 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0.5 ELSE Case when A_Day12='p' then 0 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0.5 ELSE Case when F_Day13='p' then 0 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0.5 ELSE Case when A_Day13='p' then 0 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0.5 ELSE Case when F_Day14='p' then 0 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0.5 ELSE Case when A_Day14='p' then 0 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0.5 ELSE Case when F_Day15='p' then 0 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0.5 ELSE Case when A_Day15='p' then 0 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0.5 ELSE Case when F_Day16='p' then 0 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0.5 ELSE Case when A_Day16='p' then 0 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0.5 ELSE Case when F_Day17='p' then 0 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0.5 ELSE Case when A_Day17='p' then 0 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0.5 ELSE Case when F_Day18='p' then 0 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0.5 ELSE Case when A_Day18='p' then 0 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0.5 ELSE Case when F_Day19='p' then 0 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0.5 ELSE Case when A_Day19='p' then 0 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0.5 ELSE Case when F_Day20='p' then 0 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0.5 ELSE Case when A_Day20='p' then 0 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0.5 ELSE Case when F_Day21='p' then 0 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0.5 ELSE Case when A_Day21='p' then 0 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0.5 ELSE Case when F_Day22='p' then 0 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0.5 ELSE Case when A_Day22='p' then 0 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0.5 ELSE Case when F_Day23='p' then 0 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0.5 ELSE Case when A_Day23='p' then 0 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0.5 ELSE Case when F_Day24='p' then 0 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0.5 ELSE Case when A_Day24='p' then 0 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0.5 ELSE Case when F_Day25='p' then 0 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0.5 ELSE Case when A_Day25='p' then 0 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0.5 ELSE Case when F_Day26='p' then 0 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0.5 ELSE Case when A_Day26='p' then 0 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0.5 ELSE Case when F_Day27='p' then 0 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0.5 ELSE Case when A_Day27='p' then 0 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0.5 ELSE Case when F_Day28='p' then 0 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0.5 ELSE Case when A_Day28='p' then 0 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0.5 ELSE Case when F_Day29='p' then 0 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0.5 ELSE Case when A_Day29='p' then 0 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0.5 ELSE Case when F_Day30='p' then 0 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0.5 ELSE Case when A_Day30='p' then 0 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0.5 ELSE Case when F_Day31='p' then 0 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0.5 ELSE Case when A_Day31='p' then 0 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount into #TempCountData
    FROM #AllEmpInOutDetails
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = #AllEmpInOutDetails.Employee_Code_Id
	inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	right Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
    GROUP BY #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id

	Declare @EmployeeCount Int
	Select @EmployeeCount=Count(*) from #TempCountData

 Select #TempCountData.id,#TempCountData.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge

from #TempCountData  where #TempCountData.id!=''
GROUP BY #TempCountData.id,#TempCountData.name

Select @CountOfRecords=Count(A1Count) From #TempCountData
Declare @Countdays nvarchar(10)
set @Countdays ='A'+CONVERT(Nvarchar(10),Day(Convert(DateTime,@loca_Fromdate1,108)))+'count'
Select @Countdays
Declare @Sql nvarchar(Max)
Set @Sql='
Select name,FORMAT(ROUND((Sum('+@Countdays+')/'+Convert(nvarchar(10),@CountOfRecords)+')*100,2),''N2'') As DayPercentage	  
	   From #TempCountData Group by '+@Countdays+',name'
	   --A1count,A2Count,A3Count,A4Count,A5Count,A6Count,A7Count,A8Count,A9count,A10Count,A11Count,A12Count,A13Count,A14Count,A15Count,A16Count,A17Count,A18Count,A19Count,A20count,A21Count,A22Count,A23Count,A24Count,A25Count,A26Count,A27Count,A28Count,A29Count,A30Count,A31Count,name
	   Select @Sql
	exec(@Sql)

	drop Table #TempCountData
	end 

	else 
	begin 

	insert into #Ta_Tbl_levelDetail 
	Select l1.id,l2.name+' '+l1.name From Ta_Tbl_levelDetails l1 inner join Ta_Tbl_levelDetails l2 on l1.parentId=l2.id inner Join Ta_Tbl_levelDetails l3 on l2.parentId=l3.id  where l3.id= Case when @ParentId=0 then 1 Else @ParentId End


	Select * From #Ta_Tbl_levelDetail


 --   SELECT id, levelId, parentId, name, description into #RecursiveCTEs
 --   FROM Ta_Tbl_levelDetails  

	-- SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetailss
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #RecursiveCTEs r ON t.parentId = r.id

	--SELECT t.id, t.levelId, t.parentId,r.name+' '+t.name As name, t.description into #Ta_Tbl_levelDetaill
 --   FROM Ta_Tbl_levelDetails t
 --   INNER JOIN #Ta_Tbl_levelDetailss r ON t.parentId = r.id

	--Select * From #Ta_Tbl_levelDetaill

	

	 SELECT  #Ta_Tbl_levelDetail.id,#Ta_Tbl_levelDetail.name,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0.5 ELSE Case when F_Day1='p' then 0 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0.5 ELSE Case when A_Day1='p' then 0 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0.5 ELSE Case when F_Day2='p' then 0 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0.5 ELSE Case when A_Day2='p' then 0 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0.5 ELSE Case when F_Day3='p' then 0 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0.5 ELSE Case when A_Day3='p' then 0 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0.5 ELSE Case when F_Day4='p' then 0 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0.5 ELSE Case when A_Day4='p' then 0 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0.5 ELSE Case when F_Day5='p' then 0 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0.5 ELSE Case when A_Day5='p' then 0 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0.5 ELSE Case when F_Day6='p' then 0 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0.5 ELSE Case when A_Day6='p' then 0 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0.5 ELSE Case when F_Day7='p' then 0 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0.5 ELSE Case when A_Day7='p' then 0 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0.5 ELSE Case when F_Day8='p' then 0 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0.5 ELSE Case when A_Day8='p' then 0 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0.5 ELSE Case when F_Day9='p' then 0 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0.5 ELSE Case when A_Day9='p' then 0 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0.5 ELSE Case when F_Day10='p' then 0 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0.5 ELSE Case when A_Day10='p' then 0 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0.5 ELSE Case when F_Day11='p' then 0 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0.5 ELSE Case when A_Day11='p' then 0 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0.5 ELSE Case when F_Day12='p' then 0 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0.5 ELSE Case when A_Day12='p' then 0 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0.5 ELSE Case when F_Day13='p' then 0 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0.5 ELSE Case when A_Day13='p' then 0 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0.5 ELSE Case when F_Day14='p' then 0 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0.5 ELSE Case when A_Day14='p' then 0 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0.5 ELSE Case when F_Day15='p' then 0 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0.5 ELSE Case when A_Day15='p' then 0 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0.5 ELSE Case when F_Day16='p' then 0 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0.5 ELSE Case when A_Day16='p' then 0 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0.5 ELSE Case when F_Day17='p' then 0 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0.5 ELSE Case when A_Day17='p' then 0 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0.5 ELSE Case when F_Day18='p' then 0 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0.5 ELSE Case when A_Day18='p' then 0 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0.5 ELSE Case when F_Day19='p' then 0 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0.5 ELSE Case when A_Day19='p' then 0 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0.5 ELSE Case when F_Day20='p' then 0 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0.5 ELSE Case when A_Day20='p' then 0 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0.5 ELSE Case when F_Day21='p' then 0 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0.5 ELSE Case when A_Day21='p' then 0 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0.5 ELSE Case when F_Day22='p' then 0 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0.5 ELSE Case when A_Day22='p' then 0 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0.5 ELSE Case when F_Day23='p' then 0 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0.5 ELSE Case when A_Day23='p' then 0 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0.5 ELSE Case when F_Day24='p' then 0 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0.5 ELSE Case when A_Day24='p' then 0.5 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0.5 ELSE Case when F_Day25='p' then 0 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0.5 ELSE Case when A_Day25='p' then 0 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0.5 ELSE Case when F_Day26='p' then 0 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0.5 ELSE Case when A_Day26='p' then 0 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0.5 ELSE Case when F_Day27='p' then 0 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0.5 ELSE Case when A_Day27='p' then 0 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0.5 ELSE Case when F_Day28='p' then 0 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0.5 ELSE Case when A_Day28='p' then 0 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0.5 ELSE Case when F_Day29='p' then 0 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0.5 ELSE Case when A_Day29='p' then 0 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0.5 ELSE Case when F_Day30='p' then 0 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0.5 ELSE Case when A_Day30='p' then 0 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0.5 ELSE Case when F_Day31='p' then 0 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0.5 ELSE Case when A_Day31='p' then 0 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount into #TempCountDatas
    FROM #Ta_Tbl_levelDetail
	Inner Join TA_Tbl_EmployeeLevel on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	Left Join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_Code_Id=TA_Tbl_Employee.Employee_Code_Id
	--inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id

    GROUP BY #Ta_Tbl_levelDetail.id,#Ta_Tbl_levelDetail.name
	--#AllEmpInOutDetails

	Select @EmployeeCount=Count(*) from #TempCountDatas

	--Select * From #TempCountDatas

 Select #TempCountDatas.id,#TempCountDatas.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge
from #TempCountDatas where #TempCountDatas.id!=''
GROUP BY #TempCountDatas.id,#TempCountDatas.name



Select @CountOfRecords=Count(A1Count) From #TempCountDatas

--Select name,
--	   FORMAT(ROUND((Sum(A1count)/@CountOfRecords)*100,2),'N2') As Day1Percentage,
--	   FORMAT(ROUND((Sum(A2Count)/@CountOfRecords)*100,2),'N2') As Day2Percentage,
--	   FORMAT(ROUND((Sum(A3Count)/@CountOfRecords)*100,2),'N2') As Day3Percentage,
--	   FORMAT(ROUND((Sum(A4Count)/@CountOfRecords)*100,2),'N2') As Day4Percentage,
--	   FORMAT(ROUND((Sum(A5Count)/@CountOfRecords)*100,2),'N2') As Day5Percentage,
--	   FORMAT(ROUND((Sum(A6Count)/@CountOfRecords)*100,2),'N2') As Day6Percentage,
--	   FORMAT(ROUND((Sum(A7Count)/@CountOfRecords)*100,2),'N2') As Day7Percentage,
--	   FORMAT(ROUND((Sum(A8Count)/@CountOfRecords)*100,2),'N2') As Day8Percentage,
--	   FORMAT(ROUND((Sum(A9count)/@CountOfRecords)*100,2),'N2') As Day9Percentage,
--	   FORMAT(ROUND((Sum(A10Count)/@CountOfRecords)*100,2),'N2') As Day10Percentage,
--	   FORMAT(ROUND((Sum(A11Count)/@CountOfRecords)*100,2),'N2') As Day11Percentage,
--	   FORMAT(ROUND((Sum(A12Count)/@CountOfRecords)*100,2),'N2') As Day12Percentage,
--	   FORMAT(ROUND((Sum(A13Count)/@CountOfRecords)*100,2),'N2') As Day13Percentage,
--	   FORMAT(ROUND((Sum(A14Count)/@CountOfRecords)*100,2),'N2') As Day14Percentage,
--	   FORMAT(ROUND((Sum(A15Count)/@CountOfRecords)*100,2),'N2') As Day15Percentage,
--	   FORMAT(ROUND((Sum(A16Count)/@CountOfRecords)*100,2),'N2') As Day16Percentage,
--	   FORMAT(ROUND((Sum(A17Count)/@CountOfRecords)*100,2),'N2') As Day17Percentage,
--	   FORMAT(ROUND((Sum(A18Count)/@CountOfRecords)*100,2),'N2') As Day18Percentage,
--	   FORMAT(ROUND((Sum(A19Count)/@CountOfRecords)*100,2),'N2') As Day19Percentage,
--	   FORMAT(ROUND((Sum(A20count)/@CountOfRecords)*100,2),'N2') As Day20Percentage,
--	   FORMAT(ROUND((Sum(A21Count)/@CountOfRecords)*100,2),'N2') As Day21Percentage,
--	   FORMAT(ROUND((Sum(A22Count)/@CountOfRecords)*100,2),'N2') As Day22Percentage,
--	   FORMAT(ROUND((Sum(A23Count)/@CountOfRecords)*100,2),'N2') As Day23Percentage,
--	   FORMAT(ROUND((Sum(A24Count)/@CountOfRecords)*100,2),'N2') As Day24Percentage,
--	   FORMAT(ROUND((Sum(A25Count)/@CountOfRecords)*100,2),'N2') As Day25Percentage,
--	   FORMAT(ROUND((Sum(A26Count)/@CountOfRecords)*100,2),'N2') As Day26Percentage,
--	   FORMAT(ROUND((Sum(A27Count)/@CountOfRecords)*100,2),'N2') As Day27Percentage,
--	   FORMAT(ROUND((Sum(A28Count)/@CountOfRecords)*100,2),'N2') As Day28Percentage,
--	   FORMAT(ROUND((Sum(A29Count)/@CountOfRecords)*100,2),'N2') As Day29Percentage,
--	   FORMAT(ROUND((Sum(A30Count)/@CountOfRecords)*100,2),'N2') As Day30Percentage,
--	   FORMAT(ROUND((Sum(A31Count)/@CountOfRecords)*100,2),'N2') As Day31Percentage
--From #TempCountDatas Group by A1count,A2Count,A3Count,A4Count,A5Count,A6Count,A7Count,A8Count,A9count,A10Count,A11Count,A12Count,A13Count,A14Count,A15Count,A16Count,A17Count,A18Count,A19Count,A20count,A21Count,A22Count,A23Count,A24Count,A25Count,A26Count,A27Count,A28Count,A29Count,A30Count,A31Count,name





drop Table #TempCountDatas

	end

	--SELECT * FROM #TempHeader
	
	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
	Drop Table #Ta_Tbl_levelDetail

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_DashboardDeviation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AuthOR:		<R.ManikANDan>
-- Create date: <17-Mar-2022 04:20 PM'
-- Description:	<Deviation DAShboard. SpecIFically developed fOR samsung client fOR blocking AND unblocking concept of card
-- Proc_Ta_DAShboardDeviation 'A','2022-08-17','',1,'superadmin',1,1,1,1,1,1,0,2022
-- Proc_Ta_DAShboardDeviation 'DD','2022-02-22','2022-02-23',1,'superadmin',NULL,1,0,0,0,0,0,2022
-- Proc_Ta_DAShboardDeviation 'BE','2022-03-25','20220317',1,'superadmin',NULL,1,0,0,0,0,1,2022
-- Proc_Ta_DAShboardDeviation 'WD','2022-02-22','20220317',1,'superadmin',NULL,1,0,0,0,0,1,2022
-- Proc_Ta_DAShboardDeviation 'MD','2022-02-22','20220317',1,'superadmin',NULL,1,0,0,0,0,0,2022
-- Proc_Ta_DAShboardDeviation 'QD','2022-02-22','20220317',1,'superadmin',NULL,1,0,0,0,0,0,2022
-- Proc_Ta_DAShboardDeviation 'ED','2022-02-22','20220317',1,'superadmin',NULL,1,0,0,0,0,0,2022

-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_DashboardDeviation]
	@Flag CHAR(4),
	@FROMDate DATETIME=NULL,
	@Todate DATETIME=NULL,
	@empAutoID BIGINT=NULL,
	@UserGroupName NVARCHAR(250)='IndividualUsers',
	@EmployeeCardNo VARCHAR(MAX)=NULL,
	@DailyChkbox INT,
	@PresentChkbox INT,
	@Weekly INT,
	@Quarterly INT,
	@absent INT,
	@isExport INT,
	@Year INT
AS
BEGIN
	print @Flag
	SET NOCOUNT ON;
	
	
	--Insert into TempValues values(@Flag,@FROMDate,@Todate,@empAutoID,@UserGroupName,@EmployeeCardNo,@DailyChkbox,@PresentChkbox,@Weekly,@Quarterly,@absent,@isExport,@Year)
	
	DECLARE @LocalFROMDate DATETIME=NULL
	DECLARE @LocalTodate DATETIME=NULL
	IF(@Todate='')
	SET @Todate=GETDATE()
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #LevelRights(LevelId INT)
	INSERT INTO  #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,0) AS LevelId 
	SET @EmployeeCardNo=isnull(@EmployeeCardNo,'')
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @Todate,@EmployeeCardNo,0  
	CREATE TABLE #TempDeviatedEmployees
	(
		AutoRecordID int identity(1,1),
		EmployeeAutoID BIGINT,
		EmployeeCardNo VARCHAR(50),
		EmployeeName VARCHAR(250),
		Company VARCHAR(250),
		Team VARCHAR(250),
		Department VARCHAR(250),
		Designation VARCHAR(250),
		BlockedDate date,
		BlockedTIME VARCHAR(10),
		DeviatedDate date, 
		DeviatedTIME VARCHAR(10),
		Reason VARCHAR(250),
		ReasonID int
	)
	CREATE TABLE #TempFinalCount(TotalEmployee INT,ReasonID INT,Reason VARCHAR(max),percentage DECIMAL(18,2),BlockedDate date)
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	FROM 
	(
		SELECT MAX(el.EffectiveDate) AS EffectiveDate, el.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		WHERE emp.IsDELETEd=0 
		AND (isnull(@EmployeeCardNo,'')='' OR emp.Employee_Code_Id=@EmployeeCardNo)
		GROUP BY el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cASt(@Todate AS nVARCHAR(50)),102) AND EL.LevelId IS NOT NULL
    ---Total Active Employees IN Employee mASter
    DECLARE @TotalEmployees INT
    SELECT @TotalEmployees=COUNT(*) FROM TA_Tbl_Employee E WHERE E.IsDELETEd=0 AND E.Employee_Status=1 AND Employee_Code_Id!='18000000'
	--Daily Deviation First LEFT Block    
	--Loading First TIME - All
	IF(@Flag='A' OR @Flag='DD')
	BEGIN
		DELETE FROM #TempDeviatedEmployees
		DELETE FROM #TempFinalCount
		IF(@Flag='A')
		BEGIN
			SET @LocalFROMDate=CONVERT(VARCHAR(11), DATEADD(D,-1,GETDATE()))
		END
		ELSE
		BEGIN
			SET @LocalFROMDate=@FROMDate
		END
		INSERT INTO #TempDeviatedEmployees
		SELECT	
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LAStName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				CONVERT(DATETIME,CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise))) BlockedDate,
				BlockedTIME=LEFT(right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),7),5)
		+' '+right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),2) ,
				CLK_DATE DeviatedDate,
				CLK_TIME DeviatedTIME,
				Policy_Topic=CASE	WHEN BEH.Daily=1		THEN '13 Hrs'
									WHEN BEH.DayWise=1		THEN '7th Day'
									WHEN BEH.WeekWise=1		THEN 'Week. 60 Hrs'
									WHEN BEH.QuarterWise=1	THEN 'Quart. 75 Hrs OT'
									WHEN BEH.ContinuousDayWise=1 THEN '7 Days Cont. Absent'
							 END,
				Policy_TopicID=CASE	WHEN BEH.Daily=1		THEN 1
									WHEN BEH.DayWise=1		THEN 2
									WHEN BEH.WeekWise=1		THEN 3
									WHEN BEH.QuarterWise=1	THEN 4
									WHEN BEH.ContinuousDayWise=1 THEN 5
							 END
		FROM Ta_tbl_BlockedEmployeesHistory BEH
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id=BEH.EmployeeCard
		INNER JOIN TA_Tbl_Clk_RawData rd ON (rd.CLK_CARDID=BEH.EmployeeCard AND 
		rd.CLK_DATE=CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)) AND CLK_TYPE=6402)
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		WHERE E.IsDELETEd=0 AND E.Employee_Status=1 
		AND E.Hostel=1
		AND (COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)>=@LocalFROMDate+' 00:01:00'
		AND COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)<=@LocalFROMDate+' 23:59:00')
		AND CLK_DATE IS NOT NULL
		INSERT INTO #TempFinalCount
		SELECT TotalDeviatedEmployees=COUNT(*),ReasonID,Reason,Percentage=CONVERT(DECIMAL(10,2),(COUNT(*)*1.0/@TotalEmployees)),BlockedDate
		FROM #TempDeviatedEmployees GROUP BY ReasonID,Reason,BlockedDate
		--To Bind all policies in chart.Added below lines of coding for loading chart for all policies. If any one policy is not available
		--That case, it will not load anything
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=1)
		BEGIN
		--Testing purpose inserted dummy values
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),1,'13 Hrs',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=2)
		BEGIN			
			INSERT INTO #TEMPFINALCOUNT VALUES(ROUND(RAND()*100,0),2,'7th Day',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=3)
		BEGIN			
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),3,'Week. 60 Hrs',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=4)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),4,'Quart. 75 Hrs OT',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=5)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),5,'7 Days Cont. Absent',0,@LocalFROMDate)
		END
		--Based ON the checkbox selection IN dashboard, the data need to be exported to excel. For that we included this line of coding
		IF(@DailyChkbox=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=1
		END
		IF(@PresentChkbox=0 AND @isExport=1)
		BEGIN			
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=2
		END
		IF(@Weekly=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=3
		END
		IF(@Quarterly=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=4
		END
		IF(@absent=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=5
		END
		IF(@isExport=0)
		BEGIN
			SELECT *,'Daily' FROM #TempFinalCount ORDER BY ReasonID
		END
		ELSE
		BEGIN
			SELECT [Employee Id]=EmployeeCardNo,[Employee Name]=EmployeeName,
			Team,Department,Designation,[Blocked Date]=CONVERT(VARCHAR(11),BlockedDate),[Blocked Time]=BlockedTIME,
			[Deviated Date]=CONVERT(VARCHAR(11),DeviatedDate),[Deviated Time]=DeviatedTIME,Reason,'Daily' FROM #TempDeviatedEmployees
			ORDER BY ReasonID
		END
	END
	---------------------------------------------------Daily Deviated Block Completed---------------------------------------------------
	---------------------------------------------------Previous Day Blocked Employees---------------------------------------------------
	--By Default it will show the current date blocked employees. i.e means, Morning session it will display night shift employees, evening
	--time it will display current date shift employees.
	IF(@Flag='A' OR @Flag='BE')
	BEGIN
		DELETE FROM #TempDeviatedEmployees
		DELETE FROM #TempFinalCount
		IF(@Flag='A')
		BEGIN
			SET @LocalFROMDate=CONVERT(VARCHAR(11), DATEADD(D,0,GETDATE()))
		END
		ELSE
		BEGIN
			SET @LocalFROMDate=@FROMDate
		END
		
		INSERT INTO #TempDeviatedEmployees
		SELECT	
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LAStName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				CONVERT(DATETIME,CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise))) BlockedDate,
				BlockedTIME=LEFT(right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),7),5)
		+' '+right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),2) ,
				NULL DeviatedDate,
				NULL DeviatedTIME,
				Policy_Topic=CASE	WHEN BEH.Daily=1		THEN '13 Hrs Exceed'
									WHEN BEH.DayWise=1		THEN '7 Days Continuous Present'
									WHEN BEH.WeekWise=1		THEN 'Weekly 60 Hrs Exceed'
									WHEN BEH.QuarterWise=1	THEN 'Quarterly 75 Hrs OT Exceed'
									WHEN BEH.ContinuousDayWise=1 THEN '7 Days Continuous Absent'
							 END,
				Policy_TopicID=CASE	WHEN BEH.Daily=1		THEN 1
									WHEN BEH.DayWise=1		THEN 2
									WHEN BEH.WeekWise=1		THEN 3
									WHEN BEH.QuarterWise=1	THEN 4
									WHEN BEH.ContinuousDayWise=1 THEN 5
									WHEN ISNULL(BEH.Daily,0)=0 THEN 0
							 END
		FROM Ta_tbl_BlockedEmployeesHistory BEH
		LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id=BEH.EmployeeCard
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		WHERE 
		E.IsDELETEd=0 AND E.Employee_Status=1 
		AND E.Hostel=1
		AND (COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)>=@LocalFROMDate+' 00:01:00'
		AND COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)<=@LocalFROMDate+' 23:59:00')
		AND (BEH.Daily=1 OR BEH.DayWise=1 OR BEH.WeekWise=1 OR BEH.QuarterWise=1 OR BEH.ContinuousDayWise=1)
		Insert into #TempDeviatedEmployees
		SELECT	
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LAStName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				@LocalFROMDate BlockedDate,
				BlockedTIME='',
				NULL DeviatedDate,
				NULL DeviatedTIME,
				Policy_Topic='Active Employees',
				Policy_TopicID=0
		FROM TA_Tbl_Employee E 
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		WHERE 
		E.IsDELETEd=0 AND E.Employee_Status=1 
		AND E.Employee_Code_Id not IN(SELECT EmployeeCardNo FROM #TempDeviatedEmployees)
		--SELECT * FROM #TempDeviatedEmployees
		INSERT INTO #TempFinalCount
		SELECT TotalDeviatedEmployees=COUNT(*),ReasonID,Reason,Percentage=CONVERT(DECIMAL(10,2),(COUNT(*)*1.0/@TotalEmployees)),BlockedDate
		FROM #TempDeviatedEmployees GROUP BY ReasonID,Reason,BlockedDate
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=0)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),0,'Active Employees',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=1)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),1,'13 Hrs Exceed',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=2)
		BEGIN			
			INSERT INTO #TEMPFINALCOUNT VALUES(ROUND(RAND()*100,0),2,'7 Days Continuous Present',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=3)
		BEGIN			
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),3,'Weekly 60 Hrs Exceed',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=4)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),4,'Quarterly 75 Hrs OT Exceed',0,@LocalFROMDate)
		END
		IF NOT EXISTS(SELECT TotalEmployee FROM #TempFinalCount WHERE ReasonID=5)
		BEGIN
			INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),5,'7 Days Continuous Absent',0,@FROMdate)
		END
		IF(@DailyChkbox=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=1
		END
		IF(@PresentChkbox=0 AND @isExport=1)
		BEGIN			
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=2
		END
		IF(@Weekly=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=3
		END
		IF(@Quarterly=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=4
		END
		IF(@absent=0 AND @isExport=1)
		BEGIN
			DELETE FROM #TempDeviatedEmployees WHERE ReasonID=5
		END
		IF(@isExport=0)
		BEGIN
			SELECT *,'Blocked' FROM #TempFinalCount ORDER BY ReasonID
		END
		ELSE
		BEGIN
			SELECT [Employee Id]=EmployeeCardNo,[Employee Name]=EmployeeName,
			Team,Department,Designation,[Blocked Date]=CONVERT(VARCHAR(11),BlockedDate),[Blocked Time]=BlockedTIME,
			[Deviated Date]=CONVERT(VARCHAR(11),DeviatedDate),[Deviated Time]=DeviatedTIME,Reason,'Blocked' FROM #TempDeviatedEmployees
			ORDER BY ReasonID
		END
		--return;
	END
	---------------------------------------------------Weekly Deviated Block Started---------------------------------------------------
	IF(@Flag='A' OR @Flag='WD')
	BEGIN
		DELETE FROM #TempDeviatedEmployees
		DELETE FROM #TempFinalCount
		SET @Todate=DATEADD(d,6,@FROMdate)+' 23:59:00'
		IF(@Todate>GETDATE())
		BEGIN
			SET @Todate=CONVERT(VARCHAR(11),GETDATE())+' 23:59:00'
		END
		INSERT INTO #TempDeviatedEmployees
		SELECT	
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LAStName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				CONVERT(DATETIME,CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise))) BlockedDate,
				BlockedTIME=LEFT(right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),7),5)
		+' '+right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)),100),2) ,
				CLK_DATE DeviatedDate,
				CLK_TIME DeviatedTIME,
				Policy_Topic=CASE	WHEN BEH.Daily=1		THEN 'Daily 13 Hrs Exceed'
									WHEN BEH.DayWise=1		THEN 'Continuous 7 Days Present'
									WHEN BEH.WeekWise=1		THEN 'Weekly 60 Hrs Exceed'
									--WHEN BEH.QuarterWise=1	THEN 'Quarterly 75 Hrs OT Exceed'
									WHEN BEH.ContinuousDayWise=1 THEN 'Continuous 7 Days Absent'
							 END,
				Policy_TopicID=CASE	WHEN BEH.Daily=1		THEN 1
									WHEN BEH.DayWise=1		THEN 2
									WHEN BEH.WeekWise=1		THEN 3
									--WHEN BEH.QuarterWise=1	THEN 4
									WHEN BEH.ContinuousDayWise=1 THEN 5
							 END
		FROM Ta_tbl_BlockedEmployeesHistORy BEH
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id=BEH.EmployeeCard
		Inner JOIN TA_Tbl_Clk_RawData rd ON (rd.CLK_CARDID=BEH.EmployeeCard AND rd.CLK_DATE=CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)) AND CLK_TYPE=6402)
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		WHERE 
		E.IsDELETEd=0 AND E.Employee_Status=1
		AND E.Hostel=1
		AND (COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)>=@FROMDate
		AND COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)<=@Todate)
		--AND CLK_DATE IS NOT NULL
		AND (BEH.Daily=1 OR BEH.DayWise=1 OR BEH.WeekWise=1 OR BEH.ContinuousDayWise=1)
		AND rd.CLK_DATE is not NULL
		IF(@isExport=0)
		BEGIN
			INSERT INTO #TempFinalCount
			SELECT TotalDeviatedEmployees=COUNT(*),ReasonID,Reason,Percentage=CONVERT(DECIMAL(10,2),(COUNT(*)*1.0/@TotalEmployees)),BlockedDate
			FROM #TempDeviatedEmployees GROUP BY ReasonID,Reason,BlockedDate
			WHILE @Todate>=@FROMDate
			BEGIN				
				IF NOT EXISTS(SELECT Reason FROM #TempFinalCount where BlockedDate=CONVERT(VARCHAR(11),DATEADD(d,0,@Todate)) AND ReasonID=1)
				BEGIN
					INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),1,'Daily 13 Hrs Exceed',0,DATEADD(d,0,@Todate))				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempFinalCount where BlockedDate=CONVERT(VARCHAR(11),DATEADD(d,0,@Todate))AND ReasonID=2)
				BEGIN
					INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),2,'Continuous 7 Days Present',0,DATEADD(d,0,@Todate))				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempFinalCount where BlockedDate=CONVERT(VARCHAR(11),DATEADD(d,0,@Todate))AND ReasonID=3)
				BEGIN
					INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),3,'Weekly 60 Hrs Exceed',0,DATEADD(d,0,@Todate))				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempFinalCount where BlockedDate=CONVERT(VARCHAR(11),DATEADD(d,0,@Todate)) AND ReasonID=5)
				BEGIN
					INSERT INTO #TempFinalCount VALUES(ROUND(RAND()*100,0),5,'Continuous 7 Days Absent',0,DATEADD(d,0,@Todate))				
				END
				SET @Todate=DATEADD(d,-1,@Todate)
			END
			--SELECT * FROM #TempFinalCount
			SELECT TotalEmployee ,ReasonID ,Reason ,percentage ,
			[Blocked Date]=CONVERT(VARCHAR(2),Day(CONVERT(VARCHAR(11),BlockedDate)))+'-'+CONVERT(VARCHAR(2),Month(CONVERT(VARCHAR(11),BlockedDate))),
			'Weekly' FROM #TempFinalCount
			ORDER BY ReasonID,BlockedDate
		END
		ELSE
		BEGIN
			IF(@DailyChkbox=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=1
			END
			IF(@PresentChkbox=0 AND @isExport=1)
			BEGIN			
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=2
			END
			IF(@Weekly=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=3
			END
			IF(@Quarterly=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=4
			END
			IF(@absent=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=5
			END
			SELECT [Employee Id]=EmployeeCardNo,[Employee Name]=EmployeeName,
			Team,Department,Designation,[Blocked Date]=CONVERT(VARCHAR(11),BlockedDate),
			[Blocked Time]=BlockedTIME,[Deviated Date]=CONVERT(VARCHAR(11),DeviatedDate),[Deviated Time]=DeviatedTIME,Reason 
			FROM #TempDeviatedEmployees ORDER BY ReasonID,BlockedDate
		END
	END
	---------------------------------------------------Weekly Deviated Block Completed---------------------------------------------------
	---------------------------------------------------Monthly Deviated Block Started---------------------------------------------------
	IF(@Flag='A' OR @Flag='MD')
	BEGIN
		DELETE FROM #TempDeviatedEmployees
		DELETE FROM #TempFinalCount
		DECLARE @YearsettingFromDate DATETIME
		DECLARE @YearsettingToDate DATETIME
		SELECT @YearsettingFromDate= CONVERT(VARCHAR(4),@Year)+'/01/01 00:00:01'
		SELECT @YearsettingToDate=CONVERT(VARCHAR(4),@Year)+'/12/31 23:59:59'
		INSERT INTO #TempDeviatedEmployees
		SELECT	
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LastName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				CONVERT(DATETIME,CONVERT(VARCHAR(11),COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise))) BlockedDate,
				BlockedTime=LEFT(right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise)),100),7),5)
		+' '+right('0'+CONVERT(VARCHAR(15),CONVERT(TIME,COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise)),100),2) ,
				CLK_DATE DeviatedDate,
				CLK_TIME DeviatedTime,
				Policy_Topic=CASE	WHEN BEH.Daily=1		THEN 'Daily 13 Hrs Exceed'
									WHEN BEH.DayWise=1		THEN 'Continuous 7 Days Present'
									WHEN BEH.WeekWise=1		THEN 'Weekly 60 Hrs Exceed'
									WHEN BEH.QuarterWise=1	THEN 'Quarterly 75 Hrs OT Exceed'
									WHEN BEH.ContinuousDayWise=1 THEN 'Continuous 7 Days Absent'
							 END,
				Policy_TopicID=CASE	WHEN BEH.Daily=1		THEN 1
									WHEN BEH.DayWise=1		THEN 2
									WHEN BEH.WeekWise=1		THEN 3
									WHEN BEH.QuarterWise=1	THEN 4
									WHEN BEH.ContinuousDayWise=1 THEN 5
							 END
		FROM Ta_tbl_BlockedEmployeesHistory BEH
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id=BEH.EmployeeCard
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		LEFT OUTER JOIN TA_Tbl_Clk_RawData rd ON (rd.CLK_CARDID=BEH.EmployeeCard AND rd.CLK_DATE=CONVERT(VARCHAR(11),COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise)) AND CLK_TYPE=6402)
		WHERE 
		E.IsDELETEd=0 AND E.Employee_Status=1
		AND (COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise)>=@YearsettingFromDate
		AND COALESCE(BEH.WhenBlocked_Daily,BEH.WhenBlocked_DayWise,BEH.WhenBlocked_WeekWise)<=@YearsettingToDate)
		AND CLK_DATE is not null
		AND (BEH.Daily=1 OR BEH.DayWise=1 OR BEH.WeekWise=1 OR BEH.ContinuousDayWise=1)
		IF(@isExport=0)
		BEGIN
			CREATE TABLE #TempMonthlyDeviatedEmployees(TotalEmployee INT,ReasonID INT,Reason VARCHAR(max),percentage DECIMAL(18,2),BlockingMonth INT)
			INSERT INTO #TempMonthlyDeviatedEmployees
			SELECT TotalDeviatedEmployees=COUNT(*),ReasonID,Reason,Percentage=CONVERT(DECIMAL(10,2),(COUNT(*)*1.0/@TotalEmployees)),MONTH(BlockedDate)
			FROM #TempDeviatedEmployees GROUP BY ReasonID,Reason,month(BlockedDate)
			DECLARE @start INT
			DECLARE @END INT
			SET @start=MONTH(@YearsettingFromDate)
			SET @END=CASE WHEN MONTH(@YearsettingToDate)>MONTH(GETDATE()) THEN MONTH(GETDATE()) ELSE MONTH(@YearsettingToDate) END
			SET @END=12
			WHILE @END>=@start
			BEGIN
				IF NOT EXISTS(SELECT Reason FROM #TempMonthlyDeviatedEmployees WHERE BlockingMonth=@END AND ReasonID=1)
				BEGIN
					INSERT INTO #TempMonthlyDeviatedEmployees VALUES(ROUND(RAND()*100,0),1,'Daily 13 Hrs Exceed',0,@END)				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempMonthlyDeviatedEmployees WHERE BlockingMonth=@END AND ReasonID=2)
				BEGIN
					INSERT INTO #TempMonthlyDeviatedEmployees VALUES(ROUND(RAND()*100,0),2,'Continuous 7 Days Present',0,@END)				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempMonthlyDeviatedEmployees WHERE BlockingMonth=@END AND ReasonID=3)
				BEGIN
					INSERT INTO #TempMonthlyDeviatedEmployees VALUES(ROUND(RAND()*100,0),3,'Weekly 60 Hrs Exceed',0,@END)				
				END
				IF NOT EXISTS(SELECT Reason FROM #TempMonthlyDeviatedEmployees WHERE BlockingMonth=@END AND ReasonID=5)
				BEGIN
					INSERT INTO #TempMonthlyDeviatedEmployees VALUES(ROUND(RAND()*100,0),5,'Continuous 7 Days Absent',0,@END)				
				END
				SET @END=@END-1
			END
			--SELECT @YearsettingFromDate,@YearsettingToDate
			SELECT TotalEmployee ,ReasonID ,Reason ,percentage ,[Blocked Date]=
			CASE WHEN CONVERT(VARCHAR(11),BlockingMonth)=1 THEN 'Ja'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=2 THEN 'F'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=3 THEN 'M'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=4 THEN 'Ap'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=5 THEN 'Ma'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=6 THEN 'J'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=7 THEN 'Ju'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=8 THEN 'Au'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=9 THEN 'Se'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=10 THEN 'O'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=11 THEN 'N'
				 WHEN CONVERT(VARCHAR(11),BlockingMonth)=12 THEN 'D'
			END
			--+'-'+ RIGHT(@year,2)
			,'Monthly' FROM #TempMonthlyDeviatedEmployees
			ORDER BY ReasonID,BlockingMonth
			DROP TABLE #TempMonthlyDeviatedEmployees
		END
		ELSE
		BEGIN
			IF(@DailyChkbox=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=1
			END
			IF(@PresentChkbox=0 AND @isExport=1)
			BEGIN			
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=2
			END
			IF(@Weekly=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=3
			END
			IF(@Quarterly=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=4
			END
			IF(@absent=0 AND @isExport=1)
			BEGIN
				DELETE FROM #TempDeviatedEmployees WHERE ReasonID=5
			END
			SELECT [Employee Id]=EmployeeCardNo,[Employee Name]=EmployeeName,
			Team,Department,Designation,[Blocked Date]=CONVERT(VARCHAR(11),BlockedDate),
			[Blocked Time]=BlockedTIME,[Deviated Date]=CONVERT(VARCHAR(11),DeviatedDate),[Deviated Time]=DeviatedTIME,Reason,
			'Monthly' FROM #TempDeviatedEmployees ORDER BY ReasonID
		END
	END
	---------------------------------------------------Monthly Deviated Block Completed---------------------------------------------------
	---------------------------------------------------Quarterly Deviated Block Started---------------------------------------------------
	IF(@Flag='A' OR @Flag='QD')
	BEGIN
		DELETE FROM #TempDeviatedEmployees
		DELETE FROM #TempFinalCount
		DECLARE @FinancialYear_FROMDate DATETIME
		DECLARE @FinancialYear_Todate DATETIME
		DECLARE @multiply_Factor float
		SELECT @FinancialYear_FROMDate=FROMDate,@FinancialYear_Todate=@FinancialYear_Todate FROM TA_Tbl_YearSETting WHERE IsActive=1
		SELECT @multiply_Factor= 
				case	WHEN DATEPART(month,@FROMDate) IN(1,2,3,4) THEN 1 
						WHEN DATEPART(month,@FROMDate) IN(5,6,7,8) THEN 2
						WHEN DATEPART(month,@FROMDate) IN(9,10,11,12) THEN 3
				END
		SET @Todate=@FROMDate
		SELECT @FromDate=
			CASE	WHEN @multiply_Factor=1 THEN DATEADD(m,0,@FinancialYear_FromDate)
					WHEN @multiply_Factor=2 THEN DATEADD(m,4,@FinancialYear_FromDate)
					WHEN @multiply_Factor=3 THEN DATEADD(m,8,@FinancialYear_FromDate)
			END
		INSERT INTO #TempDeviatedEmployees
		SELECT	DISTINCT
				E.Employee_Id,
				E.Employee_Code_Id,
				EmployeeName=ISNULL(E.Employee_FirstName,'') +ISNULL(E.Employee_MiddleName,'')+ISNULL(E.Employee_LAStName,''),
				ldc.name company,
				ldt.name AS Team,
				ld.name AS Department,
				T.TitleName AS Designation,
				CONVERT(DATETIME,CONVERT(VARCHAR(11),COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise))) BlockedDate,
				BlockedTIME=NULL,
				NULL DeviatedDate,
				NULL DeviatedTIME,
				Policy_Topic=CASE WHEN BEH.QuarterWise=1	THEN 'Quarterly 75 Hrs OT Exceed'END,
				Policy_TopicID=CASE	WHEN BEH.QuarterWise=1	THEN 4 END
		FROM Ta_tbl_BlockedEmployeesHistORy BEH
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id=BEH.EmployeeCard
		INNER JOIN #EmpLevel TEL ON E.Employee_Id=TEL.EmployeeId
		INNER JOIN #LevelRights lr ON TEL.LevelId=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ld ON ld.id=lr.LevelId
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldt ON ld.parentId=ldt.id
		LEFT OUTER JOIN Ta_Tbl_levelDetails ldc ON ldt.parentId=ldc.id
		INNER JOIN #EmpDesignation TED ON TED.EmployeeId=E.Employee_Id
		INNER JOIN TA_Tbl_Title T ON T.TitleId=TED.DesignationId
		WHERE 
		E.Hostel=1 AND
		E.IsDELETEd=0 AND E.Employee_Status=1
		AND (COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)>=@FROMDate
		AND COALESCE(BEH.WHENBlocked_Daily,BEH.WHENBlocked_DayWise,BEH.WHENBlocked_WeekWise)<=@Todate)
		AND (BEH.QuarterWise=1)
		delete FROM #TempDeviatedEmployees where AutoRecordID IN(
		SELECT AutoRecordID FROM (
			SELECT AutoRecordID,row=ROW_NUMBER()over(partition by employeecardno,month(blockeddate) ORDER BY employeecardno) FROM #TempDeviatedEmployees
		)AS a where row>1)
		IF(@isExport=0)
		BEGIN
			CREATE TABLE #TempFinalCount1(TotalEmployee INT,ReasonID INT,Reason VARCHAR(max),percentage DECIMAL(18,2),BlockedMonth varchar(10))
			INSERT INTO #TempFinalCount1
			SELECT TotalDeviatedEmployees=COUNT(*),ReasonID,Reason,Percentage=CONVERT(DECIMAL(10,2),(COUNT(*)*1.0/@TotalEmployees)),DATEPART(month,BlockedDate)
			FROM #TempDeviatedEmployees GROUP BY ReasonID,Reason,DATEPART(month,BlockedDate)
			DECLARE @i INT
			IF(@multiply_Factor=1)
			BEGIN
				SET @i=1
			END
			ELSE IF(@multiply_Factor=2)
			BEGIN
				SET @i=5
			END
			ELSE IF(@multiply_Factor=3)
			BEGIN
				SET @i=9
			END
			declare @j int
			set @j=1;
			WHILE @i<=MONTH(@Todate)+2
			BEGIN
				IF NOT EXISTS(SELECT Reason FROM #TempFinalCount1 where BlockedMonth=convert(varchar(20),@i) AND ReasonID=4)
				BEGIN
					INSERT INTO #TempFinalCount1 VALUES(ROUND(RAND()*100,0),4,'Quarterly 75 Hrs OT Exceed',0,'Q'+CONVERT(varchar(20), @j))
				END
				set @j=@j+1
				SET @i=@i+1
				
			END
			SELECT TotalEmployee,ReasonID,Reason,percentage,[Blocked Date]=BlockedMonth,'Quarterly' FROM #TempFinalCount1
			ORDER BY ReasonID,[Blocked Date]
			SELECT TotalEmployee_Quarter=sum(isnull(TotalEmployee,0)) FROM #TempFinalCount1 
			DROP TABLE #TempFinalCount1 
		END
		ELSE
		BEGIN
			SELECT [Employee Id]=EmployeeCardNo,[Employee Name]=EmployeeName,
			Team,Department,Designation,[Blocked Date]=CONVERT(VARCHAR(11),BlockedDate),[Blocked Time]=BlockedTIME,
			[Deviated Date]=CONVERT(VARCHAR(11),DeviatedDate),[Deviated Time]=DeviatedTIME,Reason,'Quarterly' FROM #TempDeviatedEmployees
			ORDER BY ReasonID,[Blocked Date]
		END
	END
	IF(@Flag='A' OR @Flag='ED')
	BEGIN
		Execute Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails NULL,'A'
	END
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #LevelRights
	DROP TABLE #TempDeviatedEmployees
	DROP TABLE #TempFinalCount
	--DROP TABLE #TempMonthlyDeviatedEmployees
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DashBoardYear]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_DashBoardYear]


AS
BEGIN
	
	Select YearSettings_Id,StartYear from TA_Tbl_YearSetting

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DataBaseArcheive]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <12-Mar-2012>
-- Description:	<Move the Data to database archive>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DataBaseArcheive]
	-- Add the parameters for the stored procedure here
	@Month INT,
	@Year INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupProcesseddata')
		BEGIN
			CREATE TABLE [dbo].[TA_Tbl_ProcessedData](
			[Process_Rec_ID] [bigint] IDENTITY(1,1) NOT NULL,
			[Employee_Code_Id] [nvarchar](20) NULL,
			[Date] [datetime] NULL,
			[Shift_Id] [int] NULL,
			[InTime] [nvarchar](25) NULL,
			[OutTime] [nvarchar](25) NULL,
			[HrsWork] [nvarchar](10) NULL,
			[HrsOT] [nvarchar](10) NULL,
			[NormOT] [nvarchar](10) NULL,
			[OffOT] [nvarchar](10) NULL,
			[HolOT] [nvarchar](10) NULL,
			[EarlyOut] [nvarchar](10) NULL,
			[LateIn] [nvarchar](10) NULL,
			[Attendance] [nvarchar](20) NULL,
			[WorkHrs] [nvarchar](10) NULL,
			[HrsLess] [nvarchar](10) NULL,
			[HrsExtra] [nvarchar](10) NULL,
			[LateInMins] [float] NULL,
			[EarlyOutMins] [float] NULL,
			[ExtraMins] [float] NULL,
			[OtMins] [float] NULL,
			[OvertimeStatus] [nvarchar](50) NULL,
			[TotalDays] [numeric](18, 1) NULL,
			[LeaveCode] [nvarchar](20) NULL,
			[LateEntryReason] [nvarchar](260) NULL,
			[EarlyOutReason] [nvarchar](260) NULL,
			[ProcessFlag] [bit] NULL,
			[Status] [nvarchar](50) NULL,
			[FNAttendanceCode] [nvarchar](15) NULL,
			[ANAttendanceCode] [nvarchar](15) NULL)
			IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupClk_RawData')
				begin
					CREATE TABLE [dbo].[TA_Tbl_Clk_RawData](
					[CLK_ID] [bigint] IDENTITY(1,1) NOT NULL,
					[CLK_CARDID] [nvarchar](20) NULL,
					[CLK_DEVICEID] [nvarchar](20) NULL,
					[CLK_DATE] [datetime] NULL,
					[CLK_TIME] [nvarchar](25) NULL,
					[CLK_TYPE] [nvarchar](15) NULL,
					[CLK_FLAG] [int] NULL,
					[CLK_PROCESS] [int] NULL,
					[TimecheckDateTime] [datetime] NULL,
					[TimeStamp] [datetime] NOT NULL)
					IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupClockDetails')
						begin
						CREATE TABLE [dbo].[TA_Tbl_ClockDetails](
						[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
						[Clk_CompId] [nvarchar](10) NULL,
						[Clk_EmpId] [nvarchar](20) NULL,
						[Clk_InDeviceId] [nvarchar](20) NULL,
						[Clk_InDate] [datetime] NULL,
						[Clk_InTime] [datetime] NULL,
						[Clk_InPunchType] [nvarchar](25) NULL,
						[Clk_OutDeviceId] [nvarchar](20) NULL,
						[Clk_OutDate] [datetime] NULL,
						[Clk_OutTime] [datetime] NULL,
						[Clk_OutPunchType] [nvarchar](25) NULL,
						[Clk_Process] [nvarchar](1) NULL,
						[Clk_Remarks] [nvarchar](100) NULL,
						[Clk_User] [nvarchar](20) NULL,
						[Clk_Date] [datetime] NULL,
						[Clk_Status] [nvarchar](1) NULL,
						[IsVoid] [bit] NULL)
							IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupManualTimeEntry')
								begin
									CREATE TABLE [dbo].[Ta_Tbl_ManualTimeEntry](
									[ManualTimeEntry_Id] [int] IDENTITY(1,1) NOT NULL,
									[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
									[ManualTimeEntry_Date] [datetime] NULL,
									[ManualTimeEntry_InDate] [datetime] NULL,
									[ManualTimeEntry_InTime] [nvarchar](50) NULL,
									[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
									[ManualTimeEntry_OutDate] [datetime] NULL,
									[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
									[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
									[ManualTimeEntry_InReaderID] [int] NULL,
									[ManualTimeEntry_OutReaderID] [int] NULL,
									[ManualTimeEntry_Reason] [nvarchar](255) NULL,
									[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
									[Route_Id] [int] NULL,
									[Clk_Process] [nvarchar](1) NULL,
									[ManualTimeEntry_Status] [nvarchar](25) NULL,
									[Isdeleted] [bit] NULL,
									[TimeStamp] [datetime] NULL,
									[Emp_Id] [int] NULL,
									[YearSettings_Id] [int] NULL,
									[IsDiscrepancyEntry] [bit] NULL,
									[IsOnDuty] [bit] NULL
								)
									IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupLeaveApplication')
										begin
											CREATE TABLE [dbo].[TA_Tbl_LeaveApplication](
											[LeaveApplication_Id] [int] IDENTITY(1,1) NOT NULL,
											[Employee_Id] [nvarchar](20) NOT NULL,
											[Leave_ApplicationDate] [datetime] NOT NULL,
											[LeaveType_id] [int] NOT NULL,
											[Type] [nvarchar](50) NOT NULL,
											[Leave_FromDate] [datetime] NOT NULL,
											[Leave_ToDate] [datetime] NOT NULL,
											[Leave_SessionFrom] [nvarchar](50) NOT NULL,
											[Leave_SessionTo] [nvarchar](50) NOT NULL,
											[NumberOfDays] [decimal](18, 1) NOT NULL,
											[Reason] [nvarchar](250) NULL,
											[Status] [nvarchar](50) NULL,
											[IsDeleted] [bit] NOT NULL,
											[Remarks] [nvarchar](250) NULL,
											[IsBorrow] [bit] NULL,
											[Emp_Id] [int] NULL,
											[YearSettings_Id] [int] NULL,
											[CompanyId] [int] NULL,
											[Successiveyear] [bit] NULL)
											IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_BackupPermission')	
												begin
												CREATE TABLE [dbo].[TA_Tbl_Permission](
												[Permission_Id] [int] IDENTITY(1,1) NOT NULL,
												[Employee_Id] [int] NOT NULL,
												[Permission_AppliedDate] [datetime] NOT NULL,
												[Permission_Date] [datetime] NOT NULL,
												[Permission_Type] [nvarchar](50) NULL,
												[Permission_FromTime] [datetime] NOT NULL,
												[Permission_ToTime] [datetime] NOT NULL,
												[Permission_Reason] [nvarchar](250) NOT NULL,
												[Permission_Status] [nvarchar](50) NULL,
												[Emp_Id_Sanction] [int] NULL,
												[Remarks] [nvarchar](250) NULL,
												[IsDeleted] [bit] NOT NULL,
												[TimeStamp] [datetime] NOT NULL,
												[Emp_Id] [int] NULL,
												[YearSettings_Id] [int] NULL,
												[No_Of_Hours] [nvarchar](10) NULL)
													IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_Backup_PermanentShiftAllocation')			
														begin
															CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocation](
															[EmployeeId] [int] NOT NULL,
															[Year] [int] NOT NULL,
															[Month] [int] NOT NULL,
															[Day1Shift] [int] NOT NULL,
															[Day2Shift] [int] NOT NULL,
															[Day3Shift] [int] NOT NULL,
															[Day4Shift] [int] NOT NULL,
															[Day5Shift] [int] NOT NULL,
															[Day6Shift] [int] NOT NULL,
															[Day7Shift] [int] NOT NULL,
															[Day8Shift] [int] NOT NULL,
															[Day9Shift] [int] NOT NULL,
															[Day10Shift] [int] NOT NULL,
															[Day11Shift] [int] NOT NULL,
															[Day12Shift] [int] NOT NULL,
															[Day13Shift] [int] NOT NULL,
															[Day14Shift] [int] NOT NULL,
															[Day15Shift] [int] NOT NULL,
															[Day16Shift] [int] NOT NULL,
															[Day17Shift] [int] NOT NULL,
															[Day18Shift] [int] NOT NULL,
															[Day19Shift] [int] NOT NULL,
															[Day20Shift] [int] NOT NULL,
															[Day21Shift] [int] NOT NULL,
															[Day22Shift] [int] NOT NULL,
															[Day23Shift] [int] NOT NULL,
															[Day24Shift] [int] NOT NULL,
															[Day25Shift] [int] NOT NULL,
															[Day26Shift] [int] NOT NULL,
															[Day27Shift] [int] NOT NULL,
															[Day28Shift] [int] NOT NULL,
															[Day29Shift] [int] NOT NULL,
															[Day30Shift] [int] NOT NULL,
															[Day31Shift] [int] NOT NULL,
															[Emp_Id] [int] NOT NULL,
															[TimeStamp] [datetime] NOT NULL,
															[DateShift] [datetime] NOT NULL)
															IF NOT EXISTS(select * from sys.tables WHERE NAME='TA_Tbl_Backup_TemporaryShiftAllocation')	
																begin
																	CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation](
																	[EmployeeId] [int] NOT NULL,
																	[Year] [int] NOT NULL,
																	[Month] [int] NOT NULL,
																	[Day1Shift] [int] NOT NULL,
																	[Day2Shift] [int] NOT NULL,
																	[Day3Shift] [int] NOT NULL,
																	[Day4Shift] [int] NOT NULL,
																	[Day5Shift] [int] NOT NULL,
																	[Day6Shift] [int] NOT NULL,
																	[Day7Shift] [int] NOT NULL,
																	[Day8Shift] [int] NOT NULL,
																	[Day9Shift] [int] NOT NULL,
																	[Day10Shift] [int] NOT NULL,
																	[Day11Shift] [int] NOT NULL,
																	[Day12Shift] [int] NOT NULL,
																	[Day13Shift] [int] NOT NULL,
																	[Day14Shift] [int] NOT NULL,
																	[Day15Shift] [int] NOT NULL,
																	[Day16Shift] [int] NOT NULL,
																	[Day17Shift] [int] NOT NULL,
																	[Day18Shift] [int] NOT NULL,
																	[Day19Shift] [int] NOT NULL,
																	[Day20Shift] [int] NOT NULL,
																	[Day21Shift] [int] NOT NULL,
																	[Day22Shift] [int] NOT NULL,
																	[Day23Shift] [int] NOT NULL,
																	[Day24Shift] [int] NOT NULL,
																	[Day25Shift] [int] NOT NULL,
																	[Day26Shift] [int] NOT NULL,
																	[Day27Shift] [int] NOT NULL,
																	[Day28Shift] [int] NOT NULL,
																	[Day29Shift] [int] NOT NULL,
																	[Day30Shift] [int] NOT NULL,
																	[Day31Shift] [int] NOT NULL,
																	[Emp_Id] [int] NOT NULL,
																	[TimeStamp] [datetime] NOT NULL,
																	[DateShift] [datetime] NOT NULL
																) 
																enD			
														end
												end
										end
								end
						end
				end
		END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupProcesseddata WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year AND PROCESSFLAG=0)
					BEGIN
						select 'UnProcesseddataExists' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupProcesseddata 
						SELECT * FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year
						DELETE FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year
						SELECT 'Success'
					END
			END
		ELSE
			BEGIN
				SELECT 'ProcesseddataExists'
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupClk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year AND CLK_FLAG = 0 AND CLK_PROCESS =0)
					BEGIN
						SELECT 'UnProcessed_Clk_Dataexists' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupClk_RawData
						SELECT * FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
						DELETE FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
						SELECT 'Success'
					END
			END
		ELSE
			BEGIN
				SELECT 'Clk_RawdataExists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year)
			BEGIN
				INSERT INTO TA_Tbl_BackupClockDetails
				SELECT * FROM TA_Tbl_ClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
				DELETE FROM TA_Tbl_ClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
				SELECT 'Success'
			END
		ELSE
			BEGIN
				SELECT 'ClockDetailsExists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
		AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
				AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year AND CLK_PROCESS <> 'N' AND (ManualTimeentry_status <> 'Approved' or 
				ManualTimeentry_status <> 'Rejected'))
					BEGIN
						SELECT 'UnprocessedManualEntryExists' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupManualTimeEntry
						SELECT * FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
						AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year
						DELETE FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
						AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year
						SELECT 'Success'
					END
			END
		ELSE
			BEGIN
				SELECT 'ManualEntryExists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupLeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year AND (STATUS<>'Approved' OR STATUS<> 'Rejected'))
					begin
						SELECT 'UnProcessedLeaveExists' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupLeaveApplication
						SELECT * FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year
						DELETE FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year
						SELECT 'Success'
					END
			END	
		ELSE
			BEGIN
				SELECT 'Leavedataexists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year AND (Permission_Status <> 'Approved' or Permission_Status <> 'Rejected'))
					begin
						select 'UnprocessedPermissionExists' as Alert
					end
				else	
					begin
						INSERT INTO TA_Tbl_BackupPermission
						SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year
						DELETE FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year
						SELECT 'Success'
					end
			END	
		ELSE
			BEGIN
				SELECT 'PermissionExists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Backup_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month)
			BEGIN
				INSERT INTO TA_Tbl_BackupPermission
				SELECT * FROM TA_Tbl_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				DELETE FROM TA_Tbl_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				SELECT 'Success'
			END
		ELSE
			BEGIN
				SELECT 'PermanentShiftallocatioExists' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Backup_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month)
			BEGIN
				INSERT INTO TA_Tbl_Backup_TemporaryShiftAllocation
				SELECT * FROM TA_Tbl_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				DELETE FROM TA_Tbl_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				SELECT 'Success'
			END
		ELSE
			BEGIN
				SELECT 'TemporaryShiftallocatioExists' as Alert
			END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DataReprocessInsertforAudit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_DataReprocessInsertforAudit]
@FromDate datetime = '',
@ToDate datetime = '',
@EmployeeID int =''
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
   declare @RecordCount int
   Set @RecordCount =(Select Count (*) as Count from TA_Tbl_TempShiftAllocation)
   print @RecordCount
   Insert into TA_Tbl_ProcessedDataTrigger Values (@RecordCount,@FromDate,@ToDate,@EmployeeID,'Insert')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormat]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_DateandTimeFormat  
Description : select date and time format
Tables Included : TA_Tbl_DateandTimeFormat  
Created By : S.Christopher  
Created On : 10-Oct-07
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DateandTimeFormat] 
AS
BEGIN
	SET NOCOUNT ON;
	SELECT DateFormat, TimeFormat,isdomain,DomainName,DomainAdminUserName,DomainAdminPassword FROM TA_Tbl_DateandTimeFormat
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormatUpdation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_DateandTimeFormatUpdation  
Description : update the table TA_Tbl_DateandTimeFormat
Tables Included : TA_Tbl_DateandTimeFormat  
Created By : S.Christopher  
Created On : 10-Oct-07
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DateandTimeFormatUpdation]   
 -- Add the parameters for the stored procedure here  
    @DateFormat varchar(15),   
    @TimeFormat varchar(15),  
    @isDomain int,
    @DomainName nvarchar(500),
    @DomainAdminUserName nvarchar(500),
    @DomainAdminPassword nvarchar(1000),
    @EmpId int  
AS  
declare @sql as nvarchar(3000)
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
    -- Insert statements for procedure here  
 if(select count(*) from TA_Tbl_DateandTimeFormat)>0  
begin
     --update TA_Tbl_DateandTimeFormat set DateFormat = @DateFormat, TimeFormat = @TimeFormat, Time_Stamp = getdate(), EmpId = @EmpId  
set @sql='update TA_Tbl_DateandTimeFormat set DateFormat =N''' +  @DateFormat + ''', TimeFormat =N''' + @TimeFormat + ''', Time_Stamp =''' + cast(getdate() as varchar(25)) + ''', Emp_Id =''' + cast(@EmpId as varchar(25)) + ''', isDomain='+ cast(@isDomain as varchar(25)) +', DomainName=N''' + @DomainName + ''', DomainAdminUserName=N''' + @DomainAdminUserName + ''', DomainAdminPassword=N''' + @DomainAdminPassword + '''' 
exec(@sql)
end
 else
begin  
   set @sql='insert into TA_Tbl_DateandTimeFormat(DateFormat, TimeFormat, Time_Stamp, Emp_Id, isDomain, DomainName, DomainAdminUserName, DomainAdminPassword) values(N''' + @DateFormat + ''',N''' + @TimeFormat + ''',''' + cast(getdate() as varchar(25)) + ''',''' + cast(@EmpId as varchar(25)) + ''',''' + cast(@isDomain as varchar(25)) + ''' ,''' + @DomainName + ''',''' + @DomainAdminUserName + ''',''' + @DomainAdminPassword + ''') '
exec(@sql)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateDifference]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_DateDifference  
Description : Proc to find the months diffrences between from and to date.
Tables Included : Nil  
Created By : Abul  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Proc [dbo].[Proc_TA_DateDifference]
@FromDate datetime,
@ToDate datetime
As
select datediff(mm, @FromDate, @ToDate)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_delEmployee]
(    
	@EmpID int    
)    
as    
begin    
	declare @checkFlag  int    
	set @checkFlag = 0    
	declare @recCount as int    
	declare @recCount1 as int  
	declare @recCount2 as int  
	declare @recCount3 as int  
	declare @recCount5 as int
	declare @recCount6 as int 
	declare @recCount7 as int 
	select @recCount=count(*) from Ta_Tbl_Employee where Reporting_to=@EmpID and isdeleted=0
	select @recCount1 = count(*) from Ta_Tbl_Employee where Leave_Sanc_Authority=@EmpID and isdeleted=0
	select @recCount2 = count(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmpID and isdeleted=0
	select @recCount3 = count(*) from TA_Tbl_Permission where Employee_Id=@EmpID and isdeleted=0
	select @recCount5 = count(*) from ta_Tbl_permanentshiftallocation where employeeid=@EmpID
	select @recCount6 = count(*) from ta_Tbl_temporaryshiftallocation where employeeid=@EmpID
	select @recCount7= count(*) from TA_Tbl_EmployeeBonusLeave where EmployeeId=@EmpID
	if (@recCount>0 or @recCount1>0 or @recCount2>0 or @recCount3>0 or @recCount5>0 or @recCount6>0 or @recCount7>0)
		Begin    
			set @checkFlag=1    
		End
	select @checkFlag as checkFlag    
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Delete_CompanyDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <22-09-2013,04.13 PM,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Delete_CompanyDetailsForService]
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM Ta_Tbl_DataProcessCompanyLevelTemp
END
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_Delete_LeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*  
Procedure Name : proc_TA_Delete_LeaveType  
Description : delete leave type  
Tables Included : tbl_TA_LeaveType  
Created By : Arun Vinoth
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[proc_TA_Delete_LeaveType]
(@LeaveId int)
AS
begin
set NOCOUNT ON;
Delete From tbl_TA_LeaveType Where LeaveId=@LeaveId
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Author : Kumuthini.L
-- Procedure Name : Proc_TA_DeleteAccessDeniedSettingEntries
-- Tables Used : TA_Tbl_AccessDeniedSettings
-- Created On : 13-Mar-2008
-- Purpose : Used to delete the Access Denied Entries
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]
(
    @AccessDeniedIds NVARCHAR(1000)
)
AS
BEGIN
    DELETE FROM TA_Tbl_AccessDeniedSettings WHERE AccessDenied_Id IN (@AccessDeniedIds)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAddlWeekoff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_DeleteAddlWeekoff  
Description : delete additional week off - in activate
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P 
Created On : 14-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAddlWeekoff]
(
	@type nvarchar(20),
	@AddlWeekoffID INT,
    @auditEmpId int
)
AS
IF(@type='TemporaryDelete')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Isdeleted=1, Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
ELSE IF(@type='PermanentDelete')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
		DELETE FROM TA_Tbl_Additional_WeeklyOff  WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
ELSE IF(@type='Restore')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Isdeleted=0, Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_DeleteAttandanceCode '3,7',1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAttandanceCode]
	@AttandanceID as varchar(2000),	
	@EmpID as int
AS
BEGIN
	--update  TA_Tbl_AttandanceCode set IsDeleted=1,EmpID=@EmpID where AttandanceID=@AttandanceID
	declare @Query varchar(2000)
	set @Query=''
	set @Query = @Query + 'update  TA_Tbl_AttandanceCode set IsDeleted=1,EmpID=' + cast(@EmpID as varchar(10)) + ' where AttandanceID in (' +@AttandanceID + ')'
	exec (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Category set IsDeleted=1,EmpId='+cast(@EmpID as nvarchar(20))+' where CategoryId IN ('+ @CategoryID +')'
	Execute(@Query)
	--update TA_Tbl_Category set IsDeleted=1,EmpId = @EmpID where CategoryId=@CategoryID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCCGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Deletes the existing CC groups.
-- Modified by Gopinath on 14thJun14 for adding OD approval mailing group
-- =============================================
--Proc_TA_DeleteCCGroup '4','A'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCCGroup] 
(
  @CCGroupID varchar(8000),
  @Parameter varchar(5)
)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Script varchar(8000)
	set @Script=''
	  if(@Parameter='A')
		  BEGIN
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_Planned where CCGroupID in ('+@CCGroupID+')'
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_UnPlanned where CCGroupID in ('+@CCGroupID+')'
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_Others where CCGroupID in ('+@CCGroupID+')'
		     set @Script = @Script + 'Delete from TA_tbl_CcMailGroup where CCGroupID in ('+@CCGroupID+')'
			 set @Script = @Script + 'Delete from TA_Tbl_CCGroup_ODApproval where CCGroupID in ('+@CCGroupID+')'
		  END
	  else if(@Parameter='P')
		  BEGIN
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_Planned where CCGroupID in ('+@CCGroupID+')'
		  END
	  else if(@Parameter = 'U')
		  BEGIN
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_UnPlanned where CCGroupID in ('+@CCGroupID+')'
		  END
      else if(@Parameter = 'O')
		  BEGIN
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_Others where CCGroupID in ('+@CCGroupID+')'
		  END
	   else if(@Parameter = 'OD')
		  BEGIN
		     set @Script = @Script + 'Delete from TA_Tbl_CCGroup_ODApproval where CCGroupID in ('+@CCGroupID+')'
		  END
		  exec(@Script)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteChildrenDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_DeleteChildrenDetails  
Description : delete children details  
Tables Included : TA_Tbl_EmpChildrenDetails  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteChildrenDetails]
		@EmployeeId INT
	AS
	BEGIN
		DELETE FROM  TA_Tbl_EmpChildrenDetails  WHERE Emp_ID=@EmployeeId AND Spouse_Child='C'
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCountry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_DeleteCountry  
Description : delete country  
Tables Included : TA_Tbl_Lookup  
Created By : Arun Vinoth.T  
Created On : 16-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCountry]
(
@Type CHAR(1),		
@Id INT=0,
@Ids NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
		BEGIN
			UPDATE TA_Tbl_Lookup
			SET IsDeleted=@del 
			WHERE ID=@Id
		END
ELSE IF (@Type='C')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_Lookup SET IsDeleted= ' + @del + ' WHERE ID IN ('+ @Ids +')'
			EXEC (@Query)
		END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmailLogData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <16-Feb-2013>
-- Description:	<Delete the Email log data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmailLogData]
	-- Add the parameters for the stored procedure here
	@Date varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	delete from TA_tbl_EmailScheduleStatus where SentDate <= @Date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: Proc_TA_DeleteEmpLeavePolicy  17
Description 	: Delete Employee Leave Policy details
Tables Included : TA_Tbl_Emp_LeavePolicy, TA_Tbl_Emp_LeavePolicyDetails 
Created By 		: Arun vinoth	  
Created On 		: 10 Aug 07 
Modified By 	:  Prabakaran.P
Modified On 	:  16-Feb-10
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy] 
	@EmpID INT
AS
BEGIN
	SET NOCOUNT ON;
	declare @YearSettingID as int
	Set @YearSettingID=(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)  
	DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmpID and Emp_LeavePolicyId IN (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy where EmployeeId=@EmpID and YearSettingId=@YearSettingID)	
	DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId=@EmpID and YearSettingId=@YearSettingID
	Delete from TA_Tbl_YearClosure where Year_SettingID=@YearSettingID and Employee_Id=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	:	Proc_TA_DeleteEmpLeavePolicy_Yearclose 215,48 
Description 	:	Delete Employee Leave Policy details
Tables Included :	TA_Tbl_Emp_LeavePolicy, TA_Tbl_Emp_LeavePolicyDetails, TA_Tbl_LeavePolicy 
Created By 	:	Arun vinoth	  
Created On 	:	10 Aug 07 
Modified By 	:	Prabakaran.P
Modified On 	:	15-Feb-08
Description	:	Changes based on Year Closure logic
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]   
@EmpID int,
@year int
AS  
BEGIN  
	SET NOCOUNT ON;  
	DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmpID and Emp_LeavePolicyId in (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy where YearSettingId=@Year and EmployeeId=@EmpID)
	DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId=@EmpID and YearSettingId=@Year
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]  
  @EmployeeId INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=0  
 BEGIN  
  UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child='C' 
  UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child='S' 
  DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE Emp_Id=@EmployeeId  
  DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmployeeId 
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeedetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_DeleteEmployeedetails '145','Restore' 
Description 	:	Delete Employee  details
Tables Included :	TA_Tbl_Employee, TA_Tbl_EmpChildrenDetails 
*/     
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteEmployeedetails]  
(  
	@Employees NVARCHAR(max), 
	@strType NVARCHAR(50),
	@auditEmpId int,
	@ApplnMode BIT
)  
AS  
BEGIN
	DECLARE @Query NVARCHAR(2000)  
	SET @Query=''  
	IF (@strType='TemporaryDelete')  
	BEGIN  
   		SET @Query ='UPDATE TA_Tbl_Employee SET Isdeleted_Status = 1, IsDeleted= 1 WHERE Employee_Id IN ('+ @Employees +')'  
		EXEC (@Query)  
	END
	ELSE IF (@strType='PermanentDelete')  
	BEGIN  
		-- delete employee bonus leave
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmployeeBonusLeave WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee year closure
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_YearClosure WHERE Employee_Id IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee leave policy details
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee leave policy
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee children details
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee type
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmployeeType WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee category
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmployeeCategory WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee level
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmployeeLevel WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee designation
		SET @Query =''
		SET @Query ='DELETE FROM  TA_Tbl_EmployeeDesignation WHERE EmployeeID IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
		-- delete employee pay
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_EmployeePay WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query) 
  		-- delete employee Permission
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_Permission WHERE Employee_Id IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)   
  		-- delete employee LeaveApplication
		SET @Query =''
		SET @Query ='DELETE FROM TA_Tbl_LeaveApplication WHERE Employee_Id IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)  
  		-- delete employee permanentshiftallocation
		SET @Query =''
		SET @Query ='DELETE FROM ta_Tbl_permanentshiftallocation WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query) 
  		-- delete employee temporaryshiftallocation
		SET @Query =''
		SET @Query ='DELETE FROM ta_Tbl_temporaryshiftallocation WHERE EmployeeId IN (' + cast(@Employees as NVARCHAR) + ') '
  		EXEC(@Query)
  		-- delete employee clk_rawdata
  		SET @Query =''
		SET @Query ='DELETE FROM ta_Tbl_clk_rawdata where CLK_CARDID in (select distinct SwipeCardNo FROM TA_Tbl_Employee E inner join ta_Tbl_clk_rawdata crd on E.SwipeCardNo=crd.CLK_CARDID WHERE E.Employee_Id IN (' + cast(@Employees as NVARCHAR) + ')) '
  		EXEC(@Query)
		-- delete employee Clockdetails
  		SET @Query =''
		SET @Query ='DELETE FROM ta_Tbl_Clockdetails where CLK_EMPID in (select distinct SwipeCardNo  FROM TA_Tbl_Employee E  inner join ta_Tbl_Clockdetails cd on E.SwipeCardNo=cd.CLK_EMPID WHERE E.Employee_Id IN (' + cast(@Employees as NVARCHAR) + ')) '
  		EXEC(@Query)
  		-- delete employee processeddata
  		SET @Query =''
		SET @Query ='DELETE FROM ta_Tbl_processeddata where Employee_Code_ID in (select distinct SwipeCardNo FROM  TA_Tbl_Employee E inner join ta_Tbl_processeddata pd  on E.SwipeCardNo=pd.Employee_Code_ID WHERE E.Employee_Id IN (' + cast(@Employees as NVARCHAR) + ')) '
  		EXEC(@Query)
		-- delete employee
		SET @Query =''
   		SET @Query ='DELETE FROM TA_Tbl_Employee WHERE Employee_Id IN ('+ @Employees +')'  
		EXEC (@Query)
	END
	ELSE IF (@strType='Restore')  
	BEGIN  
   		SET @Query ='UPDATE TA_Tbl_Employee SET Isdeleted_Status = 0, IsDeleted= 0 WHERE Employee_Id IN ('+ @Employees +')'  
		EXEC (@Query)
	END
  	IF(@ApplnMode = 0)
	BEGIN
		/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
		UPDATE TA_Tbl_Employee SET
			Isdeleted = 1,
			--Report_Exclude = 1,
			Employee_Status = 0,
			InActiveDate = DATEADD(D, 1, DateOfJoining)
		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> '18000000' ) AND
			Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
		/* End */
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <22-03-2019>
-- Description:	<Deleting employee details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]
@ScheduleID int
AS
BEGIN
	SET NOCOUNT ON;
	Delete from TA_Tbl_EmailScheduled_Employees where ScheduleId=@ScheduleID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeesFromTempTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeesFromTempTable]
(
   @xml xml,
   @loginEmployeeId int
)
AS
BEGIN 
  Declare @Index int
  Set @Index = 0;
   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	  delete from TA_Tbl_TempShiftAllocation
	  from OpenXML(@Index, '/DocumentElement/Table')
	  With (EmployeeAutoId Bigint 'EmployeeAutoId') as xm 
	  inner join TA_Tbl_TempShiftAllocation TS on TS.EmpID = xm.EmployeeAutoId
	  and TS.LoginEmployeeId = @loginEmployeeId
  Exec sp_xml_removedocument @Index
  select * from TA_Tbl_TempShiftAllocation where LoginEmployeeId=@loginEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]
		@EmployeeId INT
	AS
	DECLARE @DEL BIT
	SET @DEL=0
	BEGIN
		UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child='S'
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_DeleteEmpName  
Description : Delete Employee name
Tables Included : TA_Tbl_TempShiftAllocation 
Created By : Arun vinoth	  
Created On : 10 Aug 07 
Modified By :  
Modified On :  
*/   
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmpName]
(  
	@Type CHAR,
	@EmpId int,
	@loginEmployeeId int
)  
AS  
BEGIN  
	SET NOCOUNT ON;  
	IF (@Type='I')  
	BEGIN  
		Delete FROM TA_Tbl_TempShiftAllocation Where EmpID=@EmpId and LoginEmployeeId = @loginEmployeeId   
	END  
	ELSE IF (@Type='A')  
	BEGIN  
		Delete FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @loginEmployeeId   
	END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]     
/****************************************************************************************/          
-- Name    : Proc_TA_DeleteEmpNameGroupPolicy         
-- Desc    : To delete the enties in TA_Tbl_TempGroupPolicyAllocation          
-- Company : Angler Technologies          
-- Author  : P.Santhosh Raj          
-- Date    : 25-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/   
(      
@Type CHAR,      
@EmpId int,    
@loginEmployeeId int      
)      
AS      
BEGIN      
 SET NOCOUNT ON;      
IF (@Type='I')      
BEGIN      
 Delete FROM TA_Tbl_TempGroupPolicyAllocation Where EmpID=@EmpId and LoginEmployeeId = @loginEmployeeId       
END      
ELSE IF (@Type='A')      
BEGIN      
 Delete FROM TA_Tbl_TempGroupPolicyAllocation Where LoginEmployeeId = @loginEmployeeId       
END      
END      
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEntranceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteEntranceDetails]
(
@Type CHAR(1),		
@entranceId INT=0,
@Entrances NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
		BEGIN
			UPDATE TA_Tbl_Entrance SET Isdeleted=@del WHERE Entrance_Id=@entranceId
		END
ELSE IF (@Type='C')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_Entrance SET IsDeleted= ' + @del + ' WHERE Entrance_Id IN ('+ @Entrances +')'
			EXEC (@Query)
		END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGeoFencing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-Aug-2020 10:21 AM,,>
-- Description:	It will delete the created geo location
-- Proc_TA_DeleteGeoLocation '18,21,22'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteGeoFencing]
	@FencingID varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'delete from TA_tbl_Fencing WHERE FencingId IN ('+ @FencingID +')'
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGeoLocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-Aug-2020 10:21 AM,,>
-- Description:	It will delete the created geo location
-- Proc_TA_DeleteGeoLocation '18,21,22'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteGeoLocation]
	@landmarkID varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'delete from Ta_tbl_LandMarks WHERE ID IN ('+ @landmarkID +')'
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGrade]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteGrade]
		@Type CHAR(1),
		@GradeId INT,
		@GradeIds NVARCHAR(50)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_Grade SET IsDeleted=@DEL WHERE Grade_Id=@GradeId
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Grade SET IsDeleted=' + @DEL + ' WHERE Grade_Id IN  (' + @GradeIds + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified by	: 	Prabakaran.p 
Proc_TA_DeleteHoliday '219','PermanentDelete',1
Modified on	:	08-Feb-08
Description	:	Permanent Delete and Restore option Added	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteHoliday]
(
	@HolidayId NVARCHAR(1000),
	@strType NVARCHAR(50),
	@auditEmpId int
)
as  
BEGIN
	set nocount on
	DECLARE @Query NVARCHAR(2000)  
	SET @Query=''	
	if(@strType='TemporaryDelete')
		begin  
			SET @Query = 'UPDATE TA_Tbl_Holiday SET IsDeleted= 1, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Holiday_Id IN ('+ @HolidayId +')'  
		end  
	if(@strType='PermanentDelete')
		begin  
			SET @Query = 'DELETE FROM TA_Tbl_HolidayChildTable WHERE Holiday_Id IN ('+ @HolidayId +');'  
			SET @Query = @Query+'DELETE FROM TA_Tbl_Holiday WHERE Holiday_Id IN ('+ @HolidayId +')'  
		end  
	if(@strType='Restore')
		begin  
			SET @Query = 'UPDATE TA_Tbl_Holiday SET IsDeleted= 0, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Holiday_Id IN ('+ @HolidayId +')'  
		end	
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteImportErrorData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteImportErrorData]
	-- Add the parameters for the stored procedure here
	@id as nvarchar(Max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	delete from TA_Tbl_ImportMasterError where id in (SELECT * FROM [dbo].[SplitupEmployeeCode] (@id))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Created by		:	Prabakaran.P
Created on		:	
Modified on		:	03-Mar-08
Modified By		:	A.K.T.MOORTHI
Modified On		:	24-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
	EXEC [Proc_TA_DeleteLeaveApplication] 42, 1

		EXEC [Proc_TA_DeleteLeaveApplication] 159, 1
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication]
(
	@LeaveApplication_Id INT,
	@auEmpId INT
)
AS
BEGIN		
	SET NOCOUNT ON;
	DECLARE @CompOffId BIGINT 
	set @CompOffId= 0
	Declare @RemainingDays NUMERIC(18,1) 
	set @RemainingDays= 0.0
	declare @EmployeeId INT
	declare @NumberOfDays NUMERIC(18, 1)
	DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
	SELECT @EmployeeId = Employee_Id, @NumberOfDays = NumberOfDays FROM TA_Tbl_LeaveApplication
		WHERE LeaveApplication_Id = @LeaveApplication_Id
	INSERT INTO @TblRecord
		SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE '%:' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + '%'
		ORDER BY [Date]
		declare @ValCount as int
		SELECT @ValCount=COUNT(*) FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE '%:' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + '%'
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
		
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@ValCount=2) THEN @RemainingDays + 0.5 else case when (@ValCount>2) THEN CASE 
				WHEN (@NumberOfDays > NoOfDays) THEN NoOfDays
				ELSE (@RemainingDays + @NumberOfDays) end else NoOfDays end END),
				CompOffSatus = (CASE
					WHEN DateToExpired < GETDATE() THEN 'Expired'
					WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN 'Not Taken' END),
				LeaveApplicationId = case	when @NumberOfDays>0.5 then REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '') 
								else	case	when (select COUNT(Value) from dbo.Split(LeaveApplicationId,':') where Value=@LeaveApplication_Id)=2 
								then ':'+CAST(@LeaveApplication_Id AS VARCHAR(20))
												else REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '') 
										end
					end
			WHERE ExtraTime_Id = @CompOffId
			SELECT @NumberOfDays = case when (@ValCount=2) then (@NumberOfDays - 0.5) else (@NumberOfDays - RemainingDays) end FROM TA_Tbl_OverTimeStatus
				WHERE ExtraTime_Id = @CompOffId
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
	--WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
	--BEGIN
	--	SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
	--	UPDATE TA_Tbl_OverTimeStatus SET
	--		@RemainingDays = RemainingDays,
	--		RemainingDays = (CASE 
	--			WHEN (@NumberOfDays > NoOfDays) THEN (@RemainingDays + @NumberOfDays) - NoOfDays
	--			ELSE (@RemainingDays + @NumberOfDays) END),
	--		CompOffSatus = (CASE
	--			WHEN DateToExpired < GETDATE() THEN 'Expired'
	--			WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN 'Not Taken' END),
	--		LeaveApplicationId = REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '')
	--	WHERE ExtraTime_Id = @CompOffId
	--	SELECT @NumberOfDays = (@NumberOfDays - RemainingDays) FROM TA_Tbl_OverTimeStatus
	--		WHERE ExtraTime_Id = @CompOffId
	--	UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
	--END
	Delete From TA_Tbl_LeaveConversation where LeaveApplicationId=@LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplication_FileUpload WHERE LeaveApplication_Id = @LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplication WHERE LeaveApplication_Id = @LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplicationExists WHERE LeaveApplicationId = @LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplicationPrintDetails_Eastman WHERE leaveAppID = @LeaveApplication_Id
	
	--print 'test loop'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication_Angler]
(
@LeaveApplication_Id int,
@auEmpId int,
@datetimeLeaveFrom datetime,
@datetimeLeaveTo datetime,
@varSessionFrom nvarchar(50),
@varSessionTo nvarchar(50),
@varType nvarchar(1)
)
AS
begin
	SET NOCOUNT ON;
    if(@varType='A')
    begin
        update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
		where LeaveApplication_Id = @LeaveApplication_Id
    end
    else
    begin
		update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
		where LeaveApplication_Id = @LeaveApplication_Id and Leave_FromDate = @datetimeLeaveFrom and Leave_ToDate = @datetimeLeaveTo and Leave_SessionFrom = @varSessionFrom and Leave_SessionTo = @varSessionTo
    end
	declare @intDeletedLeaveId as int
	set @intDeletedLeaveId = (select count(LeaveApplication_Id) from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and IsDeleted=0)
	if(@intDeletedLeaveId=0)
		begin
			update TA_Tbl_LeaveApplicationMaster set IsDeleted = 1,Emp_Id=@auEmpId where LeaveApplication_Id = @LeaveApplication_Id
		end
	--update the processflag
	update Ta_Tbl_ProcessedData set processflag=0
	from Ta_Tbl_LeaveApplication t2
	inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
	inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
	t1.date between t2.Leave_FromDate and t2.Leave_ToDate
	where t2.LeaveApplication_Id=@LeaveApplication_Id
	declare @intEmployeeId as int
	set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id)
	--Update year closure
	update ta_tbl_yearclosure set Leave_Taken=
	(select isnull(sum(NumberOfDays),0.0)
	from Ta_Tbl_LeaveApplication
	inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
	where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
	and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
	and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
	and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status='Approved'
	and TA_Tbl_YearSetting.IsActive=1 and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId)
	select @intDeletedLeaveId as LeaveCount
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by	:	Prabakaran.P
-- Created on	:	05-Jan-10
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]
(
@LeaveApplication_Id int,
@auEmpId int
)
AS
BEGIN
SET NOCOUNT ON;
		BEGIN
				update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
				where LeaveApplication_Id = @LeaveApplication_Id
		END
		BEGIN
				Delete from TA_Tbl_LeaveApplication where LeaveApplication_Id = @LeaveApplication_Id
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeaveMaster]    
  @Id INT    
 AS    
SET NOCOUNT ON;     
 DECLARE @DEL BIT    
 SET @DEL=0    
 BEGIN    
  UPDATE TA_Tbl_LeaveMaster SET IsDeleted=@DEL WHERE Id=@Id  
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Leave Policy - Delete
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicy]
	-- Add the parameters for the stored procedure here
@Type CHAR(1),		
@LeavePolicyID INT=0,
@LeavePolicies NVARCHAR(25)
AS
SET NOCOUNT ON;
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
		BEGIN
			SET NOCOUNT ON;
		UPDATE TA_Tbl_LeavePolicy SET IsDeleted=1 WHERE Policy_Id=@LeavePolicyID 
		END
ELSE IF (@Type='C')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_LeavePolicy SET IsDeleted= 1 WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
		END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Leave Policy - Delete
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicyDetails]
	@LeavePolicyID INT
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM TA_Tbl_LeavePolicyDetails WHERE Policy_Id=@LeavePolicyID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
created by		:	Manjula.P
Created Date	:	19-Jul-2013
Descriptions	:	Deleting leave types 
*/
CREATE proc [dbo].[Proc_TA_DeleteLeaveType]
(
@EmployeeId int,
@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	delete from ta_tbl_emp_LeaveTypedetails where YearSettingsId=@YearSettingsId and EmployeeId=@EmployeeId
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLevelWiseRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 04-Sep-2010
-- Description:	Deleted Level wise rights.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLevelWiseRights]
	@GroupId as int
AS
delete from TA_Tbl_LevelRights where GroupId=@GroupId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLogo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj>
-- Create date: <Create Date,,26-Nov-07>
-- Description:	<Description,,Inserting CustomerLogo>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_DeleteLogo]
AS
BEGIN	
		Delete from Ta_Tbl_Branding
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLookupData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteLookupData]
(
@Type CHAR(1),		
@Id INT=0,
@Ids NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
		BEGIN
			UPDATE TA_Tbl_Lookup
			SET IsDeleted=@del 
			WHERE ID=@Id
		END
ELSE IF (@Type='C')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_Lookup SET IsDeleted= ' + @del + ' WHERE ID IN ('+ @Ids +')'
			EXEC (@Query)
		END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualEntry]
(
	@Type CHAR(1),
	@MID int=0,
	@ManualEntryIds NVARCHAR(25)
)
AS 
	DECLARE @Isdel VARCHAR
	SET @Isdel=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_ManualTimeEntry SET Isdeleted = @Isdel  WHERE ManualTimeEntry_Id=@MID
	END
	ELSE IF (@Type='C')
	BEGIN
		SET @Query= 'UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = ' + @Isdel +'  WHERE ManualTimeEntry_Id IN (' + @ManualEntryIds + ')'
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : Proc_TA_DeleteManualTimeEntry
Description : Update Manual Time Entry Details of Employees Based on their ManualTimeEntry_Id
IsDeleted Flag Set to 1 - For Deleted Item
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Kumuthini.L
Created On : 08-Jan-09
Modified By : K.Gopinath
Modified On : 10 Feb 2014
Description : To Added new status called as DELETED for the deleted entry.For V1.4 Release
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntry]
@ManualTimeEntry_Id BIGINT,
@auEmpId BIGINT
AS
begin
	set nocount on
	declare @FromDate nvarchar(50)
	declare @ToDate nvarchar(50)
	declare @EmpoyeeCode nvarchar(15)
	set @FromDate=(select ManualTimeEntry_InDate from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	set @ToDate=(select ManualTimeEntry_OutDate from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	set @EmpoyeeCode=(select ManualTimeEntry_Employee_Id from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = 1,Emp_Id=@auEmpId,ManualTimeEntry_Status='Deleted' WHERE ManualTimeEntry_Id=@ManualTimeEntry_Id
	exec Proc_TA_ReprocessEmpData @FromDate,@ToDate,@EmpoyeeCode
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 11-03-2016
-- Description:	Delete manual time entry using On duty ID
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]
	@OndutyID as int
AS
BEGIN
	SET NOCOUNT ON;
    delete from Ta_Tbl_ManualTimeEntry where OnDuty_ID=@OndutyID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthCloseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteMonthCloseDetails]
(
	@MonthCloseID INT
)
AS
BEGIN
	UPDATE TA_Tbl_MonthClosure SET Isdeleted=0 WHERE MonthClosure_Id=@MonthCloseID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthClosureDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created By 	:	Prabakaran.P
Created On	:	4-Mar-09
--Proc_TA_DeleteMonthClosureDetails [51,59],1
*/
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteMonthClosureDetails]
(
@MonthCloseID varchar(8000),
@EmpAutoId int
)
AS
BEGIN
DECLARE @SqlQuery1 as varchar(8000)
DECLARE @SqlQuery2 as varchar(8000)
DECLARE @SqlQuery3 as varchar(8000)
DECLARE @SqlQuery4 as varchar(8000)
set @SqlQuery1=''
set @SqlQuery2=''
set @SqlQuery3=''
set @SqlQuery4=''
set @SqlQuery1='UPDATE TA_Tbl_MonthClosure SET Emp_Id = '+cast(@EmpAutoId as nvarchar(20))+' WHERE MonthClosure_Id IN (' + Convert(varchar(8000),@MonthCloseID) + ')'
Exec(@SqlQuery1)
set @SqlQuery2='DELETE FROM TA_Tbl_PayrollProcessDetails WHERE MonthClosure_Id IN (' + Convert(varchar(8000),@MonthCloseID) + ')'
Exec(@SqlQuery2)
set @SqlQuery3='DELETE FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id IN (' + Convert(varchar(8000),@MonthCloseID) + ')'
Exec(@SqlQuery3)
set @SqlQuery4='DELETE FROM TA_Tbl_MonthClosure WHERE MonthClosure_Id IN (' + Convert(varchar(8000),@MonthCloseID) + ')'
Exec(@SqlQuery4)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOndutyEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name : Proc_TA_DeleteOndutyEntry
Description : Update Manual Time Entry and  Details of Employees Based on their onduty_ID
IsDeleted Flag Set to 1 - For Deleted Item
Tables Included : TA_Tbl_ManualTimeEntry,TA_Tbl_OndutyEntry
Created By : Karthikeyan.R
Created On : 15-Mar-2016
Description : To Added new status called as DELETED for the deleted entry.For V1.4 Release
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteOndutyEntry]
@Onduty_Id BIGINT,
@auEmpId BIGINT
AS
BEGIN
	SET NOCOUNT ON;
	--UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = 1,Emp_Id=@auEmpId,ManualTimeEntry_Status='Deleted' WHERE OnDuty_ID=@Onduty_Id

	Delete From TA_Tbl_OnDutyConversation where OnDutyApplicationId=@Onduty_Id

	delete from TA_Tbl_ManualTimeEntry WHERE OnDuty_ID=@Onduty_Id
	--update TA_Tbl_OndutyEntry set Isdeleted=1,Emp_Id=@auEmpId,Onduty_Status='Deleted' where Onduty_ID=@Onduty_Id
	delete from TA_Tbl_OndutyEntry WHERE OnDuty_ID=@Onduty_Id

	declare @FromDate as nvarchar(30)
	declare @ToDate as nvarchar(30)
	declare @EmployeeCode as nvarchar(30)
	set @FromDate=(select Onduty_FromDate from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	set @ToDate=(select Onduty_ToDate from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	set @EmployeeCode=(select Onduty_EmployeeID from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	exec Proc_TA_ReprocessEmpData @FromDate,@ToDate,@EmployeeCode
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOTRoundoffSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		christopher
-- Create date:19-05-09
-- Description:	deleting ot round off settings before inserting or updating
-- ============================================
Create PROCEDURE [dbo].[Proc_TA_DeleteOTRoundoffSettings]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int 
AS
BEGIN
	SET NOCOUNT ON;
    delete  from TA_Tbl_OTRoundoffSettings where ShiftSettingId=@shiftSettingId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteOtType] 
	@OtTypeID as int,	
	@EmpId as int
AS
BEGIN	
	update  TA_Tbl_OtType set IsDeleted=1,EmpID=@EmpID where OtTypeID=@OtTypeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePayrollLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeletePayrollLeaveDetails]
(
   @MonthClosureId INT
)
AS
begin
SET NOCOUNT ON;
DELETE FROM TA_Tbl_PayrollProcessLeaveDetails WHERE MonthClosure_Id = @MonthClosureId
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeletePermanentCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Category set EmpId='+cast(@EmpID as nvarchar(20))+' where CategoryId IN ('+ @CategoryID +')'
	Execute(@Query)
	--update TA_Tbl_Category set EmpId = @EmpID where CategoryId=@CategoryID
	--Delete from Ta_tbl_Category where CategoryId=@CategoryID
	SET @Query = 'Delete from Ta_tbl_Category where CategoryId IN ('+ @CategoryID +')'
	Execute(@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeletePermanentType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Type set EmpId='+cast(@EmpID as nvarchar(20))+' where TypeId IN ('+ @TypeID +')'
	EXEC (@Query)
	--update TA_Tbl_Type set EmpId = @EmpID where TypeId=@TypeID	
	SET @Query = 'Delete from TA_Tbl_Type where TypeId IN ('+ @TypeID +')'
	EXEC (@Query)
	--Delete from ta_tbl_type where TypeID=@TypeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermissionApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_DeletePermissionApplication
Description		:	Update Permisssion Details of Employees Based on their Permission_Id
					IsDeleted Flag Set to 1 - For Deleted Item
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	20-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_DeletePermissionApplication]
	@Permission_Id bigint,
	@auEmpId int
as
begin
	set nocount on;
	delete from TA_Tbl_PermissionConversation where PermissionId=@Permission_Id
	delete from TA_Tbl_Permission where Permission_Id=@Permission_Id
	--if the employee applied permission for second time in a month and deleted the first permission entry,
	--the first permission entry details need not to be loaded into gridview control of modify page.
	if exists(select Prev_Perm_ID from ta_tbl_PrevPermissionDetails_EastMan where Prev_Perm_ID=@Permission_Id)
	begin
		Delete from ta_tbl_PrevPermissionDetails_EastMan where Prev_Perm_ID=@Permission_Id
	end
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProgressDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteProgressDetails]
	@ProgressTaskID bigint
AS
BEGIN
	SET NOCOUNT ON;
	Delete from Ta_tbl_TaskProgressDetails where TaskDetailID=@ProgressTaskID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProject]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani.P>
-- Create date: <06Jan2020>
-- Description:	<Delete the project info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteProject]
	@ProjectId bigint, @UserId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	IF EXISTS(select isnull(Project_Id,0) from TA_Tbl_Project where Project_Id = @ProjectId)
	begin
		update TA_Tbl_Project set IsDeleted = 1 where Project_Id = @ProjectId
	End
	

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeletePunchTypes]
@Type CHAR(1),
@PunchType_Id INT,
@PunchType_Ids NVARCHAR(50)
AS
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_PunchTypes SET IsDeleted = @DEL WHERE PunchType_Id = @PunchType_Id
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_PunchTypes SET IsDeleted=' + @DEL + ' WHERE PunchType_Id IN  (' + @PunchType_Ids + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_DeleteRestoreAddlWeekoff  
Description : delete and restore additional week off 
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Christopher S
Created On : 08-Feb-2008 
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]
(
	@type nvarchar(20),
	@WeedayId varchar(100),
	@auditEmpId int
)
AS
        DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF(@type='PermanentDelete')
		BEGIN
			SET @Query='UPDATE TA_Tbl_Additional_WeeklyOff SET Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE 
			Addl_WeeklyOff_Id in (' + @WeedayId + ')'   
			EXEC (@Query)
			SET @Query=''
			set  @Query='delete from TA_Tbl_Additional_WeeklyOff_Levels where Addl_WeeklyOff_Id in('+ @WeedayId +')'
			SET @Query= @Query +'DELETE FROM TA_Tbl_Additional_WeeklyOff  WHERE Addl_WeeklyOff_Id IN ('+@WeedayId+')'
            EXEC (@Query) 
		END
	ELSE IF(@type='TemporaryDelete')
		BEGIN
			SET @Query='UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=1, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' 
			WHERE Addl_WeeklyOff_Id in (' + @WeedayId + ')'   
			EXEC (@Query) 
		END
	ELSE IF(@type='Restore')
		BEGIN
			SET @Query='UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=0, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' 
			WHERE Addl_WeeklyOff_Id in (' + @WeedayId + ')'   
			EXEC (@Query) 
		END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreEntranceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreEntranceDetails]
(
	@Type CHAR(25),		
	@Entrances NVARCHAR(500),
	@auditEmpId int
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF (@Type='TemporaryDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Entrance SET IsDeleted = 1, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Entrance_Id IN ('+ @Entrances +')'
	END
	ELSE IF (@Type='PermanentDelete')
	BEGIN				
		SET @Query = 'DELETE FROM TA_Tbl_Entrance_INOUTDetails WHERE Entrance_Id IN ('+ @Entrances +');'		
		SET @Query = @Query +' DELETE FROM TA_Tbl_Entrance WHERE Entrance_Id IN ('+ @Entrances +')'		
	END
	ELSE IF (@Type='Restore')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Entrance SET IsDeleted = 0, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Entrance_Id IN ('+ @Entrances +')'
	END	
	EXEC (@Query)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreGrade]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_DeleteRestoreGrade 'TemporaryDelete','15,16,17'
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteRestoreGrade]
		@Type NVARCHAR(20),		
		@GradeIds NVARCHAR(50),
		@auditEmpId int
	AS
	DECLARE @DEL VARCHAR
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='PermanentDelete')
	BEGIN	
		SET @Query ='DELETE FROM TA_Tbl_Grade WHERE Grade_Id IN ('+@GradeIds+')'
		EXEC (@Query)
	END
ELSE IF (@Type='TemporaryDelete')
	BEGIN
		SET @DEL=1
		SET @Query = 'UPDATE TA_Tbl_Grade SET IsDeleted=' + @DEL + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Grade_Id IN  (' + @GradeIds + ')'
		EXEC (@Query)
	END
ELSE IF (@Type='Restore')
	BEGIN
		SET @DEL=0
		SET @Query = 'UPDATE TA_Tbl_Grade SET IsDeleted=' + @DEL + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Grade_Id IN  (' + @GradeIds + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =======================================================
-- Procedure Name : Proc_TA_DeleteRestoreLeavePolicy
-- Tables Used : TA_Tbl_LeavePolicy,TA_Tbl_LeavePolicyDetails
-- Author:   Arun vinoth
-- ALTER  date : 28 June 2007
-- Last Modified By: Kumuthini.L
-- Last Modified On: 07-Feb-2008
-- Description:	Leave Policy - Delete
-- =======================================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeavePolicy]
	@Type CHAR(25),		
	@LeavePolicies NVARCHAR(500),
	@auditEmpId int	
AS
begin
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	DECLARE @Query1 NVARCHAR(2000)
	SET @Query=''
	SET @Query1=''
	IF (@Type='TemporaryDelete') -- In Activating the Records
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_LeavePolicyDetails SET Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
			SET @Query = ''
			SET @Query = 'UPDATE TA_Tbl_LeavePolicy SET IsDeleted= 1, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
		END
	ELSE IF (@Type='PermanentDelete') -- Permanently Deleting the Records
		BEGIN			
			SET @Query1 = ''
			SET @Query1 = 'DELETE FROM TA_Tbl_LeavePolicyDetails WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query1)
			SET @Query = ''
			SET @Query = 'DELETE FROM TA_Tbl_LeavePolicy WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
		END
	ELSE IF (@Type='Restore')  -- Restoring the Records
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_LeavePolicyDetails SET Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
			SET @Query = ''
			SET @Query = 'UPDATE TA_Tbl_LeavePolicy SET IsDeleted = 0, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE Policy_Id IN ('+ @LeavePolicies +')'
			EXEC (@Query)
		END
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure Name - Proc_TA_DeleteRestoreLeaveType
-- Tables Used - TA_Tbl_LeaveType
-- Created By -  Kumuthini.L
-- Created On - 05-Feb-2008
-- Proc_TA_DeleteRestoreLeaveType 'PermanentDelete','5,8,6',1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeaveType]   
(     
	@Type CHAR(25),
	@Leaves NVARCHAR(500),
	@auditEmpId int
)
AS	
begin
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='TemporaryDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_LeaveType SET IsDeleted = 1, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE LeaveType_Id IN ('+ @Leaves +')'
        EXEC (@Query)
	END
ELSE IF (@Type='PermanentDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_LeaveType SET Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE LeaveType_Id IN ('+ @Leaves +')'
        EXEC (@Query)
		SET @Query =''
		SET @Query = 'DELETE FROM TA_Tbl_YearClosure WHERE LeaveTypeID IN ('+ @Leaves +')'
		EXEC (@Query)
		SET @Query =''
		SET @Query = 'DELETE FROM TA_Tbl_LeaveType WHERE LeaveType_Id IN ('+ @Leaves +')'
		EXEC (@Query)
	END
ELSE IF (@Type='Restore')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_LeaveType SET IsDeleted = 0, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE LeaveType_Id IN ('+ @Leaves +')'
        EXEC (@Query)
	END
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLookupdata]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreLookupdata]
(
	@Type nvarchar (20),		
	@Ids NVARCHAR(25),
	@auditEmpId int
)
AS
	DECLARE @del NVARCHAR
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='PermanentDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Lookup SET Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE ID IN ('+ @Ids +')'
		EXEC (@Query)
		SET @Query = 'DELETE FROM TA_Tbl_Lookup WHERE ID IN ('+@Ids+')'
		EXEC (@Query)
	END
ELSE IF (@Type='TemporaryDelete')
	BEGIN
		SET @del=1
		SET @Query = 'UPDATE TA_Tbl_Lookup SET IsDeleted= ' + @del + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE ID IN ('+ @Ids +')'
		EXEC (@Query)
	END
ELSE IF (@Type='Restore')
	BEGIN
		SET @del=0
		SET @Query = 'UPDATE TA_Tbl_Lookup SET IsDeleted= ' + @del + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE ID IN ('+ @Ids +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreNews]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- =============================================
-- Author:		Christopher S
-- ALTER  date: 07-Feb-08
-- Description:	Delete & Restore News/Events
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreNews]
(
	@type NVARCHAR(20),
    @newsId varchar(1000),
	@empId int
)
AS
declare @SQLQuery varchar(2000)
set @SQLQuery = ''
if(@type='PermanentDelete')
	BEGIN
		set @SQLQuery = @SQLQuery + 'update ta_tbl_newsEvents set emp_Id= ' + cast(@empId as varchar(20)) + ' where NewsEvent_Id in (' + cast(@newsId as varchar(1000)) +')'
		set @SQLQuery = @SQLQuery + 'delete ta_tbl_newsEvents where NewsEvent_Id in (' + cast(@newsId as varchar(1000)) + ')'
		exec (@SQLQuery)
	END
else if(@type='TemporaryDelete')
	BEGIN
		set @SQLQuery = @SQLQuery + 'update ta_tbl_newsEvents set isDeleted=1,timeStamp=getDate(),emp_Id=' + cast(@empId as varchar(20)) + 'where NewsEvent_Id in ( ' + cast(@newsId as varchar(1000)) + ')'
		exec (@SQLQuery)
	END
else if(@type='Restore')
	BEGIN
		set @SQLQuery = @SQLQuery + 'update ta_tbl_newsEvents set isDeleted=0,timeStamp=getDate(),emp_Id= ' + cast(@empId as varchar(20)) + ' where NewsEvent_Id in ( ' + cast(@newsId as varchar(1000)) + ')'
		exec (@SQLQuery)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestorePunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestorePunchTypes]
	@Type CHAR(25),
	@PunchType_Ids NVARCHAR(500),
	@auditEmpId int
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF (@Type='TemporaryDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_PunchTypes SET IsDeleted=1, Emp_Id = '+cast(@auditEmpId as nvarchar(20))
	END
	ELSE IF (@Type='PermanentDelete')
	BEGIN
		SET @Query = 'DELETE FROM TA_Tbl_PunchTypes '			
	END
	ELSE IF (@Type='Restore')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_PunchTypes SET IsDeleted=0, Emp_Id = '+cast(@auditEmpId as nvarchar(20))
	END
	EXEC (@Query+' WHERE PunchType_Id IN  (' + @PunchType_Ids + ')')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreReligion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreReligion] 
(     
	@Type CHAR(25),		
	@ID NVARCHAR(500),
	@auditEmpId int
)
AS	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='TemporaryDelete') -- In Activating the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Religion SET IsDeleted = 1 WHERE ID IN ('+ cast(@ID as nvarchar(500)) +')'
        EXEC (@Query)
	END
ELSE IF (@Type='PermanentDelete') -- Permanently Deleting the Single or Multiple Records
	BEGIN
		--SET @Query = 'UPDATE TA_Tbl_Religion SET SET 1=1 WHERE ID IN ('+ @ID +')'
        --EXEC (@Query)
		SET @Query =''
		SET @Query = 'DELETE FROM TA_Tbl_Religion WHERE ID IN ('+ @ID +')'
        EXEC (@Query)
	END
ELSE IF (@Type='Restore') -- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Religion SET IsDeleted = 0 WHERE ID IN ('+ @ID +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreShiftAll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
For Temporary Deleting or Permanent Delete or Restoring multiple shifts 
Modified by	:	P.Prabakaran
Modified on	:	05-Feb_08
Description	:	@del default value modified from 0 to 1
Option Given for Permanent Delete , Temporary Delete and Restore Records
*/
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreShiftAll] 
(
	@ShiftIds varchar(200),
	@DeleteRestoreOption nvarchar(50),
	@auditEmpId int
)
as
	DECLARE @del NVARCHAR
	DECLARE @restore NVARCHAR
	SET @del=1
	SET @restore=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
if(@DeleteRestoreOption='TemporaryDelete') -- In Activating the Single or Multiple Records
	BEGIN
		/*UPDATE TA_Tbl_Shift SET Isdeleted=0 WHERE Shift_Id=@ShiftId*/
		SET @Query = 'UPDATE TA_Tbl_Shift SET IsDeleted= ' + @del + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Shift_Id IN ('+ @ShiftIds +')'
		EXEC (@Query)
	END
else if(@DeleteRestoreOption='PermanentDelete')-- Permanently Deleting the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Shift SET  Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Shift_Id IN ('+ @ShiftIds +')'
		EXEC (@Query)
		SET @Query = ''
		SET @Query = 'DELETE FROM TA_Tbl_Shift WHERE Shift_Id IN ('+ @ShiftIds +')'
		EXEC (@Query)
	END
else if(@DeleteRestoreOption='Restore')-- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Shift SET IsDeleted= ' + @restore + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE Shift_Id IN ('+ @ShiftIds +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminal]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure Name - Proc_TA_DeleteRestoreTerminal
-- Tables Used - TA_Tbl_Terminal
-- Modified By -  Kumuthini.L
-- Modified On - 07-Feb-2008
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminal]
(
	@Type CHAR(25),
	@Terminals NVARCHAR(500),
	@auditEmpId int	
)
AS	
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF (@Type='TemporaryDelete')
	BEGIN
		SET @Query= 'UPDATE TA_Tbl_Terminal SET IsDeleted = 1, Emp_ID = '+cast(@auditEmpId as nvarchar(20))
	END
	IF (@Type='PermanentDelete')
	BEGIN		
		SET @Query= 'DELETE FROM TA_Tbl_Terminal '
	END
	IF (@Type='Restore')
	BEGIN
		SET @Query= 'UPDATE TA_Tbl_Terminal SET IsDeleted = 0, Emp_ID = '+cast(@auditEmpId as nvarchar(20))
	END
	EXEC (@Query +' WHERE Terminal_Id IN (' + @Terminals + ')')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]
(
	@Type CHAR(20),
	@TerminalDataTypes NVARCHAR(max),
	@auditEmpId int
)
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	IF (@Type='TemporaryDelete')
		BEGIN
			SET @Query= 'UPDATE TA_tbl_TerminalDatatype SET IsDeleted = 1, Emp_Id = '+cast(@auditEmpId as nvarchar(20))
		END
	ELSE IF (@Type='PermanentDelete')
		BEGIN		
			SET @Query= 'DELETE FROM TA_tbl_TerminalDatatype'
		END
	ELSE IF (@Type='Restore')
		BEGIN
			SET @Query= 'UPDATE TA_tbl_TerminalDatatype SET IsDeleted = 0, Emp_Id = '+cast(@auditEmpId as nvarchar(20))
		END
	EXEC (@Query+' WHERE TerminalDatatype_ID IN (' + @TerminalDataTypes + ')')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTitle]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified By : Kumuthini.L
-- Modified On : 8-Feb-08
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteRestoreTitle]
(
	@Type CHAR(25),
	@TitleIds NVARCHAR(100),
	@auditEmpId int
)
AS	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='TemporaryDelete') -- In Activating the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Title SET IsDeleted = 1, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE TitleId IN  (' + @TitleIds + ')'
		EXEC (@Query)
	END
IF (@Type='PermanentDelete')-- Permanently Deleting the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Title SET Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE TitleId IN  (' + @TitleIds + ')'
		EXEC (@Query)
		SET @Query = 'DELETE FROM TA_Tbl_Title WHERE TitleId IN  (' + @TitleIds + ')'
		EXEC (@Query)
	END
IF (@Type='Restore')-- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Title SET IsDeleted = 0, Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE TitleId IN  (' + @TitleIds + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreWeekday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*    
Procedure Name : Proc_TA_DeleteRestoreWeekday 
Description : delete the weekday 
Tables Included : TA_Tbl_TemWeekday  
Created By : Christopher S   
Created On : 07-Feb-2008
Modified By :  Manikandan.R
Modified On :  14-Mar-2012
*/  
--[Proc_TA_DeleteRestoreWeekday] 'TemporaryDelete',6,1
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteRestoreWeekday] 
(
	@type nvarchar(20),
    @WeedayId varchar(100),
	@auditEmpId int	
)	
AS
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	BEGIN
		SET NOCOUNT ON;
		if(@type='PermanentDelete')  --permanently delete temporary week day
			begin		 		
				SET @Query= 'UPDATE TA_Tbl_TemWeekday SET Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE TempWeekday_Id  IN (' + @WeedayId + ')'
				EXEC (@Query) 		
				SET @Query=''		
				set @Query='Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in (' + @WeedayId + '))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate'
				EXEC (@Query) 
				SET @Query=''
				SET @Query= 'DELETE FROM Ta_Tbl_Temp_WeeklyOff_Levels WHERE TempWeekday_Id  in (' + @WeedayId + ')'
				EXEC (@Query) 
				SET @Query=''
				SET @Query= 'DELETE FROM Ta_Tbl_Temporary_WeeklyOff_Levels WHERE TempWeekday_Id  in (' + @WeedayId + ')'
				EXEC (@Query) 
				SET @Query=''
				SET @Query='DELETE FROM TA_Tbl_TemWeekday WHERE TempWeekday_Id  in (' + @WeedayId + ')'
				EXEC (@Query) 
			end
		else if(@type='TemporaryDelete')  --inactivate the temporary week day
			begin
				SET @Query= 'UPDATE TA_Tbl_TemWeekday SET IsDeleted = 1, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE TempWeekday_Id  IN (' + @WeedayId + ')'
				EXEC (@Query)
				set @Query=''			
				set @Query='Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in (' + @WeedayId + '))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate'				 
				EXEC (@Query)
			end
		else if(@type='Restore')    -- restore the temporary week day
			begin
				SET @Query= 'UPDATE TA_Tbl_TemWeekday SET IsDeleted = 0, Emp_Id = '+cast(@auditEmpId as nvarchar(20))+' WHERE TempWeekday_Id  IN (' + @WeedayId + ')'
				EXEC (@Query)	    
				set @Query=''
				set @Query='Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in (' + @WeedayId + '))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate'
				EXEC (@Query) 
			end     
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]
(
	@ScheduleId int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    delete from TA_tbl_MailIdsForTriggeringEmail where ScheduleId = @ScheduleId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteScheduleWhatsAppNumberBeforeUpdating]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteScheduleWhatsAppNumberBeforeUpdating] 
	-- Add the parameters for the stored procedure here
	@ScheduleId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	 delete from TA_tbl_WhatsAppNumberForTriggeringMessage where ScheduleId = @ScheduleId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_DeleteShift]
(@ShiftId int,
 @auditEmpId int)
as
BEGIN
	UPDATE TA_Tbl_Shift SET Isdeleted=1,Emp_ID =@auditEmpId WHERE Shift_Id=@ShiftId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftAll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
For Deleting multiple shifts
*/
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteShiftAll] 
(@ShiftIds varchar(200))
as
BEGIN
	DECLARE @del NVARCHAR
	SET @del=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	/*UPDATE TA_Tbl_Shift SET Isdeleted=0 WHERE Shift_Id=@ShiftId*/
	SET @Query = 'UPDATE TA_Tbl_Shift SET IsDeleted= ' + @del + ' WHERE Shift_Id IN ('+ @ShiftIds +')'
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	: Proc_TA_DeleteShiftHoliday_YrSettings  59
Description 	: Check for data available during delete of new year settings in shift and holiday if the data is not yet processed.
Tables Included : TA_Tbl_YearSetting  
Created By 	: Gopinath  
*/   
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]
	@YearSettingId  int
as  
begin
	SET NOCOUNT ON;
	Declare @StartMonth as int
	Declare @EndMonth as int
	declare @StartYear as int
	Declare @EndYear as int
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @RowCount as bigint
	Select @StartYear = Year(Fromdate), @EndYear = Year(Todate), @StartMonth = Month(Fromdate),@EndMonth = Month(Todate),
	@StartDate = Fromdate, @EndDate = Todate from ta_tbl_yearsetting where YearSettings_ID = @YearSettingId
	Set @RowCount = (select Count(*) from ta_tbl_processeddata where Date between @StartDate and @EndDate)
	--select @StartYear,@EndYear,@StartMonth,@EndMonth,@StartDate,@EndDate,@RowCount
	if(@RowCount = 0)
	BEGIN
		DELETE ta_tbl_permanentshiftAllocation where ((year=@StartYear and month>=@StartMonth) or (year=@EndYear and month<=@EndMonth)) 
		DELETE ta_tbl_holidaysettings where YearSettingID = @YearSettingId
		Delete TA_Tbl_HolidayChildTable where holiday_id in 
	   (Select Holiday_ID from ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate)
		DELETE ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftId]
		@Type CHAR(1),
		@ShiftId  INT,
		@ShiftIds varchar(200)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_Shift SET IsDeleted=@DEL WHERE Shift_Id=@ShiftId
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Shift SET IsDeleted=' + @DEL + ' WHERE Shift_Id IN  (' + @ShiftIds + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/* 
Created by	: 	Abul
Description	:	To delete a particular shift pattern using its pattern id  
Modified by	:	P.Prabakaran
Modified on	:	05-Feb-08
*/
CREATE      Proc [dbo].[Proc_TA_DeleteShiftPattern]
@ShiftPattern_Id int,
@Type CHAR(1),
@ShiftPattern_Ids varchar(1000)
As
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
	IF (@Type='I')
	-- I refers Individual record updation
		BEGIN
			update TA_Tbl_ShiftPattern set Isdeleted=@DEL where ShiftPattern_Id = @ShiftPattern_Id
		END
	ELSE IF (@Type='M')
	-- M refers Multilple records updation
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_ShiftPattern SET IsDeleted=' + @DEL + ' WHERE ShiftPattern_Id IN  (' + @ShiftPattern_Ids + ')'
			EXEC (@Query)
		END
	ELSE IF (@Type='P')
	--P refers Permanently delete the record
		BEGIN
			Delete from TA_Tbl_ShiftPattern where ShiftPattern_Id = @ShiftPattern_Id
		END
	--select * from ta_tbl_shiftPattern
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftRoaster]  
(@ShiftRoasterId int)
AS
	BEGIN
		Delete from TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id=@ShiftRoasterId
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoasterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
	Modified By		:	A.K.T.MOORTHI
	Modified Date	:	17-Dec-2013
	Description		:	Delete Shift Roster Details Based On Shift Roster Ids
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftRoasterDetails]
	@RoasterIds NVARCHAR(MAX),
	@DeleteType BIT
AS
BEGIN
	DECLARE @Query NVARCHAR(MAX)
	SET @Query=''
	IF(@RoasterIds <> '')
	BEGIN
		IF (@DeleteType = 1)
			SET @Query = 'DELETE FROM TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id IN ('+ @RoasterIds +')'
		ELSE
			SET @Query = 'UPDATE TA_Tbl_ShiftRoaster SET IsDeleted = 1 WHERE ShiftRoaster_Id IN ('+ @RoasterIds +')'
		EXEC (@Query)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteSpouseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteSpouseDetails]
		@EmployeeId INT
	AS
	BEGIN
		DELETE FROM  TA_Tbl_EmpChildrenDetails  WHERE Emp_ID=@EmployeeId AND Spouse_Child='S'
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Manikandan.R
-- Create date: 30-07-2014 04:19
-- Description:	Delete the records in temporary shift allocation
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTempShiftAllocation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_TempShiftAllocation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminal]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminal]
		@Type CHAR(1),
		@TerminalId INT=0,
		@Terminals NVARCHAR(25)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_Terminal SET IsDeleted=@DEL WHERE Terminal_Id=@TerminalId
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query= 'UPDATE TA_Tbl_Terminal SET IsDeleted = ' + @DEL + ' WHERE Terminal_Id IN (' + @Terminals + ')'
	EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalDatatype]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminalDatatype]
(
@Type CHAR(1),
@TerminalDatatypeId INT,
@TerminalDataTypes NVARCHAR(25)
)
AS
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_tbl_TerminalDatatype SET IsDeleted=@del WHERE TerminalDatatype_ID=@TerminalDatatypeId
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query= 'UPDATE TA_tbl_TerminalDatatype SET IsDeleted = ' + @DEL + ' WHERE TerminalDatatype_ID IN (' + @TerminalDataTypes + ')'
	             EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalMapping]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminalMapping]
		@TerminalMapId INT
	AS
	DECLARE @DEL BIT
	SET @DEL=1
	BEGIN
		UPDATE TA_Tbl_TerminalMapping SET IsDeleted=@DEL
		 WHERE TerMap_Id=@TerminalMapId
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitle]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteTitle]
		@Type CHAR(1),
		@TitleId INT,
		@TitleIds NVARCHAR(50)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
IF (@Type='I')
	BEGIN
		UPDATE TA_Tbl_Title SET IsDeleted=@DEL WHERE TitleId=@TitleId
	END
ELSE IF (@Type='C')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Title SET IsDeleted=' + @DEL + ' WHERE TitleId IN  (' + @TitleIds + ')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitleMapping]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteTitleMapping]  
  @Id INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=1  
 BEGIN  
  UPDATE TA_Tbl_TitleMapping SET IsDeleted=@DEL WHERE Id=@Id
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Type set IsDeleted=1,EmpId='+cast(@EmpID as nvarchar(20))+' where TypeId IN ('+ @TypeID +')'
	Execute(@Query)
	--update TA_Tbl_Type set IsDeleted=1,EmpId = @EmpID where TypeId=@TypeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosuredetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_DeleteYearClosuredetails] 
(
@YearsettingId int,
@EmployeeId int
)
as
DELETE FROM TA_TBL_YEARCLOSURE WHERE YEAR_SETTINGID=@YearsettingId AND EMPLOYEE_ID=@EmployeeId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_DeleteYearClosureLeaveTypedetails 11,[1,2,3],4,1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails] 
(
@EmployeeId int,
@mappedLeaveTypes nvarchar(4000),
@YearsettingId int,
@auEmpId int
)
as
BEGIN
if(@mappedLeaveTypes!='')
	BEGIN
		SET NOCOUNT ON;
		DECLARE @Query NVARCHAR(2000)
		SET @Query=''
		SET @Query = 'DELETE FROM TA_TBL_YEARCLOSURE WHERE LeaveTypeId NOT IN ('+ @mappedLeaveTypes +') and EMPLOYEE_ID=' + cast(@EmployeeId as nvarchar(20)) + ' and YEAR_SETTINGID=' + cast(@YearsettingId as nvarchar(20)) + ' '
		EXEC (@Query)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearsetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name 	: Proc_TA_DeleteYearsetting  50
Description 	: Save year settings details into table  
Tables Included : TA_Tbl_YearSetting  
Created By 	: Prabakaran  
Created On 	: 22-Nov-07  
Modified By 	:  
Modified On 	:  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteYearsetting]   
@YearSettingId  int
as  
--declare @RecordExiststing as int  
--set @RecordExiststing=(select count(*) From TA_Tbl_Yearsetting ys where ys.IsActive=0 
--and (Year(Getdate()) not between ys.StartYear and ys.EndYear) and ys.StartYear > Year(Getdate()) and ys.EndYear > Year(Getdate()) 
--and ys.YearSettings_Id=@YearSettingId)
--select @RecordExiststing
--if(@RecordExiststing>0)
begin
delete from ta_tbl_yearclosure where Year_SettingID=@YearSettingId
--end
--if(@RecordExiststing>0)
--begin
delete from TA_Tbl_Yearsetting where YearSettings_Id=@YearSettingId
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_delLevels]  
(  
 @levID varchar(10),  
 @opr varchar(1)   
)  
as  
begin  
 if @opr='C'  
  Begin  
   declare @checkFlag  int  
   set @checkFlag = 0  
   declare @recCount as int  
   set @recCount = (select count(*) from ta_tbl_leveldetails where levelId=@levID and isdeleted=0)  
   if (@recCount>0)  
    Begin  
     set @checkFlag=1  
    End  
   set @recCount = (select count(*) from ta_tbl_level where parentLevelId=@levID and isdeleted=0)  
   if (@recCount>0)  
    Begin  
     set @checkFlag=1  
    End     
  select @checkFlag as checkFlag  
  end  
 else  
  Begin  
	declare @Query varchar(2000)
	set @Query = ''
    set @Query = @Query + 'update ta_tbl_level set isdeleted=1 where levelid in ( ' + cast(@levID as varchar(10)) + ')'
    exec (@Query)
  End   
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLookup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_delLookup]  
(   
	@lookupID int  
)  
as  
begin  	
	declare @checkFlag  int  
	set @checkFlag = 0  
	declare @recCount as int  
	declare @recCount1 as int
	declare @recCount2 as int
	declare @recCount3 as int
	--checking in lookup mapping
	set @recCount = (select count(*) from ta_tbl_lookup where Parent=@lookupID)  
	--checking in Employee for City mapping
	set @recCount1 = (select count(*) from ta_tbl_Employee where Native_Place=@lookupID) 
	--checking in Employee for State mapping
	set @recCount2 = (select count(*) from ta_tbl_Employee where State=@lookupID) 
	--checking in Employee for Country mapping 
	set @recCount3 = (select count(*) from ta_tbl_Employee where Country=@lookupID)  
	if (@recCount>0)  
		Begin  
			set @checkFlag=1  
		End  
	else if (@recCount1>0)  
		Begin  
			set @checkFlag=1  
		End     
	else if (@recCount2>0)  
		Begin  
			set @checkFlag=1  
		End 
	else if (@recCount3>0)  
		Begin  
			set @checkFlag=1  
		End  
	select @checkFlag as checkFlag  
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delOrgLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_delOrgLevels]
(
	@levID int,
	@opr varchar(1),
	@oprType nvarchar(20)=null
)
as
begin
	if @opr='C'
		Begin
			declare @checkFlag  int
			set @checkFlag = 0
			declare @recCount as int
			set @recCount = (select count(*) from ta_tbl_leveldetails where parentId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from ta_tbl_employeeLevel where LevelId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Entrance where OrgLevel_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_MonthClosure where OrgLevel_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_RouteMaster where Level_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Title where LevelID=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_YearClosure where OrgLevelId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Additional_WeeklyOff where LevelId_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
		select @checkFlag as checkFlag
		end
	else		
		Begin
			if(@oprType='TemporaryDelete')
				Begin
					update ta_tbl_leveldetails set isdeleted=1 where id=@levID
				End
			if(@oprType='PermanentDelete')
				Begin
					delete from ta_tbl_leveldetails where id=@levID
				End
			if(@oprType='CheckRestore')
				Begin
					set @checkFlag = 0
					set @recCount = (select count(*) from ta_tbl_levelDetails where isdeleted=0 and id!=@levID and  name=(select name from ta_tbl_leveldetails where id=@levID and isdeleted=0) )
					if (@recCount>0)
						Begin
							set @checkFlag=1
						End
					select @checkFlag as checkFlag
				End
			if(@oprType='Restore')
				Begin
					update ta_tbl_leveldetails set isdeleted=0 where id=@levID
				End			
		End	
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delUserGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- Create date: 18-August-2007
-- Description:	Delete User Group
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_delUserGroup] 
@groupId int,
@opr varchar(1)
AS
BEGIN
	if (@opr='C')
		Begin
			select count(*) as recCount from ta_tbl_employee where userGroup_Id = @groupId
		End
	else
		Begin
			update ta_tbl_usergroup set isDeleted=1 where groupId=@groupId
			update ta_tbl_userrights set isDeleted=1 where groupId=@groupId
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DetailAttendanceforExportTally]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_DetailAttendanceforExportTally '2017/04/01','2017/04/30','','','0,1','SuperAdmin','0','',9,0,'Both',0,0,1
-- exec Proc_TA_RptDetailAttendanceDynamicNew @fromDat='2014-07-01 00:00:00',@ToDat='2014-07-31 00:00:00',@empId=N'',
--@EmployeeName=N'',@LevelID=N'0',@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@DesignationId=0,@Gender=N'Both',0,0
CREATE PROCEDURE [dbo].[Proc_TA_DetailAttendanceforExportTally]   
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(max),   
	@EmployeeName varchar(max),
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
	@ParentId int,  
	@DesignationID int,  
	@Gender varchar(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
)  
AS  
BEGIN  
	set nocount on
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),[Employee Id] varchar(50),SwipeCardNo varchar(50),
		Gender varchar(20),	Present numeric(8,1),Absent numeric(8,1),
		[Total Late Days] numeric(8,1),[Total Late Hours] numeric(8,1),
		[Total Early Exit Days] numeric(18,1),[Total Early Exit Hours] float default(0),
		[Total OT Days] numeric(8,1),
		[Total OT Hours] numeric(8,1),[Norm OT Hrs] numeric(8,1),[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),Others numeric(8,1),
		EmployeeCategory int,EmpCategory nvarchar(200),
		EmployeeType int,WeeklyOff numeric(8,1),Holiday numeric(8,1),Leave Numeric(8,1),LOP numeric(8,1)
	)
	create table #TempDetailedAttendanceFinal  
	(     
		[Employee Name] nvarchar(200),[Employee Id] varchar(50),
		Gender varchar(20),Present numeric(8,1),Absent numeric(8,1),
		[Total Late Days] numeric(8,1),[Total Late Hours] numeric(8,1),
		EarlyOutInMins float default(0),EarlyOutDays numeric(18,1),
		[Total OT Days] numeric(8,1),[Total OT Hours] numeric(8,1),
		[Norm OT Hrs] numeric(8,1),[WeekOff OT Hrs] numeric(8,1),
		[Holiday OT Hrs] numeric(8,1),Others numeric(8,1)
	)
	create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20))   
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50)) 
	create table #EmpGrade(Grade_Id int)  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpAttendanceDetails(EmployeeID  varchar(50),Present numeric(8,1),Absent numeric(8,1),TotalLateDays numeric(8,1),TotalLateHours numeric(8,1),TotalOTDays numeric(8,1),TotalOTHours numeric(8,1),NormalOTHrs numeric(8,1),WeekOffOTHrs numeric
	(8,1),HolidayOTHours numeric(8,1),EarlyOutInMins float,TotalEarlyOutDays numeric(8,1),EmployeeCategory int,EmpCategory nvarchar(200),EmployeeType int,WeeklyOff numeric(8,1),Holiday numeric(8,1),Leave Numeric(8,1),LOP numeric(8,1))
	create table #LevelRights(LevelId int)
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20),Shift_Id int,TotalDays numeric(18,
	1),LateInMins float,OtMins float,NormOT nvarchar(10),OffOT nvarchar(10),HolOT nvarchar(10),EarlyOutMins float)	
	create table #TempEmployeeForProcessedData(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]   
	(  
		[Grade_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId], [DesignationId] ASC  
	)ON [PRIMARY]  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #tempLeavetype SELECT Top 5 substring(LeaveType,1,3)  FROM ta_tbl_leavetype
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel  	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	--To split up the comma separated values
	if(@empId is not null and @empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@empId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)	
			declare @LevelId1 as int
			declare @GetLevelID as int
			declare @LeaveName as nvarchar(200)
            set @GetLevelID=(select top 1 LevelId from #EmpLevel)
            DECLARE @childID INT 
             ;WITH ParentLevel AS
            (
                  SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
                  WHERE id = @GetLevelID
                  UNION ALL
                  SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
                  INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
            )
            SELECT TOP 1 @LevelId1=id
            FROM ParentLevel r
            --inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
            ORDER BY lvl DESC
	select @LeaveName=name from Ta_Tbl_levelDetails where id=@LevelId1
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo=
	'insert into #TempEmployeeForProcessedData 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
	If Not (@empId = '')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.report_exclude = 0 '
	if(@Gender<>'Both')  
		begin  
			set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end   
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	execute(@sqlCommonSwipeCardNo)	
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=  
	'insert into #TempProcessedData 
	select	#TempEmployeeForProcessedData.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Attendance,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.Shift_Id,
			PD.TotalDays,
			PD.LateInMins,
			PD.OtMins,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			PD.EarlyOutMins
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployeeForProcessedData on #TempEmployeeForProcessedData.EmpSwipeCardNo=PD.Employee_Code_Id  
	inner join TA_Tbl_Employee E on E.SwipeCardNo=#TempEmployeeForProcessedData.EmpSwipeCardNo  
	where (PD.date >= CONVERT(DATETIME,'''+cast( @fromDat as nvarchar(50))+''', 102))  
	AND (PD.date <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date)  
	or  
	(E.Employee_Status=1)  
	)'  
	execute(@sqlTempProcessedData1)
	declare @SqlQuery as varchar(8000)  
	set @SqlQuery=''  
	set @SqlQuery = 'insert into #tempemployee (EmployeeCodeId,SwipeCardNo,EmployeeName,Gender) select ta_tbl_employee.employee_code_id as [Employee Id],ta_tbl_employee.SwipeCardNo,isnull(Employee_FirstName,'''') + SPACE(1) + isnull(Employee_LastName,'''') AS [Employee Name],TA_Tbl_Employee.Gender'  
	set @SqlQuery = @SqlQuery + '	from ta_tbl_employee inner join #TempProcessedData on #TempProcessedData.EmpAutoId = ta_tbl_employee.Employee_ID'  
	set @SqlQuery = @SqlQuery + '	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '  
	set @SqlQuery = @SqlQuery + '	Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '  
	set @SqlQuery = @SqlQuery + '	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + '	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sqlQuery = @sqlQuery + '	WHERE 
									(TA_Tbl_Employee.Employee_Status = 1  
										or   
									(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102) >=   
									convert(varchar(11),#TempProcessedData.Date,102))) ' 	
	if(@UserGroupName<>'SuperAdmin')  
		begin  
			set @SqlQuery=@SqlQuery+' AND TA_Tbl_Grade.Grade_Level >=''' + cast(@GradeLevel as nvarchar(8)) + ''' '
		end  
	exec(@SqlQuery)  
	insert into #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender) select distinct EmployeeCodeId,SwipeCardNo,EmployeeName,Gender from #tempemployee  
	declare @SqlPresent varchar(8000)  
	set @SqlPresent = ' insert into #EmpAttendanceDetails select Employee_code_Id, '  
	set @SqlPresent = @SqlPresent + ' ''Present'' = sum( CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'	
	--set @SqlPresent = @SqlPresent + ' ''Present'' = 
	--									sum(
	--											CASE FNAttendanceCode 
	--												WHEN ''Present'' THEN	Case TotalDays	When ''1.0'' Then ''0.5'' 
	--																						Else TotalDays 
	--																		END 
	--												When ''|'' Then TotalDays 
	--												When ''Weekly Off'' then totalDays 
	--												else 0 
	--											END
	--										) + 
	--									sum( 
	--											CASE	ANAttendanceCode 
	--													WHEN ''Present'' THEN	Case TotalDays	When ''1.0'' Then ''0.5'' 
	--																							Else TotalDays 
	--																			END  
	--													else 0 
	--											END
	--										)'  
	--set @SqlPresent = @SqlPresent + ' + sum( CASE FNAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)+ sum( CASE FNAttendanceCode WHEN ''BL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''BL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END),'
	set @SqlPresent = @SqlPresent + ' ''Absent'' = sum( CASE FNAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'  
	set @SqlPresent = @SqlPresent + ' ''Total Late Days'' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , '  
	set @SqlPresent = @SqlPresent + ' ''Total Late Hours'' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), '  
	set @SqlPresent = @SqlPresent + ' ''Total OT Days'' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , '  
	set @SqlPresent = @SqlPresent + ' ''Total Ot Hours'' =  sum(CASE otmins WHEN otmins THEN  otmins END)/60, '  
	set @SqlPresent = @SqlPresent + ' ''Norm OT Hrs''=sum(CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''WeekOff OT Hrs''=sum(CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''Holiday OT Hrs''=sum(CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),'  
	set @SqlPresent = @SqlPresent + ' ''Total EarlyOut Hours'' =  sum(CASE EarlyOutmins WHEN EarlyOutmins THEN  EarlyOutmins END), '  
	set @SqlPresent = @SqlPresent + ' ''Total EarlyOut Days'' =  count(CASE EarlyOutmins WHEN EarlyOutmins THEN  EarlyOutmins END) - count(CASE EarlyOutmins WHEN 0 THEN  EarlyOutmins END) - count(CASE EarlyOutmins WHEN null THEN  EarlyOutmins END),C.CategoryId,C.CategoryName,T.TypeId ,'
	set @SqlPresent = @SqlPresent + ' ''WeeklyOff'' = sum( CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'  
	set @SqlPresent = @SqlPresent + ' ''Holiday'' = sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'	
	set @SqlPresent = @SqlPresent + ' ''Leave'' = SUM(CASE WHEN FNAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'',''LOP'') THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + 
	SUM( CASE WHEN ANAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'	
	set @SqlPresent = @SqlPresent + ' ''LOP'' = sum( CASE FNAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END)'		
	set @SqlPresent = @SqlPresent + ' from #TempProcessedData  '  
	set @SqlPresent = @SqlPresent + ' inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=#TempProcessedData.EmpAutoId 
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=#TempProcessedData.EmpAutoId  
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId   '  
	set @SqlPresent = @SqlPresent + ' where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance) '  
	set @SqlPresent = @SqlPresent + ' group by Employee_Code_ID,C.CategoryId,C.CategoryName,T.TypeId '  
	exec (@SqlPresent)  
	--Updates the Present,Absent,OT,Late details in the temporary table.  
	update #TempDetailedAttendance set Present = #EmpAttendanceDetails.Present,Absent = #EmpAttendanceDetails.Absent,  
	[Total Late Days] = #EmpAttendanceDetails.TotalLateDays,[Total Late Hours] = #EmpAttendanceDetails.TotalLateHours,  
	[Total OT Days] = #EmpAttendanceDetails.TotalOTDays,[Total OT Hours] = #EmpAttendanceDetails.TotalOTHours,  
	[Norm OT Hrs] = #EmpAttendanceDetails.NormalOTHrs,[WeekOff OT Hrs] = #EmpAttendanceDetails.WeekOffOTHrs,  
	[Holiday OT Hrs] = #EmpAttendanceDetails.HolidayOTHours,
	[Total Early Exit Hours]=#EmpAttendanceDetails.EarlyOutInMins,
	[Total Early Exit Days]= #EmpAttendanceDetails.TotalEarlyOutDays,
	EmployeeCategory=#EmpAttendanceDetails.EmployeeCategory,
	EmpCategory=#EmpAttendanceDetails.EmpCategory,
	EmployeeType=#EmpAttendanceDetails.EmployeeType,
	WeeklyOff=#EmpAttendanceDetails.WeeklyOff,
	Holiday=#EmpAttendanceDetails.Holiday,
	Leave=#EmpAttendanceDetails.Leave,
	LOP=#EmpAttendanceDetails.LOP
	 from #EmpAttendanceDetails inner join #TempDetailedAttendance   
	on #EmpAttendanceDetails.EmployeeID=#TempDetailedAttendance.SwipeCardNo  
	--Inserts the Others details in the temporary table  
	--declare @SqlOthers varchar(4000)  
	--create table #Others(SwipeCardNo  varchar(50),Others numeric(8,1))  
	----inserts the Others in the temporary table.  
	--set @SqlOthers = 'Insert into #Others select Employee_Code_Id ,''Others'' = sum( CASE FNAttendanceCode WHEN ''RH'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)'  
	--set @SqlOthers = @SqlOthers + ' + sum( CASE ANAttendanceCode WHEN ''RH'' THEN Case TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''LOP'' THEN Case TotalDays
	--When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)'  
	--set @SqlOthers = @SqlOthers + ' from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance) '  
	--set @SqlOthers = @SqlOthers + ' group by Employee_Code_ID'  
	--exec(@SqlOthers)  
	--Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype varchar(10) )  
	--insert into #tempLeaveTypeforOthers select LeaveType from Ta_Tbl_LeaveType where LeaveType not in(select LeaveType from #tempLeavetype)  
	--declare @LTOthersCount int  
	--set @LTOthersCount=1  
	--while(@LTOthersCount<=(select count(*) from #tempLeaveTypeforOthers))  
	--	BEGIN  
	--		declare @LeaveTypeForOthers varchar(10)  
	--		set @LeaveTypeForOthers =(select LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount)  
	--		declare @SqlUpdateOthers varchar(3000)  
	--		set @SqlUpdateOthers = 'Update #Others set Others = Others + '  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + 'A.TotalDays from '   
	--		set @SqlUpdateOthers =@SqlUpdateOthers + ' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END)'  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + ' + sum( CASE PD.ANAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else PD.TotalDays END else 0 END)) as TotalDays'
	--		set @SqlUpdateOthers = @SqlUpdateOthers + ' from #TempProcessedData PD '  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + ' group by PD.Employee_Code_Id) A'  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + ' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id'  
	--		set @LTOthersCount=@LTOthersCount+1  
	--		exec(@SqlUpdateOthers)  
	--	END  
	--Updates the Others column in the temporary table  
	--update #TempDetailedAttendance set Others=#Others.Others from #Others inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo  
	--Adding the Leave type column in the #TempDetailedAttendance table.  
	--declare @LeaveTypeCount int  
	--set @LeaveTypeCount=1  
	--while(@LeaveTypeCount<=5)  
	--	BEGIN  
	--		declare @LeaveType varchar(10)  
	--		set @LeaveType=(select Leavetype from #tempLeavetype where slno=@LeaveTypeCount)  
	--		declare @AlterQuery varchar(100)  
	--		set @AlterQuery='Alter table #TempDetailedAttendance add [' + @LeaveType + '] numeric(18,1)'  
	--		exec(@AlterQuery)  
	--		declare @UpdateQuery varchar(4000)  
	--		set @UpdateQuery = 'update #TempDetailedAttendance  set ['+ @LeaveType +']'  
	--		set @UpdateQuery = @UpdateQuery + '=A.TotalDays from'  
	--		set @UpdateQuery = @UpdateQuery +' (select Employee_Code_ID,(sum(CASE PD.FNAttendanceCode WHEN ''' + @LeaveType + ''' THEN CASE PD.TotalDays When ''0.5'' Then ''0.5'' when ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END) '  
	--		set @UpdateQuery = @UpdateQuery + ' + sum(CASE PD.ANAttendanceCode WHEN ''' + @LeaveType + ''' THEN CASE PD.TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END)) as TotalDays '  
	--		set @UpdateQuery = @UpdateQuery + ' from #TempProcessedData PD'  
	--		set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=PD.Employee_code_ID'  
	--		set @UpdateQuery = @UpdateQuery + ' group by PD.Employee_Code_ID) A'  
	--		set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID'  
	--		exec(@UpdateQuery)  
	--		set @LeaveTypeCount=@LeaveTypeCount+1  
	--END  
	set @SqlPresent=''
	set @SqlPresent=' select *,'''+cast(isnull(@LeaveName,'') as nvarchar(100))+''' as LevelName from #TempDetailedAttendance where 1=1  '
	if(isnull(@EmployeeCategory,0)>0)
		begin
			set @SqlPresent = @SqlPresent + ' and EmployeeCategory ='''+cast(@EmployeeCategory as varchar(50))+''' ' 
		end
	if(isnull(@EmployeeType,0)>0)
		begin
			set @SqlPresent = @SqlPresent + ' and  EmployeeType='''+cast(@EmployeeType as varchar(50))+''' ' 
		end
	exec (@SqlPresent)
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	--drop table #Others  
	--drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployeeForProcessedData  
	drop table #TempDetailedAttendanceFinal  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DevicewiseINOUTRawdataRpt]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_DevicewiseINOUTRawdataRpt]

    @FromDate varchar(20) ='2023-03-01',
	@ToDate varchar(20) ='2023-05-30' ,
	@EmployeeId varchar(max) ='TCT0005',
	@EmployeeName varchar(max) ='',
	@UserGroupName varchar(250) ='',
	@DesignationID int ='',
	@employeeCategory int ='', 
	@employeeType int ='',
	@ParentID int ='',
	@Gender varchar(10) ='Both',
	@ProcessType int ='',
	@EmpAutoID int ='',
	@DeviceId varchar(50) =''
	
AS
BEGIN
--
	SELECT Convert ( varchar, Convert(date, CLK_DATE),101) as PunchDate,dbo.TA_Tbl_Employee.Employee_Code_Id ,dbo.TA_Tbl_Terminal.Terminal_Name , 
Concat( dbo.TA_Tbl_Employee.Employee_FirstName , dbo.TA_Tbl_Employee.Employee_LastName )AS EmployeeName,dbo.Ta_Tbl_levelDetails.name AS PunchType,
Max(CLK_TIME) as Process,CASE WHEN Min(CLK_TIME) = Max(CLK_TIME) THEN '00:00' ELSE Min(CLK_TIME) END AS PunchTime,

[dbo].[ConvertMinsToHours](DATEDIFF(MI,CLK_DATE  + max(CLK_TIME),CLK_DATE  + min(CLK_TIME))) as LevelName ,

CASE WHEN Max(CLK_TIME)<> '' THEN 'Present' ELSE 'Absent' END AS Resolution


FROM TA_Tbl_Clk_RawData INNER JOIN
 dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
 dbo.TA_Tbl_EmployeeLevel ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN
 dbo.Ta_Tbl_levelDetails ON Convert(nvarchar(50), dbo.TA_Tbl_EmployeeLevel.LevelId )= Convert(nvarchar(50), dbo.Ta_Tbl_levelDetails.id)INNER JOIN 
 dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID INNER JOIN
 dbo.TA_Tbl_EmployeeDesignation  ON  dbo.TA_Tbl_EmployeeDesignation.EmployeeID = dbo.TA_Tbl_Employee.Employee_Id INNER JOIN
 dbo.TA_Tbl_EmployeeCategory ON dbo.TA_Tbl_EmployeeCategory.EmployeeId =  dbo.TA_Tbl_Employee.Employee_Id INNER  JOIN 
 dbo.TA_Tbl_EmployeeType ON dbo.TA_Tbl_EmployeeType.Employeeid =   dbo.TA_Tbl_Employee.Employee_Id 
 

WHERE dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 2 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE BETWEEN @FromDate AND @ToDate AND

dbo.TA_Tbl_Employee.Employee_Code_Id = CASE WHEN @EmployeeId = '' THEN dbo.TA_Tbl_Employee.Employee_Code_Id ELSE  @EmployeeId END  AND

dbo.TA_Tbl_EmployeeDesignation.DesignationID = CASE WHEN @DesignationID = '' THEN dbo.TA_Tbl_EmployeeDesignation.DesignationID ELSE  @DesignationID END  AND

dbo.TA_Tbl_Employee.Gender = CASE WHEN @Gender = 'Both' THEN  dbo.TA_Tbl_Employee.Gender  ELSE @Gender END AND 

dbo.TA_Tbl_EmployeeCategory.CategoryId = CASE WHEN @employeeCategory = '' THEN dbo.TA_Tbl_EmployeeCategory.CategoryId  ELSE  @employeeCategory END AND 

dbo.TA_Tbl_EmployeeType.TypeId = CASE WHEN @employeeType = '' THEN  dbo.TA_Tbl_EmployeeType.TypeId  ELSE @employeeType END 

 
 

GROUP BY CLK_DATE,dbo.TA_Tbl_Employee.Employee_Code_Id ,
dbo.TA_Tbl_Employee.Employee_FirstName ,dbo.Ta_Tbl_levelDetails.name,dbo.TA_Tbl_Employee.Employee_LastName,dbo.TA_Tbl_Terminal.Terminal_Name
order by CLK_DATE
--
END



--Select * from TA_Tbl_Employee
--SELECT * FROM TA_Tbl_EmployeeDesignation
--SELECT * FROM TA_Tbl_EmployeeCategory
--SELECT * FROM TA_Tbl_EmployeeType
--SELECT * FROM TA_Tbl_EmployeeDesignation
--SELECT * FROM TA_Tbl_Terminal









--SELECT        dbo.TA_Tbl_Employee.Employee_FirstName, dbo.TA_Tbl_Clk_RawData.CLK_CARDID, dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID, dbo.TA_Tbl_Clk_RawData.CLK_DATE, dbo.TA_Tbl_Clk_RawData.CLK_TIME, 
--                         dbo.TA_Tbl_Clk_RawData.CLK_TYPE, dbo.TA_Tbl_Clk_RawData.CLK_FLAG, dbo.TA_Tbl_Clk_RawData.CLK_PROCESS, dbo.TA_Tbl_Clk_RawData.TimeStamp, dbo.TA_Tbl_Clk_RawData.TimecheckDateTime, 
--                         dbo.TA_Tbl_Clk_RawData.ReasonId, dbo.TA_Tbl_Terminal.Terminal_Name INTO #PIN
--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE ='2023-05-04 00:00:00.000' and 
--CLK_TIME  = (SELECT  MAX( CLK_TIME)FROM dbo.TA_Tbl_Clk_RawData WHERE CLK_TYPE = 1 AND CLK_DATE ='2023-05-04 00:00:00.000')


--SELECT        dbo.TA_Tbl_Employee.Employee_FirstName, dbo.TA_Tbl_Clk_RawData.CLK_CARDID, dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID, dbo.TA_Tbl_Clk_RawData.CLK_DATE, dbo.TA_Tbl_Clk_RawData.CLK_TIME, 
--                         dbo.TA_Tbl_Clk_RawData.CLK_TYPE, dbo.TA_Tbl_Clk_RawData.CLK_FLAG, dbo.TA_Tbl_Clk_RawData.CLK_PROCESS, dbo.TA_Tbl_Clk_RawData.TimeStamp, dbo.TA_Tbl_Clk_RawData.TimecheckDateTime, 
--                         dbo.TA_Tbl_Clk_RawData.ReasonId, dbo.TA_Tbl_Terminal.Terminal_Name INTO #POUT
--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE ='2023-05-04 00:00:00.000' and 
--CLK_TIME  = (SELECT  MIN( CLK_TIME)FROM dbo.TA_Tbl_Clk_RawData WHERE CLK_TYPE = 1 AND CLK_DATE ='2023-05-04 00:00:00.000')



--SELECT       dbo.TA_Tbl_Clk_RawData.CLK_DATE as [PUNCH DATE], dbo.TA_Tbl_Terminal.Terminal_Name AS [PLANET NAME],dbo.TA_Tbl_Employee.Employee_Code_Id AS [EMPLOYEE ID],
--dbo.TA_Tbl_Employee.Employee_FirstName AS [EMPLOYEE NAME],dbo.Ta_Tbl_levelDetails.name AS DEPARTMENT,#PIN.CLK_TIME AS [IN PUNCH],#POUT.CLK_TIME AS [OUT PUNCH] ,

--(DATEDIFF(HH,CONVERT(DATETIME,#PIN.CLK_TIME,104),CONVERT(datetime,#POUT.CLK_TIME,104)) %24) AS WORKHOURS,

--(CASE WHEN (DATEDIFF(HH,CONVERT(DATETIME,#PIN.CLK_TIME,104),CONVERT(datetime,#POUT.CLK_TIME,104)) %24) >=8 then 'P' else 'A' end ) as STATUS

--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_EmployeeLevel ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN
--                         dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelId = dbo.Ta_Tbl_levelDetails.id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID inner join 
--						 #PIN ON #PIN.CLK_CARDID = dbo.TA_Tbl_Clk_RawData.CLK_CARDID INNER JOIN 
--						 #POUT ON #POUT.CLK_CARDID = dbo.TA_Tbl_Clk_RawData.CLK_CARDID 
						 
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE = '2023-05-04 00:00:00.000' 

--GROUP BY dbo.TA_Tbl_Clk_RawData.CLK_DATE , dbo.TA_Tbl_Terminal.Terminal_Name ,dbo.TA_Tbl_Employee.Employee_Code_Id ,
--dbo.TA_Tbl_Employee.Employee_FirstName ,dbo.Ta_Tbl_levelDetails.name,#PIN.CLK_TIME ,#POUT.CLK_TIME


----select * from #PIN
----select * from #POUT



--drop table #PIN
--drop table #POUT
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DomainLogin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- [Proc_TA_DomainLogin] 'manikandan.rr@angleritech.com'
CREATE PROCEDURE [dbo].[Proc_TA_DomainLogin]
(
	@DomainUserName NVARCHAR(1000)
)
AS
BEGIN	
	SELECT	
	Employee_Id,Employee_FirstName + ' ' + Employee_LastName AS 'Employee Name',
	Employee_Code_Id,EmailId,Photo,
	UserGroup_Id,Designation_Id,ShiftPattern_Id,Bus_Id,
			Employee_MiddleName,Employee_LastName,Father_name,Mother_name,DateofBirth,DateofBirth_Record,Blood_Group,Contact_Address, 
			Permanent_Address, Phone_Number, Mobile_Number, Gender, Marital_status, Nationality, Religion,Personal_mailid, Passport_No, 
			Passport_expirydate, Visa_No, Visa_expirydate, Vehicle_Type, Vehicle_No, Anniversary_Date, Native_Place, District, State, Country, 
			Spouse_No, Children_No, DateOfJoining, Reporting_To, Leave_Sanc_Authority, Prev_Experience, Basic_Salary, Allowances, 
			UserName, Emp_password, Qual_JoiningTime, Qual_Employment, OutDoorJob, CompOff_Eligible, OT_Eligible, ESI_Eligible, PF_Eligible, 
			Report_Exclude, Employee_Status, SwipeCardNo, Time_Stamp, Emp_ID, Isdeleted, Hostel, IsFlexible, InActiveDate, CustomField1, CustomField2, 
			CustomField3, CustomField4, CustomField5, IsComplete, Isdeleted_Status, InActive_Status, IsImported,MobileClockInOUt,IsMyProfileRqrd=ISNULL(IsMyProfileRqrd,0) FROM TA_Tbl_Employee 
	--WHERE Employee_FirstName=@DomainUserName AND IsDeleted=0 and Employee_status=1
	WHERE (UserName=@DomainUserName) AND IsDeleted=0 and Employee_status=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVEmployeeCreation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_DVEmployeeCreation
Description : check employee creation for demo version
Tables Included : TA_Tbl_Employee  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVEmployeeCreation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_Employee where isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVLevelCreation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_DVLevelCreation
Description : check level creation for demo version
Tables Included : TA_Tbl_YearSetting  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVLevelCreation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_Level where isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVYearSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_DVYearSetting
Description : check year setting for demo version
Tables Included : TA_Tbl_YearSetting  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVYearSetting]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_YearSetting 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EditDeleteImportErrorData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-Apr-2017
-- Description:	
--[Proc_TA_EditDeleteImportErrorData] 'D',14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EditDeleteImportErrorData]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@id bigint ,
	@Emp_FirstName nvarchar(50) = null,
	@Emp_MiddleName  nvarchar(50)= null,
	@Emp_LastName nvarchar(50)= null,
	@Father_Name nvarchar(50)= null,
	@Mother_Name nvarchar(50)= null,
	@DateOfBirth nvarchar(20)= null,
	@DateOfBirth_Record nvarchar(20)= null,
	@Blood_Group nvarchar(10)= null,
	@Email_Id nvarchar(100) = null,
	@Contact_Address nvarchar(MAX)= null,
	@Permanent_Address nvarchar(MAX)= null,
	@Phone_Number nvarchar(50)= null,
	@Mobile_Number nvarchar(50)= null,
	@Gender nvarchar(10)= null,
	@Marital_Status nvarchar(10)= null,
	@Nationality nvarchar(50)= null,
	@Religion nvarchar(50)= null,
	@Personal_EmailID nvarchar(100)= null,
	@Passport_No nvarchar(50)= null,
	@Passport_ExpiryDate nvarchar(20)= null,
	@Visa_No nvarchar(50)= null,
	@Visa_ExpiryDate nvarchar(20)= null,
	@Employee_Code nvarchar(50)= null,
	@DateOfJoining nvarchar(20)= null,
	@Qualification_joiningtime nvarchar(50)= null,
	@Qualification_Employement nvarchar(50)= null,
	@CompOff_Eligible nvarchar(5)= null,
	@OT_Eligible nvarchar(5)= null,
	@Report_Exclude nvarchar(5)= null,
	@Employee_Status nvarchar(5)= null,
	@IsDeleted nvarchar(5)= null,
	@Hostel nvarchar(5)= null,
	@Designation nvarchar(200)= null,
	@Grade nvarchar(50)= null,
	@GradeNo nvarchar(50)= null,
	@Employee_Type nvarchar(100)= null,
	@Employee_Category nvarchar(100)= null,
	@BasicSalary nvarchar(50)= null,
	@Level1 nvarchar(100)= null,
	@Level2 nvarchar(100)= null,
	@Level3 nvarchar(100) = null,
	@Level4 nvarchar(100)= null,
	@Level5 nvarchar(100)= null,
	@Level6 nvarchar(100)= null,
	@Level7 nvarchar(100)= null,
	@Level8 nvarchar(100)= null,
	@Level9 nvarchar(100)= null,
	@Level10 nvarchar(100)= null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@tag='M')
		BEGIN
			update TA_Tbl_ImportMasterError set Emp_FirstName=@Emp_FirstName ,Emp_MiddleName=@Emp_MiddleName  ,Emp_LastName=@Emp_LastName ,Father_Name=@Father_Name ,Mother_Name=@Mother_Name ,DateOfBirth=@DateOfBirth ,DateOfBirth_Record=@DateOfBirth_Record ,Blood_Group=@Blood_Group ,Email_Id=@Email_Id,Contact_Address=@Contact_Address ,Permanent_Address=@Permanent_Address ,Phone_Number=@Phone_Number ,Mobile_Number=@Mobile_Number ,Gender=@Gender ,Marital_Status=@Marital_Status ,Nationality=@Nationality ,Religion=@Religion,Personal_EmailID=@Personal_EmailID ,Passport_No=@Passport_No ,Passport_ExpiryDate=@Passport_ExpiryDate ,Visa_No=@Visa_No ,Visa_ExpiryDate=@Visa_ExpiryDate ,Employee_Code=@Employee_Code ,DateOfJoining=@DateOfJoining ,Qualification_joiningtime=@Qualification_joiningtime ,Qualification_Employement =@Qualification_Employement,CompOff_Eligible=@CompOff_Eligible ,OT_Eligible=@OT_Eligible ,Report_Exclude=@Report_Exclude ,Employee_Status=@Employee_Status ,IsDeleted=@IsDeleted ,Hostel=@Hostel ,Designation=@Designation ,Grade=@Grade ,GradeNo=@GradeNo ,Employee_Type=@Employee_Type ,Employee_Category=@Employee_Category ,BasicSalary=@BasicSalary ,Level1=@Level1 ,Level2=@Level2 ,Level3=@Level3 ,Level4=@Level4 ,Level5=@Level5 ,Level6=@Level6 ,Level7=@Level7 ,Level8=@Level8 ,Level9=@Level9 ,Level10=@Level10 where id=@id
		END
	ELSE IF(@tag='D')
	BEGIN
		delete from TA_Tbl_ImportMasterError where id=@id
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmailToEmployeeDetailsForSearch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
exec Proc_TA_EmployeeDetailsForSearch @EmployeeName=N'',@empId=N'',@UserGroupName=N'SuperAdmin',
@UserLevel='0',@GradeLevel=N'0',@SwipeOpt='Select',@EmpSwipeCard='',@ParentId=0,@LoginEmployeeAutoId=1,@ApplnMode=1,@Filter= 10
,@EmployeeCategory=0,@employeetype=1,@Gender='Both',@EmpAutoID=1,@ScheduleID=0,@FilterUserGroup=0,@LeavePolicy=0,@Reportingto=0,@ApprovalAuthority=0,@EmailAvail=0,@expiryNo=10
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmailToEmployeeDetailsForSearch]    
(    
	@EmployeeName			NVARCHAR(MAX)='',
	@empId					NVARCHAR(MAX)='',
	@UserGroupName			NVARCHAR(250),
	@UserLevel				VARCHAR(8000),
	@GradeLevel				NVARCHAR(20) ,
	@SwipeOpt				VARCHAR(25),
	@EmpSwipeCard			VARCHAR(20),
	@ParentId				INT,
	@LoginEmployeeAutoId	INT,
	@ApplnMode				BIT,
	@Filter					INT,
	@EmployeeCategory		INT,
	@EmployeeType			INT,
	@Gender					VARCHAR(10),
	@EmpAutoID int,
	@ScheduleID int		=	null,	
	@FilterUserGroup int,  
	@LeavePolicy int,  
    @Reportingto int,  
    @ApprovalAuthority int, 
    @EmailAvail int,
    @expiryNo int
)    
AS
BEGIN 
	--insert into TestingEmployee values
	--(
	--	@EmployeeName,
	--	@empId		,
	--	@UserGroupName,
	--	@UserLevel	,
	--	@GradeLevel	,
	--	@SwipeOpt	,
	--	@EmpSwipeCard,
	--	@ParentId	,
	--	@LoginEmployeeAutoId	,
	--	@ApplnMode				,
	--	@Filter					,
	--	@EmployeeCategory		,
	--	@EmployeeType			,
	--	@Gender					,
	--	@EmpAutoID ,
	--	@ScheduleID ,
	--	@FilterUserGroup ,
	--	@LeavePolicy ,
	--	@Reportingto ,
	--	@ApprovalAuthority ,
	--	@EmailAvail 
	--)
	SET NOCOUNT ON;
	DECLARE @IndividualUserStatus int
	DECLARE @sql AS VARCHAR(8000) 	
	DECLARE @EmpId_Numeric table (EmployeeCodeId VARCHAR(15))
	CREATE table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) AS LevelId
	CREATE table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	CREATE table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	CREATE table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	CREATE table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	declare @isReportingto as int
	
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
    CREATE table #EmployeeID(EmployeeID VARCHAR(25))
    CREATE table #EmployeeName(EmployeeID VARCHAR(25))
    
	if(@empId is not null and @empId <> '')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
	(
		select max(el.EffectiveDate) AS EffectiveDate,el.EmployeeId from TA_Tbl_EmployeeLevel el  
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
		INNER JOIN #LevelRights LR ON LR.LevelId=el.LevelId
		Left outer JOIN #EmployeeID TEmpID ON TEmpID.EmployeeID=Employee_Code_Id 
		Left Outer JOIN #EmployeeName TEmpName ON TEmpName.EmployeeID=Employee_Code_Id
		left outer join TA_Tbl_Emp_LeavePolicyDetails LP on emp.Employee_Id=LP.EmpID
		Where 1=1
		and
		(
			(@Filter=0) or 
			(@Filter=1 and OT_Eligible=1 and CompOff_Eligible=0) or 
			(@Filter=2 and OT_Eligible=0 and CompOff_Eligible=1) or
			(@Filter=3 and OT_Eligible=1 and CompOff_Eligible=1) or
			(@Filter=4 and LP.Policy_Id is null)  or
			(@Filter=5 and Employee_Status=0) or
			(@Filter=6 and Hostel=1) or
			(@Filter=7 and Report_Exclude=1) or
			(@Filter=8 and (UserGroup_Id is null or UserGroup_Id='')) or
			(@Filter=9 and OT_Eligible=0 and CompOff_Eligible=0) or
			(@Filter=10 and Employee_Status=1)			
		)
		and(@Gender='Both' or Gender=@Gender)
		and(isnull(@expiryNo,0)=0 or ((Passport_expirydate is not null and Passport_expirydate<=DATEADD(d,@expiryNo,getdate())) or (Visa_expirydate is not null and Visa_expirydate<=DATEADD(d,@expiryNo,getdate()))))
		and(@isReportingto=0 or (Employee_ID IN (select * from #EmployeeIds)))
		and(ISNULL(@empId,'')='' or (Employee_Code_Id IN (select EmployeeID from #EmployeeID)))
		and(ISNULL(@EmployeeName,'')='' or (Employee_Code_Id IN (select * from #EmployeeName)))
		group by el.EmployeeId
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from 
	(
		select max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		group by ed.EmployeeId
	) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	and ED.DesignationId is not null
	
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeCategory,0)=0 or ec.CategoryId=@EmployeeCategory)
		group by ec.EmployeeId,Employee_Code_Id,emp.SwipeCardNo 
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeType,0)=0 or et.TypeId=@EmployeeType)
		group by et.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	and EType.TypeId is not null
	
	insert into @EmpId_Numeric 
	select Employee_code_Id  AS EmpId from TA_Tbl_Employee 
	INNER JOIN #EmpLevel EL ON TA_Tbl_Employee.Employee_Id=EL.EmployeeId 
	where TA_Tbl_Employee.Employee_Firstname<>'Administrator' and PatIndex('%[^0-9]%',Employee_code_Id) = 0 order by EmpId ASc
	
	select @IndividualUserStatus=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0
	--Testing purpose commented this line on 21-07-2022
	--IF(@ApplnMode = 0)
	--	BEGIN
	--		DECLARE @Deleted int	
	--		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
	--		begin
	--			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
	--			SET @Deleted=1
	--		end			
	--		UPDATE TA_Tbl_Employee SET
	--		Isdeleted = 1,
	--		Employee_Status = 0,
	--		InActiveDate = DATEADD(D, 1, DateOfJoining)
	--		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> '18000000') AND
	--		Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
	--		if @Deleted=1
	--			begin
	--				ENABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
	--			end
	--	END
		

	Create table #Temp_TA_Tbl_EmailScheduled_Employees(Employee_id int,ScheduleId int)
	Insert into #Temp_TA_Tbl_EmailScheduled_Employees
	select Employee_id,ScheduleId from TA_Tbl_EmailScheduled_Employees where ScheduleId=@ScheduleID
	SELECT	E.Employee_Id,
			E.Employee_Code_Id,
			E.Employee_FirstName + ' '+ isnull(E.Employee_LastName,'')AS Employee_FirstName,
			case when E.Employee_Status=1 then 'Active' else 'InActive' end Employee_Status,
			case when E.IsDeleted=1 then 'True' else 'False' end Isdeleted,
			T.TitleName,
			case when isnull(ESE.Employee_id,0)=0 then 0 else 1 end emailScheduler_flag,
			E.EmailId,
			E.Mobile_number,
			E.SwipeCardNo,
			E.Contact_Address,
			groupName, 
			E.Father_name,
			E.Mother_name,
			E.DateofBirth,
			E.DateofBirth_Record,
			E.Blood_Group,
			E.Permanent_Address,
			E.Phone_Number,
			E.Mobile_Number,
			E.Gender,
			E.Marital_status,
			E.Personal_mailid,
			E.Passport_No,
			E.Passport_expirydate,
			E.Visa_No,
			E.Visa_expirydate,
			E.Vehicle_No,
			E.Anniversary_Date,
			E.DateOfJoining,
			Reporting_To=ER.Employee_Code_Id + ' - '+ ER.Employee_FirstName + ' '+ isnull(ER.Employee_LastName,''),
			Leave_Sanc_Authority=ES.Employee_Code_Id + ' - '+es.Employee_FirstName + ' '+ isnull(es.Employee_LastName,''),
			CompOff_Eligible=case when E.CompOff_Eligible=1 then 'Yes' else 'No' end,
			OT_Eligible=case when E.OT_Eligible=1 then 'Yes' else 'No' end,
			Report_Exclude=case when E.Report_Exclude=1 then 'Yes' else 'No' end,
			E.InActiveDate,
			E.CustomField1,
			E.CustomField2,
			E.CustomField3,
			E.CustomField4,
			E.CustomField5,
			[Imported]=case when E.IsImported=1 then 'Yes' else 'No' end,
			MobileClockIn=case when E.MobileClockInOUt=1 then 'Yes' else 'No' end,
			DepartmentName=ld.name,
			C.CategoryName,
			Typ.TypeName,
			E.Time_Stamp as CreatedDate
			FROM TA_Tbl_Employee E
			inner JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
			inner JOIN #EmpLevel ON E.Employee_Id = #EmpLevel.EmployeeId
			inner JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
			INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId
			Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId
			inner join Ta_Tbl_levelDetails ld on #LevelRights.LevelId=ld.id
			left outer join #EmpType on #EmpType.employeeid=e.Employee_Id
			inner join TA_Tbl_Type typ on typ.TypeId=#EmpType.TypeId
			left outer join #Temp_TA_Tbl_EmailScheduled_Employees ESE on ESE.Employee_id=e.Employee_Id
			left outer join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id
			inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
			left outer join ta_tbl_usergroup ug on E.UserGroup_Id=ug.groupId
			left outer join TA_Tbl_Employee er on e.Reporting_To=er.Employee_Id
			left outer join TA_Tbl_Employee es on e.Leave_Sanc_Authority=es.Employee_Id
			WHERE E.Employee_FirstName<>'Administrator' and (ESE.ScheduleId is null or ESE.ScheduleId = @ScheduleID)
			and(@SwipeOpt='Not Exists' or e.swipecardno is not null and e.swipecardno!='')
			and(@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			and(ISNULL(@FilterUserGroup,0)=0 or E.UserGroup_Id= @FilterUserGroup)
			and(ISNULL(@Reportingto,0)=0 or E.Reporting_To=@Reportingto)
			and(ISNULL(@ApprovalAuthority,0)=0 or E.Leave_Sanc_Authority=@ApprovalAuthority)
			and E.EmailId!=''
			--and(ISNULL(@EmailAvail,0)=0 or (@EmailAvail=1 and E.EmailId is not null and E.EmailId<>'') or (@EmailAvail=2 and (E.EmailId is null or E.EmailId='' )))
			and(isnull(@IndividualUserStatus,0)=0 or E.Employee_Id =@IndividualUserStatus)
			ORDER BY E.Employee_Id	
	drop table #EmpLevel      
	drop table #LevelRights
	drop table #EmpDesignation	 
	drop table #EmployeeID
	drop table #EmployeeName
	drop table #EmpCategory
	drop table #EmpType
	drop table #Temp_TA_Tbl_EmailScheduled_Employees
	drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation] '03/31/2018',62,'SuperAdmin',0,1,'7,1'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]
(
	@ToDat datetime,
	@InsertedYearSettingsID int,
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int,
    @WeekOff VARCHAR(25)
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,TopParentLevelId int,EffectiveDate datetime,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
--insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
--select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) ELevel
--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,[dbo].[Func_TA_GetParentIds](EL.LEVELID),ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Shift_Id int)
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,
	dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,
	ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''') as EmployeeName,Ta_Tbl_Shift.Shift_Id '
	set @sqlQuery = @sqlQuery + ' from ta_tbl_Employee '
    set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_Shift on #EmpLevel.TopParentLevelId = Ta_Tbl_Shift.Level_id'
	set @sqlQuery = @sqlQuery + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1 and Ta_Tbl_Shift.DefaultShift=1)'
	set @sqlQuery = @sqlQuery + '  order by ta_tbl_Employee.Employee_FirstName '
	exec(@sqlQuery)
	Declare @StartMonth as int
	Declare @EndMonth as int
	declare @StartYear as int
	Declare @EndYear as int
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @MonthCount as int
	Declare @MonthName as varchar(10)
 SET @StartYear = (select Year(Fromdate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndYear = (select Year(Todate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 	
 SET @StartMonth = (select Month(Fromdate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndMonth = (select Month(Todate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @StartDate = (select Fromdate from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndDate = (select Todate from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @MonthCount = (SELECT DATEDIFF(MONTH, FromDate, ToDate)+1 from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID)
 Delete ta_tbl_permanentshiftAllocation where ((year=@StartYear and month>=@StartMonth) or (year=@EndYear and month<=@EndMonth)) 
 IF (@StartDate <= @EndDate)
	BEGIN
		Declare @Month int 
		Declare @Year int 
		Declare @InsertedMonth int
		Declare @MonthStartDate nvarchar(50)
		SET @Month= @StartMonth
		SET @Year= @StartYear
		SET @InsertedMonth=1
		While (@MonthCount>=@InsertedMonth)
			BEGIN
				SET @MonthName= (Select CONVERT(varchar(3),DateName( month , DateAdd( month , @Month , -1 ))))	
				Declare @date29 int				
				if(@year%4=0)
				begin
					set @date29=29					
				end
				else
				begin
					set @date29=28					
				end
				Declare @DynamicQuery varchar(max)
				set @DynamicQuery=''
				set @DynamicQuery=@DynamicQuery+' insert into TA_Tbl_PermanentShiftAllocation 
				 SELECT E.EmployeeAutoID '+','+  convert(varchar(4),@Year) + ',' +  convert(varchar(4),@Month)+',
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''01-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''02-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''03-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''04-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''05-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''06-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''07-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''08-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''09-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''10-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''11-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''12-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''13-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''14-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''15-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''16-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''17-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''18-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''19-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''20-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''21-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''22-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''23-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''24-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''25-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''26-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''27-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''28-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END)'
				if(@MonthName='Feb')
					begin
						set @DynamicQuery=@DynamicQuery+',
						(CASE WHEN (('''+ convert(varchar(4),@MonthName) +'''=''Feb'') AND (DATEADD(D, -1, (''01-Mar-' + CONVERT(varchar(6),@Year)+''')) = 29)) THEN 
								(
									CASE	WHEN '''+convert(varchar(15),@WeekOff) +''' LIKE ''%'' +  CAST(DATEPART(DW, '''+CONVERT(varchar(6),@date29)+'-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 
											ELSE E.Shift_Id 
									END
								) 
								ELSE 0 
						END),0,0'
					end
				else if(@MonthName NOT IN ('Apr', 'Jun', 'Sep', 'Nov'))
					begin
						set @DynamicQuery=@DynamicQuery+',
						CASE WHEN '''+ convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''29-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END,						
						CASE WHEN '''+ convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''30-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END,
						CASE WHEN '''+ convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''31-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END'
					 end
				else
					begin	
						set @DynamicQuery=@DynamicQuery+',	
						(CASE WHEN '''+ convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''29-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),									
						(CASE WHEN '''+ convert(varchar(15),@WeekOff) +''' LIKE ''%'' + CAST(DATEPART(DW, ''30-' + convert(varchar(4),@MonthName) + '-' + CONVERT(varchar(6),@Year)+''') AS VARCHAR(8)) + ''%'' THEN -1 ELSE E.Shift_Id END),0'
					end
				set @MonthStartDate=  convert(varchar(5),@Year)+'-'+ convert(varchar(5),@Month)+'-01 00:00:00.000'
				set @DynamicQuery=@DynamicQuery + ','+convert(varchar(5),@LoggedInEmployeeId)+','''+ convert(varchar(50),Getdate()) +''','''+ convert(varchar(50),@MonthStartDate) +''' From #TempEmployee E'
				Execute (@DynamicQuery)
				SET @Month = (@Month+1)
				IF (@Month=13)
					BEGIN
						SET @Month = 1
						SET @Year = @StartYear+1
					END
				SET @InsertedMonth = @InsertedMonth+1
			END	
				SET @StartDate = DateAdd(Day, 365, @StartDate) 
	END
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_EmpCategory]'2014-09-11','787,788,789,8,888',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpCategory]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeCategory int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here		
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql='
		select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 '
	if (@Employee_Code_Id<>'')
		if(@employeeCategory<>0 and @employeeCategory!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and ec.CategoryId='+convert(varchar(20),@employeeCategory)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	else 
		if(@employeeCategory<>0 and @employeeCategory!='')
			BEGIN					
				Set @sql=@sql+' and ec.CategoryId='+convert(varchar(20),@employeeCategory)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	Set @sql=@sql+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and ECategory.CategoryId is not null '	
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory_MusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 06-08-2015 02.30 pm
-- Description:	Get the employee details based on selecte levels
-- [Proc_TA_EmpCategory_MusterRoll]'2014-09-11','787,788,789,8,888',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpCategory_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeCategory int,
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here		
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql='	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
					from TA_Tbl_EmployeeCategory	ec 
					inner join ta_tbl_employee		emp	on ec.EmployeeId = emp.Employee_Id
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 
					group by ec.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)EmpCategory
				inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
				AND ECategory.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and ECategory.CategoryId is not null '
	if (@Employee_Code_Id<>'')
		if(@employeeCategory<>0 and @employeeCategory!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and ECategory.CategoryId='+convert(varchar(20),@employeeCategory)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	else 
		if(@employeeCategory<>0 and @employeeCategory!='')
			BEGIN					
				Set @sql=@sql+' and ECategory.CategoryId='+convert(varchar(20),@employeeCategory)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_EmpDesignation]'2014-11-23','100,105,',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpDesignation]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@DesignationId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql='	select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
				select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
				inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 '
	if (@Employee_Code_Id<>'')
	begin
		if(@DesignationId<>0 and @DesignationId!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and ED.DesignationId='+convert(varchar(20),@DesignationId)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	end
	else 
		if(@DesignationId<>0 and @DesignationId!='')
			BEGIN					
				Set @sql=@sql+' and ED.DesignationId='+convert(varchar(20),@DesignationId)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	Set @sql=@sql + ' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and ED.DesignationId is not null '	
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation_MusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]'2014-09-11','',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpDesignation_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@DesignationId varchar(50),
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql='	select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
					inner join ta_tbl_employee		emp	on ed.EmployeeId = emp.Employee_Id 
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 group by ed.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)EDesig
				inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
				AND ED.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and ED.DesignationId is not null '
	if (@Employee_Code_Id<>'')
		if(@DesignationId<>0 and @DesignationId!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and ED.DesignationId='+convert(varchar(20),@DesignationId)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	else 
		if(@DesignationId<>0 and @DesignationId!='')
			BEGIN					
				Set @sql=@sql+' and ED.DesignationId='+convert(varchar(20),@DesignationId)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeaveAvailed]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_EmpLeaveAvailed '94'
-- select * from ta_tbl_leaveApplication where employee_id=32 and yearSettings_Id=3 and type='Leave'
--update ta_tbl_leaveApplication set numberofDays=4.0 where CheckedIDs=49 LeaveApplication_Id=512
-- =============================================
-- Author:		<Angeswaran.S>
-- Create date: <06-Apr-2012>
-- Description:	<Pop up window for Employee Leave availed>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLeaveAvailed]
	-- Add the parameters for the stored procedure here
	@Employee_code_Id varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	Declare @EmployeeId int	
	Declare @StartMonth int
	Declare @RemainingMonth int
	Declare @Startyear int
	Declare @EndYear int
	--Declare @RemainingMonthUpdate int
	select @EmployeeId=Employee_Id from TA_Tbl_Employee where Employee_Code_Id= @Employee_code_Id
	select @StartMonth=DATEPART(MONTH ,FromDate),@Startyear=StartYear,@EndYear=EndYear from TA_Tbl_YearSetting where IsActive=1 
	--set @RemainingMonthUpdate=@StartMonth
	select DATENAME(month,LA.Leave_FromDate)  as month,sum(LA.NumberOfDays) as NumberofDays,
	case 				
		when DATENAME(month,LA.Leave_FromDate)='January' then 1
		when DATENAME(month,LA.Leave_FromDate)='February' then 2
		when DATENAME(month,LA.Leave_FromDate)='March' then 3
		when DATENAME(month,LA.Leave_FromDate)='April' then 4	
		when DATENAME(month,LA.Leave_FromDate)='May' then 5    
		when DATENAME(month,LA.Leave_FromDate)='June' then 6
		when DATENAME(month,LA.Leave_FromDate)='July' then 7      
		when DATENAME(month,LA.Leave_FromDate)='August' then 8      
		when DATENAME(month,LA.Leave_FromDate)='September' then 9 
		when DATENAME(month,LA.Leave_FromDate)='October' then 10
		when DATENAME(month,LA.Leave_FromDate)='November' then 11 
		when DATENAME(month,LA.Leave_FromDate)='December' then 12 
    end 'OrderBy' into #FinalLeaveApplicationData
	from TA_Tbl_LeaveApplication LA 
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id where LA.Employee_Id=@EmployeeId and YS.IsActive=1 and 
	LA.Type <> 'Comp Off' and LA.IsDeleted=0 and LA.Status='Approved' group by DATENAME(month,LA.Leave_FromDate)	
	Update #FinalLeaveApplicationData set MONTH=MONTH +' - ' +CONVERT(varchar(20), @Startyear) where OrderBy >=@StartMonth
	Update #FinalLeaveApplicationData set MONTH=MONTH +' - ' +CONVERT(varchar(20),@EndYear) where OrderBy<@StartMonth
	Select MONTH,NumberofDays from #FinalLeaveApplicationData Order by OrderBy
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[Proc_TA_EmpLeavePolicy] 
(
	@PolicyID INT=1
)
as
Begin
	SET NOCOUNT ON;
	select LP.Policy_Id,PolicyName,LT.LeaveType_Id,LeaveType,MaxDays_applicable,MaxDays_Month,
	LeaveDescription=LeaveDescription + ' ('+LeaveType+')' ,
	IsProrataRequired=isnull(IsProrataRequired,1),IsDocProofRequired=isnull(IsDocProofRequired,1)
	from TA_Tbl_LeavePolicyDetails LP 
	INNER JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id=LP.LeaveType_Id 
	INNER JOIN TA_Tbl_LeavePolicy L ON L.Policy_Id=LP.Policy_Id 
	where LP.policy_id=@PolicyID
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    -- =============================================  
Author		:   	Prabakaran.P
ALTER  date	:   
Description	:	select Emp Leave Policy   
Modified by	:	
Modified on	:	
Description	:	Display Employee Leave Policy of active year Based on employee Leave
			Policy Year Setting Id
--Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure 152
-- =============================================  
*/
CREATE  PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]   
@EmpID INT  
AS 
BEGIN  
 SET NOCOUNT ON;  
SELECT ELPD.LeaveType_Id,L.LeaveType,isnull(sum(ELPD.No_Of_Days),0.0) as No_Of_Days FROM TA_Tbl_Emp_LeavePolicyDetails ELPD  inner join Ta_tbl_LeavePolicy LP on ELPD.Policy_Id =LP.Policy_Id inner join Ta_Tbl_Emp_LeavePolicy ELP on ELP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id LEFT OUTER JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=ELPD.LeaveType_Id WHERE EmpID=@EmpID AND ELPD.Isdeleted=0  AND YS.Isactive=1 group by ELPD.LeaveType_Id,L.LeaveType
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
    -- =============================================    
Author:  Arun vinoth    
ALTER  date: 30/07/2007    
Description: select Emp Leave Policy     
Modified by : Prabakaran.P  
Modified on : 15-Feb-08  
Description : Display Employee Leave Policy of active year Based on employee Leave  
Policy Year Setting Id  
Modified By:Manikandan.RR
Modified Date:12-Jul-2019 03:45 PM
-- =============================================    
*/  
CREATE PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]     
	@EmpID INT    
AS   
BEGIN    
	SET NOCOUNT ON;    
	SELECT ELPD.Emp_LeavePolicyId,ELPD.Policy_ID,LP.PolicyName,ELPD.LeaveType_Id, L.LeaveType,ELPD.No_Of_Days ,LeaveDescription=LeaveDescription + ' ('+LeaveType+')'
	FROM TA_Tbl_Emp_LeavePolicyDetails ELPD inner join Ta_tbl_LeavePolicy LP on ELPD.Policy_Id =LP.Policy_Id 
	inner join Ta_Tbl_Emp_LeavePolicy ELP on ELP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId 
	inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id 
	LEFT OUTER JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=ELPD.LeaveType_Id 
	WHERE ELPD.EmpID=@EmpID AND ELPD.Isdeleted=0  AND YS.Isactive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLevel]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
    -- Insert statements for procedure here
	Declare @sql varchar(max)
	Set @sql='	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
				select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
				inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId				
				AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and EL.LevelId is not null '	
	if (@Employee_Code_Id<>'')
		begin					
			Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
		End
	else
		Begin				
			Set @sql=@sql 
		end	
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel_MusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 06-08-2015
-- Description:	Get the employee details based on selecte levels
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLevel_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@UserGroupName varchar(250),
	@ParentId int,
	@EmployeeName varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @NextString nvarchar(4000)
	declare @Pos int
	declare @NextPos int
	declare @CommaCheck nvarchar(1) 
	declare @Delimiter nvarchar (10)
	declare @String nvarchar (max)
	if (@Employee_Code_Id<>'')
		begin			
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end	
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
    -- Insert statements for procedure here
	Declare	@sql varchar(max)
	Set @sql='	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
				(
					select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
					from TA_Tbl_EmployeeLevel el					
					inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights on #LevelRights.LevelId = EL.LevelId
					where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId				
				AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and EL.LevelId is not null
			'	
	if (@Employee_Code_Id<>'')
		begin					
			Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
		End
	else
		Begin				
			Set @sql=@sql 
		end	
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Employee_ForShiftReAllocation] '05/23/2011','05/23/2011','1',18,'','SuperAdmin',323,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoggedInEmployeeId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoggedInEmployeeId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id nvarchar(20),EmployeeAutoID bigint,EmpName nvarchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id nvarchar(20),EmployeeAutoID bigint,EmpName nvarchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day nvarchar(20),ShiftId int,Date nvarchar(20))
	create table #TempShiftAllocatedEmployeeTS (EmployeeID int,Year int,Month int,Day nvarchar(20),ShiftId int,Date nvarchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''') as EmployeeName '
	set @sqlQuery = @sqlQuery + ' from ta_tbl_Employee '
    set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)'
	if not(@EmployeeName='')
	begin
		set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + '' ''+  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if not (@empId='')
	begin
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_Employee.Employee_code_id= ''' + @empId + ''' )'
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	set @sqlQuery = @sqlQuery + '  order by ta_tbl_Employee.Employee_FirstName '
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployeeTS (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 or ShiftId=0
	delete from #TempShiftAllocatedEmployeeTS where isDate(Date) = 0 or ShiftId=0
	insert into #TempShiftAllocatedEmployeeTS  
	select * from #TempShiftAllocatedEmployee where 
	not exists (select * from #TempShiftAllocatedEmployeeTS where EmployeeID=#TempShiftAllocatedEmployee.EmployeeID
	and Date=#TempShiftAllocatedEmployee.Date) and Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from #TempEmployeeWithDate
	--select * from #TempShiftAllocatedEmployee where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from  #TempShiftAllocatedEmployeeTS where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,'0' as SelectedRecords from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	delete from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where LoggedInEmployeId = @LoggedInemployeeId
    -- select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= cast(E.Date as datetime) and (E.Date between dateadd(dd,-1,@fromDat) 
	--and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId<>0
	--and PS.ShiftId=@shift
    --inserts the employee with current shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId=@shift
	--Updates the Previous day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.PreviousDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--Updates the Next day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.NextDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
	--select * from ta_tbl_employee
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
drop table #TempShiftAllocatedEmployeeTS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Employee_ForShiftReAllocation1] '05/23/2011','05/23/2011','1',18,'','SuperAdmin',323,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	create table #TempShiftAllocatedEmployeeTS (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''') as EmployeeName '
	set @sqlQuery = @sqlQuery + ' from ta_tbl_Employee '
    set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)'
	if not(@EmployeeName='')
	begin
		set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if not (@empId='')
	begin
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_Employee.Employee_code_id= ''' + @empId + ''' )'
	end
	set @sqlQuery = @sqlQuery + '  order by ta_tbl_Employee.Employee_FirstName '
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployeeTS (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 or ShiftId=0
	delete from #TempShiftAllocatedEmployeeTS where isDate(Date) = 0 or ShiftId=0
	insert into #TempShiftAllocatedEmployeeTS  
	select * from #TempShiftAllocatedEmployee where 
	not exists (select * from #TempShiftAllocatedEmployeeTS where EmployeeID=#TempShiftAllocatedEmployee.EmployeeID
	and Date=#TempShiftAllocatedEmployee.Date) and Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from #TempEmployeeWithDate
	--select * from #TempShiftAllocatedEmployee where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from  #TempShiftAllocatedEmployeeTS where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,'0' as SelectedRecords from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	delete from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where LoggedInEmployeId = @LoggedInemployeeId
    -- select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= cast(E.Date as datetime) and (E.Date between dateadd(dd,-1,@fromDat) 
	--and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId<>0
	--and PS.ShiftId=@shift
    --inserts the employee with current shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId=@shift
	--Updates the Previous day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.PreviousDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--Updates the Next day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.NextDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
	--select * from ta_tbl_employee
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
drop table #TempShiftAllocatedEmployeeTS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_EmployeeAutoIDGet]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Proc_Ta_EmployeeAutoIDGet]

@Employee_Code_Id nvarchar(50)= 'E015'
AS
BEGIN
	
	Select * from TA_Tbl_Employee Where 
	Employee_Code_Id = @Employee_Code_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBonusLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- Author:  Kumuthini      
-- ALTER  date: 12-Jan-09         
-- Proc_TA_EmployeeBonusLeave '','','',0,0,'SuperAdmin','1',3      
-- Description: Employee Bonus Leave Details      
-- =============================================      
CREATE      PROCEDURE [dbo].[Proc_TA_EmployeeBonusLeave]
 @Employee_ID int,
 @EmployeeId nvarchar(100),      
 @EmployeeName nvarchar(50),      
 @LevelID nvarchar(max),      
 @EmployeeCategory int,      
 @EmployeeType int,      
 @UserGroupName nvarchar(250),      
 @GradeLevel nvarchar(20),  
 @YearSettingsId int,
 @EmpSwipeCard nvarchar(20),
 @ParentID int       
AS      
BEGIN      
	SET NOCOUNT ON;
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
declare @sqlQuery as nvarchar(max)   
create table #empBonusLeave(Department nvarchar(500),Department1 nvarchar(500),EmployeeCodeId nvarchar(500),EmployeeId nvarchar(500),EmpAutoId int,DateOfJoining datetime,EmpName nvarchar(500),BonusLeaveQuota int,BonusLeaveTaken int,BonusLeaveAvailable int,YearSettings_Id int)  
  set @sqlQuery = ''   
  set @sqlQuery = @sqlQuery + 'SELECT replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as Department, replace(dept.name,''&amp;'',''&'') as Department1, dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId, dbo.TA_Tbl_Employee.SwipeCardNo as EmployeeId, dbo.TA_Tbl_Employee.Employee_Id as EmpAutoId,dbo.TA_Tbl_Employee.DateOfJoining,'      
  set @sqlQuery = @sqlQuery + ' ISNULL(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as EmpName,''0'' AS BonusLeaveQuota,''0'' AS BonusLeaveTaken,''0'' AS BonusLeaveAvailable,''' + cast(@YearSettingsId as nvarchar(20)) + ''' as YearSettings_Id '      
  set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_Employee '      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id'      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'      
  set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'       
  SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation edes ON ta_tbl_Employee.Employee_Id = edes.EmployeeId '      
  SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title tit ON tit.TitleId=edes.DesignationId '      
  SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade grd ON grd.Grade_ID = tit.GradeId '      
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=edes.EffectiveDate and #EmpDesignation.employeeid=edes.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
 set @sqlQuery = @sqlQuery + ' where   (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'') '      
if(@UserGroupName<>'SuperAdmin')      
  begin      
  set @sqlQuery = @sqlQuery + ' AND grd.Grade_Level>=' + @GradeLevel + ' '      
  end      
if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
  if not(@EmployeeName='')      
  begin      
   set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'      
  end      
  if not (@EmployeeId='')      
  begin      
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '      
  end      
  If Not (@EmpSwipeCard = '')  
    Begin  
		  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End 
  if not (@EmployeeCategory=0)      
  begin      
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))      
  end      
  if not (@EmployeeType=0)      
  begin      
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))      
  end      
  set @sqlQuery = @sqlQuery + ' order by dbo.TA_Tbl_Employee.Employee_code_Id '      
insert into #empBonusLeave exec(@sqlQuery)   
update #empBonusLeave set BonusLeaveQuota=EBL.BonusLeaveQuota  
from TA_Tbl_EmployeeBonusLeave EBL   
inner join #empBonusLeave TBL  
on   
EBL.EmployeeId=TBL.EmpAutoId and  
EBL.YearSettingId=TBL.YearSettings_Id  
select * from #empBonusLeave  
drop table #empBonusLeave  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBulkConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- 
/*
Proc_TA_EmployeeBulkConfiguration
'<Dst_bulkimport>
  <EmployeeBulkImport>
    <Employee_Id>758</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress />
    <PermanentAddress />
    <PhoneNumber />
    <MobileNumber />
    <ReportingTo />
    <ApprovalAuthority />
    <InActive />
    <BasicSalary>5000</BasicSalary>
  </EmployeeBulkImport>
</Dst_bulkimport>',17,1


Proc_TA_EmployeeBulkConfiguration 
'<Dst_bulkimport>
  <EmployeeBulkImport>
    <Employee_Id>787</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>1</ContactAddress>
    <PermanentAddress>100</PermanentAddress>
    <PhoneNumber>04222676867</PhoneNumber>
    <MobileNumber>9894159117</MobileNumber>
    <ReportingTo>758</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>788</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>2</ContactAddress>
    <PermanentAddress>101</PermanentAddress>
    <PhoneNumber>04222676868</PhoneNumber>
    <MobileNumber>9894159118</MobileNumber>
    <ReportingTo>758</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>789</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>3</ContactAddress>
    <PermanentAddress>102</PermanentAddress>
    <PhoneNumber>04222676869</PhoneNumber>
    <MobileNumber>9894159119</MobileNumber>
    <ReportingTo>789</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>790</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>4</ContactAddress>
    <PermanentAddress>103</PermanentAddress>
    <PhoneNumber>04222676870</PhoneNumber>
    <MobileNumber>9894159120</MobileNumber>
    <ReportingTo>788</ReportingTo>
    <ApprovalAuthority>758</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>791</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>5</ContactAddress>
    <PermanentAddress>104</PermanentAddress>
    <PhoneNumber>04222676871</PhoneNumber>
    <MobileNumber>9894159121</MobileNumber>
    <ReportingTo>790</ReportingTo>
    <ApprovalAuthority>788</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>792</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>6</ContactAddress>
    <PermanentAddress>105</PermanentAddress>
    <PhoneNumber>04222676872</PhoneNumber>
    <MobileNumber>9894159122</MobileNumber>
    <ReportingTo>788</ReportingTo>
    <ApprovalAuthority>4</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>793</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>7</ContactAddress>
    <PermanentAddress>106</PermanentAddress>
    <PhoneNumber>04222676873</PhoneNumber>
    <MobileNumber>9894159123</MobileNumber>
    <ReportingTo>787</ReportingTo>
    <ApprovalAuthority>4</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>794</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>8</ContactAddress>
    <PermanentAddress>107</PermanentAddress>
    <PhoneNumber>04222676874</PhoneNumber>
    <MobileNumber>9894159124</MobileNumber>
    <ReportingTo>4</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>795</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>9</ContactAddress>
    <PermanentAddress>108</PermanentAddress>
    <PhoneNumber>04222676875</PhoneNumber>
    <MobileNumber>9894159125</MobileNumber>
    <ReportingTo>1</ReportingTo>
    <ApprovalAuthority>1</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>796</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>10</ContactAddress>
    <PermanentAddress>109</PermanentAddress>
    <PhoneNumber>04222676876</PhoneNumber>
    <MobileNumber>9894159126</MobileNumber>
    <ReportingTo>795</ReportingTo>
    <ApprovalAuthority>1</ApprovalAuthority>
  </EmployeeBulkImport>
</Dst_bulkimport>',14,0
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeBulkConfiguration]
	-- Add the parameters for the stored procedure here
	@Data XML=NULL, @Eligible int, @FromYesToNo int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @XMLParams INT	
	DECLARE @ErrMsg VARCHAR(MAX)
	Declare @ErrIds VARCHAR(MAX)
	Declare @SQLQuery varchar(max)
	Declare @SQLQuery1 varchar(max)
	BEGIN TRY
		BEGIN TRAN
			--Create table #TempEmployee(Employee_Code_Id varchar(50))			
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @Data
			--insert into #TempEmployee
			--select E.Employee_Code_Id 
			--FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
			--		(Employee_Code_Id VARCHAR(50)) Tbl
			--		inner JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			--		AND E.IsDeleted = 0 AND E.Employee_Status = 1			
			if(@Eligible=1)
				begin
					update TA_Tbl_Employee set OT_Eligible=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=2)
				begin
					update TA_Tbl_Employee set CompOff_Eligible=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=3)
				begin
					update TA_Tbl_Employee set CompOff_Eligible=case when @FromYesToNo=1 then 1 else 0 end,OT_Eligible=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=4)
				begin				
					update TA_Tbl_Employee set Report_Exclude=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end				
			else if(@Eligible=6)
				begin				
					update TA_Tbl_Employee set Hostel=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=7)
				begin					
					update TA_Tbl_Employee set UserGroup_Id=ug.groupId
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport',2) WITH 
					(Employee_Id VARCHAR(50),UserGroup varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					inner join TA_Tbl_Usergroup ug on ug.groupName=Tbl.UserGroup
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end		
			else if(@Eligible=8)
				begin				
					update TA_Tbl_Employee set EmailId=Tbl.EmailID
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),EmailID varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end				 
			else if(@Eligible=9)
				begin				
					update TA_Tbl_Employee set Personal_mailid=Tbl.PersonalEmailID
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),PersonalEmailID varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=10)
				begin				
					update TA_Tbl_Employee set Contact_Address=Tbl.ContactAddress
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),ContactAddress varchar(500)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=11)
				begin				
					update TA_Tbl_Employee set Permanent_Address=Tbl.PermanentAddress
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),PermanentAddress varchar(500)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=12)
				begin				
					update TA_Tbl_Employee set Phone_Number=Tbl.PhoneNumber
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),PhoneNumber varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=13)
				begin				
					update TA_Tbl_Employee set Mobile_Number=Tbl.MobileNumber
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),MobileNumber varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=14)
				begin				
					update TA_Tbl_Employee set Reporting_To=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=Tbl.ReportingTo)
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
						(Employee_Id VARCHAR(50),ReportingTo varchar(50)) Tbl
						LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
						AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=15)
				begin				
					update TA_Tbl_Employee set Leave_Sanc_Authority=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=Tbl.ApprovalAuthority)
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50),ApprovalAuthority varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=16)
				begin				
					update TA_Tbl_Employee set	InActive_Status=case when @FromYesToNo=1 then 1 else 0 end,
												InActiveDate=case when @FromYesToNo=1 then tbl.InActive end,
												Employee_Status=case when @FromYesToNo=1 then 0 else 1 end
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50), InActive varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			   else if(@Eligible=17)
				begin				
					update E set	E.Basic_Salary=tbl.BasicSalary
					--select Tbl.*
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50), BasicSalary varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
				--Code for vaigai--
				else if(@Eligible=18)
				begin
					update TA_Tbl_Employee set MobileClockInOUt=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
				
				else if(@Eligible=19)
				begin
					update TA_Tbl_Employee set SMSEnabled=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, '/Dst_bulkimport/EmployeeBulkImport', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end			
			   --Code for vaigai--

			EXEC SP_XML_RemoveDocument @XMLParams			
		COMMIT TRAN
	END TRY		
	BEGIN CATCH
		--SET @ErrMsg = ERROR_MESSAGE()
		--SET @ErrIds = @@ERROR
		ROLLBACK TRAN
		--RAISERROR(@ErrMsg, 16,@ErrIds, 'Error')
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name    :     Proc_TA_EmployeeCompOffOTSanction
Tables Included :      TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
                              TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
                              TA_Tbl_Grade,ta_tbl_shift
Created By        :     A.K.T.MOORTHI
Created On        :     20-July-2013
Description       :     To get the OT and CompOff Employee.
Modified By       :   A.K.T.MOORTHI
Modified On       :   06-Aug-2014
Description       :     Remove The Date Convertion In Expaire Date Calculation
UPDATE TA_Tbl_ProcessedData SET OverTimeStatus = 'Pending' WHERE Process_Rec_ID IN(1944, 1945, 2065)
EXEC [Proc_TA_EmployeeCompOffOTSanction] '2019/02/01','2019/02/28','14230','','1','0','0','SuperAdmin','0','All','',1, 97
exec Proc_TA_EmployeeCompOffOTSanction @FromDate='2015-04-01 00:00:00',@ToDate='2016-04-30 00:00:00',@EmpId='',@EmployeeName='',@LevelID='1',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName='SuperAdmin',@GradeLevel='5',@Status='All',@EmpSwipeCard='',@ParentId=1,@ApprovalEmpId='2'
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTSanction](
      @FromDate DATETIME,
      @ToDate DATETIME,
      @EmpId VARCHAR(100),
      @EmployeeName VARCHAR(50),
      @LevelID VARCHAR(8000),
      @EmployeeCategory INT,
      @EmployeeType INT,
      @UserGroupName VARCHAR(250),
      @GradeLevel VARCHAR(20),
      @Status VARCHAR(50),
      @EmpSwipeCard VARCHAR(20),
      @ParentId INT,
      @ApprovalEmpId VARCHAR(20)
)
AS
BEGIN
	set nocount on
   DECLARE @SQLQuery VARCHAR(MAX) 
   set @SQLQuery= ''
   declare @AUserGroup VARCHAR(100) 
   declare @AUserGroupType VARCHAR(100) 
   set @AUserGroup= ''
   set @AUserGroupType= ''
   DECLARE @Id INT
   DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
   set @Id = ISNULL(@ParentId, 0)
      SELECT @AUserGroup = ISNULL(UG.groupName, ''),@AUserGroupType=ISNULL(ReportsBasedOn,2) FROM TA_Tbl_Employee Emp
            INNER JOIN TA_Tbl_Usergroup UG ON UG.groupId = Emp.UserGroup_Id
      WHERE Employee_Id = @ApprovalEmpId
      if(@AUserGroupType='')
      begin
		set @AUserGroupType=2
	  end
      WHILE (NOT EXISTS(SELECT Id FROM Ta_Tbl_levelDetails WHERE id = @Id AND parentId = 0) AND @Id !=0)
      BEGIN
            SELECT @Id = parentId FROM Ta_Tbl_levelDetails WHERE id = @Id
      END
      declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](CAST(@ApprovalEmpId as int)) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](CAST(@ApprovalEmpId as int)) as EmpAutoId
--Temporary table's creation
      CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME)
      CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
      CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
      CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
      CREATE TABLE #LevelRights(LevelId INT)
      Create table #OTHours (Process_Rec_ID int,Employee_ID int,Employee_Code_ID nvarchar(20),Date varchar(20),Employee_FirstName nvarchar(Max),[Level Name] nvarchar(Max),HrsExtra nvarchar(20),ActHrsExtra nvarchar(20),ActExtraMins int,HrsExtraIn nvarchar(20),ExtraMins int,OverTimeStatus nvarchar(10),CompOffEligible int,OTEligible int,CompOffChecked int,OTChecked int,Status nvarchar(10),TopLevelID int)
      INSERT INTO #LevelRights 
            SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
      (
            [LevelId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
      (
            [EffectiveDate] ASC
      )ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
      (
            [DesignationId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
      (
            [EmployeeId] ASC
      ) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
      (
            [TypeId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
      (
            [EffectiveDate] ASC
      )ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
      (
            [CategoryId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
      (
            [EmployeeId] ASC
      ) ON [PRIMARY]
--Employee Level insert in Temporary table
      INSERT INTO #EmpLevel 
            SELECT EL.EmployeeId, EL.LevelId, MAX(EL.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeLevel EL
                  INNER JOIN TA_Tbl_Employee Emp ON EL.EmployeeId = Emp.Employee_Id       
            WHERE Emp.Isdeleted = 0 AND EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
            GROUP BY EL.EmployeeId, EL.LevelId
      INSERT INTO #EmpDesignation 
            SELECT ED.EmployeeId, ED.DesignationID, MAX(ED.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeDesignation ED
                  INNER JOIN TA_Tbl_Employee Emp ON ED.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
            GROUP BY ED.EmployeeID, ED.DesignationID
      INSERT INTO #EmpType 
            SELECT ET.EmployeeId, ET.TypeId, MAX(ET.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeType ET
                  INNER JOIN TA_Tbl_Employee Emp ON ET.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND ET.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ET.TypeId IS NOT NULL
            GROUP BY ET.EmployeeId, ET.TypeId
      INSERT INTO #EmpCategory
            SELECT EC.EmployeeId, EC.CategoryId, MAX(EC.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeCategory EC
                  INNER JOIN TA_Tbl_Employee Emp ON EC.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EC.CategoryId IS NOT NULL
            GROUP BY EC.EmployeeId, EC.CategoryId
      --CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''00:00''), 108)
      SET @SQLQuery = 'SELECT PD.Process_Rec_ID, Emp.Employee_Id, Emp.Employee_Code_Id, case when '+cast(@dateFormat as varchar(100))+'=106 then
					REPLACE(CONVERT(VARCHAR, PD.[Date],'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
					else CONVERT(VARCHAR, PD.[Date], '+cast(@dateFormat as varchar(100))+') end  AS [Date],'
      SET @SQLQuery = @SQLQuery + ' Emp.Employee_FirstName + SPACE(1) + ISNULL(Emp.Employee_LastName, '''') Employee_FirstName, REPLACE(LD.Name, ''&amp;'', ''&'') [Level Name],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN PD.HrsOT != ''00:00'' THEN PD.HrsOT WHEN PD.NormOT != ''00:00'' THEN PD.NormOT WHEN PD.OffOT != ''00:00'' THEN PD.OffOT WHEN PD.HolOT != ''00:00'' THEN PD.HolOT END) [HrsExtra],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN isnull(PD.ActHrsOT,PD.HrsOT) != ''00:00'' THEN isnull(PD.ActHrsOT,PD.HrsOT) WHEN isnull(PD.ActNormOT,PD.NormOT) != ''00:00'' THEN isnull(PD.ActNormOT,PD.NormOT) WHEN isnull(PD.ActOffOT,PD.OffOT) != ''00:00'' THEN isnull(PD.ActOffOT,PD.OffOT) WHEN isnull(PD.ActHolOT,PD.HolOT) != ''00:00'' THEN isnull(PD.ActHolOT,PD.HolOT) END) [ActHrsExtra],isnull(PD.ActOtMins,PD.OtMins) [ActExtraMins],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN PD.HrsOT != ''00:00'' THEN PD.HrsOT WHEN PD.NormOT != ''00:00'' THEN ''NormOTHrs'' WHEN PD.OffOT != ''00:00'' THEN ''WeekOffOT'' WHEN PD.HolOT != ''00:00'' THEN ''HolOT'' END) [HrsExtraIn],'
      SET @SQLQuery = @SQLQuery + ' PD.OtMins [ExtraMins], 
      (CASE WHEN ((''' + @AUserGroup + ''' = ''SuperAdmin'' OR ' + @ApprovalEmpId + ' = ISNULL(Emp.Reporting_To, 0) OR ' + @AUserGroupType + ' = 0) 
      AND (ISNULL(PD.OverTimeStatus, ''Pending'') = ''Pending'') AND (''' + @AUserGroup + ''' = ''SuperAdmin'' OR ' + @ApprovalEmpId + ' = ISNULL(Emp.Leave_Sanc_Authority, 0) OR ' + @AUserGroupType + ' = 0)) 
      THEN ''Forwarded'' ELSE ISNULL(PD.OverTimeStatus, ''Pending'') END) [OverTimeStatus],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN ((DATEADD(D, ISNULL(SS.VaildityCompOffDays, 0), PD.[Date]) < GETDATE()) OR (ISNULL(PD.OverTimeStatus, ''Pending'') = ''Approved'')) THEN 0 WHEN ((DATEDIFF(MI,''00:00'', ISNULL(SS.HalfDayCompOff, ''00:00'')) > ISNULL(PD.OtMins, 0)) OR ISNULL(PD.OtMins, 0) = 0) THEN 0 ELSE 1 END) [CompOffEligible],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN ((ISNULL(PD.OtMins, 0) = 0) OR (ISNULL(PD.OverTimeStatus, ''Pending'') = ''Approved'')) THEN 0 ELSE 1 END) [OTEligible],'
      SET @SQLQuery = @SQLQuery + ' ISNULL(OTS.CompOffEligible, 0) [CompOffChecked], ISNULL(OTS.OTEligible, 0) [OTChecked],'
      SET @SQLQuery = @SQLQuery + ' (CASE WHEN ''' + @AUserGroup + ''' = ''SuperAdmin'' OR ' + @ApprovalEmpId + ' = ISNULL(Emp.Leave_Sanc_Authority, 0) OR ' + @AUserGroupType + ' = 0 THEN ''Approved'' WHEN ((' + @ApprovalEmpId + ' = ISNULL(Emp.Reporting_To, 0)) AND (' + @ApprovalEmpId + ' = ISNULL(Emp.Leave_Sanc_Authority, 0))) THEN ''Approved'' WHEN ' + @ApprovalEmpId + ' = ISNULL(Emp.Reporting_To, 0) THEN ''Forwarded'' ELSE ''Pending'' END) [Status],'     
      SET @SQLQuery = @SQLQuery + CAST(@Id AS VARCHAR(15)) + ' [TopLevelId]'  
      SET @SQLQuery = @SQLQuery + ' FROM TA_Tbl_ProcessedData PD'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo'
      SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.EmployeeId = Emp.Employee_Id'
      SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id = ELP.LeavePolicy_Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId'
      --SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id'
      SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = ' + CAST(@Id AS VARCHAR(15))
      SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_OverTimeStatus OTS ON OTS.Process_RecID = PD.Process_Rec_ID'    
      SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel EL ON EL.EmployeeId = Emp.Employee_Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation ED ON ED.EmployeeId = Emp.Employee_Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType ET ON ET.EmployeeId = Emp.Employee_Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory EC ON EC.EmployeeId = Emp.Employee_Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = EL.LevelId'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
      SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'      
      SET @SQLQuery = @SQLQuery + ' WHERE PD.OtMins != 0 AND Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1'
      SET @SQLQuery = @SQLQuery + ' AND Emp.IsDeleted = 0 AND Emp.Employee_Status = 1 AND PD.[Date] BETWEEN ''' + CONVERT(VARCHAR(11), @FromDate, 101) + ''' AND ''' + CONVERT(VARCHAR(11), @ToDate, 101) + ''''
      SET @SQLQuery = @SQLQuery + ' AND YS.IsActive = 1'-- AND LP.OtDayWise = 1' AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''00:00''), 108) != ''00:00'' 
      IF(@UserGroupName <> 'SuperAdmin')
      BEGIN
            SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel  
      END
		if(@isReportingto > 0)
            BEGIN
               set @SQLQuery = @SQLQuery + ' and (Emp.Employee_ID IN (select * from #EmployeeIds)) '  
            END
      IF NOT(@EmployeeName = '')
      BEGIN
            SET @SQLQuery = @SQLQuery + ' AND (Emp.Employee_FirstName + '' '' + ISNULL(Emp.Employee_LastName, '''') LIKE ''' + @EmployeeName + '%'')'
      END
      IF(@EmployeeCategory <> 0)
      BEGIN
            SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@EmployeeCategory AS VARCHAR(10))
      END
      IF(@EmployeeType<>0)
      BEGIN
            SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@EmployeeType AS VARCHAR(10))
      END
      IF NOT(@EmpId='')
      BEGIN
            SET @SQLQuery = @SQLQuery + ' AND Emp.Employee_Code_Id = ''' + CAST(@EmpId AS VARCHAR(50)) + ''''
      END
      IF NOT(@EmpSwipeCard = '')  
    BEGIN
            SET @SQLQuery = @SQLQuery + ' AND Emp.SwipeCardNo = ''' + @EmpSwipeCard + ''''
      END
      SET @SQLQuery = @SQLQuery + ' ORDER BY PD.Employee_Code_Id, PD.[Date]'
      --print(@SQLQuery)
      insert into #OTHours EXEC(@SQLQuery)
      DECLARE @SQL nvarchar(max)
      set @SQL=''
      set @SQL='select * from #OTHours '
      IF NOT(@Status = '' OR @Status = 'All')
      BEGIN
            IF(@Status = 'Pending')
            BEGIN
                  SET @SQL = @SQL + ' where (OvertimeStatus IS NULL OR OvertimeStatus = ''' + @Status + ''')'
            END
            ELSE
            BEGIN
                SET @SQL = @SQL + ' where OvertimeStatus = ''' + @status + ''''
            END
    END
      EXEC(@SQL)
      DROP TABLE #EmpLevel
      DROP TABLE #EmpDesignation
      DROP TABLE #EmpType
      DROP TABLE #EmpCategory
      DROP TABLE #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	: Proc_TA_EmployeeOTStatus  
Description		: To Update the OverTime Status in ta_tbl_processedData  table
Tables Included : ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		: A.K.T.MOORTHI
Created On		: 22-July-2013
Modified By :  
Modified On :  
	EXEC [Proc_TA_EmployeeCompOffOTStatus]	'<NewDataSet>
  <Status>
    <Process_Rec_ID>1944</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>04/02/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>06:00</HrsExtra>
    <ExtraMins>360</ExtraMins>
    <OverTimeStatus>Approved</OverTimeStatus>
    <CompOffEligible>1</CompOffEligible>
    <OTEligible>1</OTEligible>
    <Status>Pending</Status>
  </Status>
  <Status>
    <Process_Rec_ID>1945</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>04/06/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>06:00</HrsExtra>
    <ExtraMins>360</ExtraMins>
    <OverTimeStatus>Approved</OverTimeStatus>
    <CompOffEligible>1</CompOffEligible>
    <OTEligible>1</OTEligible>
    <Status>Pending</Status>
  </Status>
  <Status>
    <Process_Rec_ID>2065</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>05/01/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>01:00</HrsExtra>
    <ExtraMins>60</ExtraMins>
    <OverTimeStatus>Pending</OverTimeStatus>
    <CompOffEligible>0</CompOffEligible>
    <OTEligible>0</OTEligible>
    <Status>Pending</Status>
  </Status>
</NewDataSet>'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTStatus]
	@Xml XML
As
BEGIN 
	DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,[Date] DATETIME, HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT)
	DECLARE @Index INT
	SET @Index = 0
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	INSERT INTO @TblRecords
		SELECT * FROM OPENXML(@Index, '/NewDataSet/ColumnValues')
		WITH(
			Process_Rec_ID BIGINT 'Process_Rec_ID',
			Employee_Id INT 'Employee_Id',
			[Date] DATETIME 'Date',
			HrsExtra VARCHAR(5) 'HrsExtra',
			ExtraMins INT 'ExtraMins',
			[Status] VARCHAR(50) 'Status',
			CompOffEligible BIT 'CompOffEligible',
			OTEligible BIT 'OTEligible'
		   ) AS OT 
	UPDATE TA_Tbl_ProcessedData SET OvertimeStatus = OT.OverTimeStatus FROM TA_Tbl_ProcessedData PD 	
	INNER JOIN @TblRecords OT ON OT.Process_RecID = PD.Process_Rec_ID
	EXEC sp_xml_removedocument @Index
	INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible)
		SELECT * FROM @TblRecords WHERE Process_RecID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus)
	UPDATE TA_Tbl_OverTimeStatus SET 
		Process_RecID = TR.Process_RecID,
		Employee_Id = TR.Employee_Id,
		[Date] = TR.[Date],
		HrsExtra = TR.HrsExtra,
		ExtraMins = TR.ExtraMins,
		OverTimeStatus = TR.OverTimeStatus,
		CompOffEligible = TR.CompOffEligible,
		OTEligible = TR.OTEligible
	FROM TA_Tbl_OverTimeStatus OTS
	INNER JOIN @TblRecords TR ON TR.Process_RecID = OTS.Process_RecID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffRequestionCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_EmployeeOTSanction  
Description : To get the OT Employee with Approval Status
*/  
-- [Proc_TA_EmployeeCompOffRequestionCount] 2,'IndividualUsers'
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffRequestionCount]
(
	@Employee_ID int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
	--select * from #EmpDesignation
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
		;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	--inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	--select @TopLevelId
	--update TA_Tbl_ShiftSettings set isRequestingforCompOff=1
	
	CREATE TABLE #TempProcessedData
	(
		[Process_Rec_ID] bigint,
		[Employee_Code_Id] nvarchar(20),
		[Date] datetime,
		[Shift_Id] int,
		[InTime] nvarchar(25),
		[OutTime] nvarchar(25),
		[HrsWork] nvarchar(10),
		[HrsOT] nvarchar(10),
		[NormOT] nvarchar(10),
		[OffOT] nvarchar(10),
		[HolOT] nvarchar(10),
		[EarlyOut] nvarchar(10),
		[LateIn] nvarchar(10),
		[Attendance] nvarchar(20),
		[WorkHrs] nvarchar(10),
		[HrsLess] nvarchar(10),
		[HrsExtra] nvarchar(10),
		[LateInMins] float,
		[EarlyOutMins] float,
		[ExtraMins] float,
		[OtMins] float,
		[OvertimeStatus] nvarchar(50),
		[TotalDays] numeric(18, 1),
		[LeaveCode] nvarchar(20),
		[LateEntryReason] nvarchar(260),
		[EarlyOutReason] nvarchar(260),
		[ProcessFlag] bit,
		[Status] nvarchar(50),
		[FNAttendanceCode] nvarchar(15),
		[ANAttendanceCode] nvarchar(15),
		[ActHrsOT] nvarchar(10),
		[ActNormOT] nvarchar(10),
		[ActOffOT] nvarchar(10),
		[ActHolOT] nvarchar(10),
		[ActOtMins] float,
		[AvailOtMins] float,
		[ExtraTime_Id] bigint
	)
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate,@ToDate=TODATE  from TA_Tbl_YearSetting where IsActive=1
	
	insert into #TempProcessedData 
	select OT.Process_RecID as 'Process_Rec_ID',E.Employee_Code_Id,OT.Date,p.Shift_Id,
	P.InTime,P.OutTime,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,
	p.EarlyOut,p.LateIn,p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,
	p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
	p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,
	p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id				
	from TA_Tbl_OverTimeStatus OT 
	inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
	inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id  
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
	where P.[Date] between @Fromdate and @ToDate and OT.isDelete=0 and OT.isRequest=1
	and OT.isdelete=0 and DateToExpired>=GETDATE()
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''	
	set @sqlQuery = @sqlQuery + 'select 
	count(case  when OverTimeStatus=''Approved'' and E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1  end)Approved,
	count(case  when OverTimeStatus=''Forwarded'' and E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1 end)Forwarded,
    count(case  when OverTimeStatus=''Pending'' and (E.Reporting_To=''' +cast(@Employee_Id as nvarchar(50))   + ''' or E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''') then 1  end)Pending 
    from #TempProcessedData TPD 
	INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.SwipeCardNo'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'	 
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' where TPD.AvailOtMins <> 0 AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 '
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	set @sqlQuery = @sqlQuery + ' And E.isdeleted=0 and E.report_exclude=0 and E.employee_status=1'
	exec (@sqlQuery)
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <22-Jan-2012>
-- Description:	<Comp off Sanction>
-- exec [Proc_TA_EmployeeCompOffSanction] '2012/01/01','2013/01/22','','','1','0','0','SuperAdmin','0','All','',1,'compoff'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffSanction] 
	-- Add the parameters for the stored procedure here
	(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(50),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @SanctionType varchar(25)   
    )
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  --Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
--/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
--(
--	[EffectiveDate] ASC
--) ON [PRIMARY]
--/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
--CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
--(
--	[PayId] ASC
--) ON [PRIMARY]
--/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
--CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
--(
--	[EmployeeId] ASC
--)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EPay.PayId is not null
/*
	declare @shfTime as dateTime
	set @shfTime = (select Shift_EndTime from ta_tbl_shift where shift_id = @shift)	
*/
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15),
			[CompoffMins] nvarchar(15),
			[HrsCompOff] nvarchar(15)
	  )
	 -- /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessDate] ON [dbo].[#TempProcessedData] 
		--(
		--	[Date] ASC
		--) ON [PRIMARY]
		--/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessCode] ON [dbo].[#TempProcessedData] 
		--(
		--	[Employee_Code_Id] ASC
		--) ON [PRIMARY]
		--/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessOtMins] ON [dbo].[#TempProcessedData] 
		--(
		--	[OtMins] ASC
		--) ON [PRIMARY]
	  insert into #TempProcessedData 
	  select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
	  [EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
	  [OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[CompoffMins],[Hrscompoff]
	   from TA_Tbl_ProcessedData PD
	  where Employee_Code_Id in (
	  select SwipeCardNo from TA_Tbl_Employee inner join
	  #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id)
	  and CompoffMins<>0 and CompoffMins is not null and 
	  [Date] between @fromDat and @ToDat 
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'select * from ('
	set @sqlQuery = @sqlQuery + 'select #TempProcessedData.Process_Rec_ID,TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,'
	--set @sqlQuery = @sqlQuery + 'ISNULL(ta_tbl_shift.Shift_ShortName,''Off'') as ShiftName,'
	--set @sqlQuery = @sqlQuery +  ' #TempProcessedData.HrsWork, #TempProcessedData.HrsOt,#TempProcessedData.OffOT,#TempProcessedData.HolOT, ta_tbl_Employee.Employee_FirstName from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.Employee_Code_Id'
	--set @sqlQuery = @sqlQuery +  ' where #TempProcessedData.HrsOT is not NULL and #TempProcessedData.HrsOt <>''0'''
	set @sqlQuery = @sqlQuery + ' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT,#TempProcessedData.OffOT,#TempProcessedData.HolOT,ISNULL(#TempProcessedData.OverTimeStatus,''Pending'') as OverTimeStatus, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],ta_tbl_Employee.Employee_Id,#TempProcessedData.OTMins,''0'' as SelectedRecords,HrsCompoff from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
	--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'	 
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' where #TempProcessedData.CompoffMins <> 0 '
	if(@SanctionType = 'OverTime')
		begin
			set @sqlQuery = @sqlQuery + ' AND Ta_Tbl_Employee.OT_Eligible=1 '
		end
	ELSE IF(@SanctionType = 'compoff')
		BEGIN
			set @sqlQuery = @sqlQuery + ' AND Ta_Tbl_Employee.CompOff_Eligible=1 '
		END	
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end
--	if(@shift<>0) 
--	begin
--		set @sqlQuery = @sqlQuery + ' And #TempProcessedData.Shift_Id=' + cast (@shift as nvarchar(50))  
--	end 
	set @sqlQuery = @sqlQuery + ' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1'
	--set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	--set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	--set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	--set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	--set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeePay.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeePay where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	if not(@EmployeeName='')
	begin
			set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		-- set @sqlQuery = @sqlQuery + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@empId='')
	begin
		--set @sqlQuery = @sqlQuery + ' and #TempProcessedData.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
	end
 If Not (@EmpSwipeCard = '')  
    Begin  
		  Set @sqlQuery = @sqlQuery + ' And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End
	--if not(@LevelID='' or @LevelID='0')
	--begin
		--set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ') ' 
	--end
	if not(@status='' or @status='All')
	begin
	 	IF(@status = 'Pending')
			BEGIN
				set @sqlQuery = @sqlQuery + ' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = ''' + @status + ''')'
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + ' AND #TempProcessedData.OvertimeStatus = ''' + @status + ''''
			END
             end 
	set @sqlQuery = @sqlQuery + ' ) OTRecords order by OTRecords.Employee_Code_Id , OTRecords.Date'
	exec (@sqlQuery)
--Remove the temporary tables here
drop table #TempProcessedData
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayroll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_EmployeeDetailsForPayroll  
Description : Select all Active Employee Details for Payroll
Tables Included : TA_Tbl_Employee, TA_Tbl_EmployeePay  
Created By : Kumuthini.L
Created On : 19-Apr-2008
Modified By :  Kumuthini.L
Modified On :  21-Apr-2008
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayroll]
(
    @Type CHAR(1),
    @EndDate NVARCHAR(10),
    @SwipeCardNo NVARCHAR(10)
)
AS
IF(@Type = 'A') -- Selecting all Active Employees for Payroll
	BEGIN				
		SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,EP.BasicPay
		FROM TA_Tbl_Employee E
		INNER JOIN TA_Tbl_EmployeePay EP ON EP.EmployeeId = E.Employee_Id 
		--INNER JOIN TA_Tbl_YearSetting Y ON Y.YearSettings_Id = EP.YearSettingID
		WHERE Employee_Firstname <> 'Administrator' AND  E.IsDeleted = 0 AND E.Employee_Status = 1 AND
                           EP.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeePay WHERE EffectiveDate <= @EndDate AND EmployeeId = E.Employee_Id) 
	END
ELSE IF(@Type = 'P') -- Getting the Details for a particular Swipe Card No
	BEGIN				
		SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,EP.BasicPay
		FROM TA_Tbl_Employee E
		INNER JOIN TA_Tbl_EmployeePay EP ON EP.EmployeeId = E.Employee_Id 
		--INNER JOIN TA_Tbl_YearSetting Y ON Y.YearSettings_Id = EP.YearSettingID
		WHERE Employee_Firstname <> 'Administrator' AND E.SwipeCardNo = @SwipeCardNo AND E.IsDeleted = 0 AND E.Employee_Status = 1 AND
                           EP.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeePay WHERE EffectiveDate <= @EndDate AND EmployeeId = E.Employee_Id) 
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_EmployeeDetailsForPayrollProcess '2019-05-30 00:00:00.000','1','SuperAdmin',1,3,1,0,'Process','<NewDataSet />','',''
/*
Modified By       :     Manjula.P
Modified On       :     07-Oct-2013
Descriptinos      :     Added where condition by Manjula.P on 07-Oct-2013 to avoiding Date out of range error while updating Early out Mantis : 0019299 
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]
@MonthClosureEndDate nVarchar(15),
@Levels varchar(8000),
@UserGroupName varchar(250),
@ParentId int,
@MonthCloseID int,
@AuditEmpId int,
@ProcessCount int,
@ProcessType varchar(50),
@strEmployees xml,
@Employee_code_Id varchar(25),
@Employeename varchar(50)
AS
BEGIN TRY
      BEGIN TRANSACTION    -- Start the transaction
            SET NOCOUNT ON;
            Declare @RowCountEmployeeID int
            Declare @RowCountEmployeeName int
    create table #EmployeeID(EmployeeID varchar(25))
            create table #EmployeeName(EmployeeName varchar(25))
            if(@Employee_code_Id is not null and @Employee_code_Id <> '')
            begin
                  if(SUBSTRING(@Employee_code_Id,LEN(@Employee_code_Id),len(@Employee_code_Id)) = ',')
                  begin
                        set @Employee_code_Id=SUBSTRING(@Employee_code_Id,0,len(@Employee_code_Id))             
                  end
                        insert into #EmployeeID
                        select value from dbo.split(@Employee_code_Id,',')
                        select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID                        
          end
            if(@EmployeeName is not null and @EmployeeName <> '')
            begin
                  if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = ',')
                  begin
                        set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))                        
                  end 
                        insert into #EmployeeName
                        select value from dbo.split(@EmployeeName,',')                    
                        select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName                       
                  end
      --Temporary table's creation
      create table #ReprocessEmployees(EmployeeCodeId varchar(15))
      create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
      create table #LevelRights(LevelId int)
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
      --Employee Level Indexes
      /****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
      /****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
      (
            [LevelId] ASC
      ) ON [PRIMARY]
      /****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
      CREATE TABLE #TempProcessedData
      (
            [Process_Rec_ID] bigint,[Employee_Code_Id] nvarchar(20),
            [Date] datetime,  [Shift_Id] int,
            [InTime] nvarchar(25),[OutTime] nvarchar(25),
            [HrsWork] nvarchar(10),[HrsOT] nvarchar(10),
            [NormOT] nvarchar(10),[OffOT] nvarchar(10),
            [HolOT] nvarchar(10),[EarlyOut] nvarchar(10),
            [LateIn] nvarchar(10),[Attendance] nvarchar(20),
            [WorkHrs] nvarchar(10),[HrsLess] nvarchar(10),
            [HrsExtra] nvarchar(10),[LateInMins] float,
            [EarlyOutMins] float,[ExtraMins] float,
            [OtMins] float,[OvertimeStatus] nvarchar(50),
            [TotalDays] numeric(18, 1),[LeaveCode] nvarchar(20),
            [LateEntryReason] nvarchar(260),[EarlyOutReason] nvarchar(260),
            [ProcessFlag] bit,[Status] nvarchar(50),
            [FNAttendanceCode] nvarchar(15),[ANAttendanceCode] nvarchar(15),[HoursWorkInMins] float,
            [LessHoursInMins] float,[WorkedHrsInMins] float,
            SPEC_NormOT1 nvarchar(10),
            SPEC_NormOT2 nvarchar(10),
            SPEC_OffOT1	nvarchar(10),
            SPEC_OffOT2	nvarchar(10),
            SPEC_HOLOT1	nvarchar(10),
            SPEC_HOLOT2	nvarchar(10)
      )
      Declare @Index int
      Set @Index = 0;
      EXEC sp_xml_preparedocument @Index OUTPUT, @strEmployees
      insert into #ReprocessEmployees (EmployeeCodeId)
      select EmployeeId from OpenXML(@Index, '/NewDataSet/ReprocessEmployees')
      With (EmployeeId varchar(15) 'EmployeeId')
      Exec sp_xml_removedocument @Index   
      DECLARE @SQLQUERY VARCHAR(8000)
      SET @SQLQUERY=''
      --select * from #ReprocessEmployees
      --Employee Level insert in Temporary table
      if exists(select * from #ReprocessEmployees)
      BEGIN
                  insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
                  select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
                  inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
                  inner join #ReprocessEmployees on #ReprocessEmployees.EmployeeCodeId=emp.Employee_Code_Id
                  where emp.Isdeleted=0 group by EmployeeId) ELevel
                  inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
                  AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@MonthClosureEndDate as nvarchar(50)), 102) and EL.LevelId is not null
      ENd
      else
      BEGIN
                  insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
                  select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
                  inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
                  where emp.Isdeleted=0 group by EmployeeId) ELevel
                  inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
                  AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@MonthClosureEndDate as nvarchar(50)), 102) and EL.LevelId is not null
      END
      if (@ProcessType='BindGrid')
      BEGIN
            SET @SQLQUERY='' + 'SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.Employee_FirstName + Space(1) + isnull(E.Employee_LastName,'''') as "Employee Name" FROM TA_Tbl_Employee E '
            SET @SQLQUERY=@SQLQUERY +' INNER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
            SET @SQLQUERY=@SQLQUERY +' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
            SET @SQLQUERY=@SQLQUERY +' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.Levelid '
            IF(@RowCountEmployeeID >0)
            BEGIN
                        SET @SQLQUERY=@SQLQUERY +' Inner join #EmployeeID ON #EmployeeID.EmployeeID  = E.EMPLOYEE_CODE_ID '
            END
            if(@RowCountEmployeeName >0)
            begin
                        SET @SQLQUERY=@SQLQUERY +' Inner join #EmployeeName on #EmployeeName.EmployeeName = E.Employee_FirstName ' 
            end
            SET @SQLQUERY=@SQLQUERY +' WHERE E.Employee_Firstname<>''Administrator'' AND E.Isdeleted = 0'        
            EXEC(@SQLQUERY)
      END
      else
      BEGIN
            declare @fromDat datetime
            declare @todat datetime
            select @fromDat=MonthClosure_StartDate,@todat=MonthClosure_EndDate from Ta_Tbl_MonthClosure where MonthClosure_Id=@MonthCloseID
            insert into #TempProcessedData
            select [Process_Rec_ID],pd.[Employee_code_id],pd.[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],[EarlyOut],
            [LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],[OvertimeStatus],[TotalDays],
            [LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[HoursWorkInMins],[LessHoursInMins],substring([WorkHrs],0,charindex(':',[WorkHrs]))*60+substring([WorkHrs],charindex(':',[WorkHrs])+1,len([WorkHrs])) as [WorkedHrsInMins],
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_NormOTHrs1 end,
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_NormOTHrs2 end,
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_OffOTHrs1 end,
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_OffOTHrs2 end,
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_HolOTHrs1 end,
            Case when PD.OvertimeStatus='Approved' then spot.Modified_Spec_HolOTHrs2 end
            from TA_Tbl_ProcessedData PD
            Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
            where PD.Employee_Code_Id in (select SwipeCardNo from ta_tbl_employee e
            inner join #EmpLevel el on el.employeeid=e.employee_id
            inner join #LevelRights lr on lr.levelId=el.levelid WHERE e.Employee_Firstname<>'Administrator' AND e.Isdeleted = 0) AND
            (PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
            AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
            --select * from #TempProcessedData 
            CREATE TABLE #TempPayrollProcessDetails(
            [MonthClosure_Id] [int] NULL,
            [Employee_Id] [nvarchar](20) NULL,
            [HrsWork] [nvarchar](25) NULL default('00:00'),
            [HrsOT] [nvarchar](25) NULL default('00:00'),
            [NormOT] [nvarchar](25) NULL default('00:00'),
            [OffOT] [nvarchar](25) NULL default('00:00'),
            [HolOT] [nvarchar](25) NULL default('00:00'),
            [OtMins] int default(0),
            [EarlyOut] [nvarchar](25)  default('00:00'),
            [LateIn] [nvarchar](25)  default('00:00'),
            [WorkHrs] [nvarchar](25)  default('00:00'),
            [HrsLess] [nvarchar](25)  default('00:00'),
            [HrsExtra] [nvarchar](25)  default('00:00'),
            [LeaveDays] [numeric](18, 1) default(0.0),
            [AbsentDays] [numeric](18, 1) default(0.0),
            [PresentDays] [numeric](18, 1) default(0.0),
            [Holidays] [numeric](18, 1) default(0.0),
            [LOPDays] [numeric](18, 1) default(0.0),
            [Emp_Id] [int] NULL,
            [TimeStamp] [datetime] NULL
            ,TotalPermissionHours nvarchar(25)null default('00:00')
            ,WeekOffDays [numeric](18, 1) default(0.0),
            SPEC_NormOT1 nvarchar(10)default('00:00'),
            SPEC_NormOT2 nvarchar(10)default('00:00'),
            SPEC_OffOT1	nvarchar(10)default('00:00'),
            SPEC_OffOT2	nvarchar(10)default('00:00'),
            SPEC_HOLOT1	nvarchar(10)default('00:00'),
            SPEC_HOLOT2	nvarchar(10)default('00:00')
            )
            insert into #TempPayrollProcessDetails (Employee_Id) select distinct [Employee_Code_Id] as Employee_Id from #TempProcessedData
            update #TempPayrollProcessDetails set [MonthClosure_Id]=@MonthCloseID
            select E.employee_code_id,sum(convert(int,substring(no_of_hours,1,(charindex(':',no_of_hours)-1))))as PermissionHours,
            sum(convert(int,substring(no_of_hours,charindex(':',no_of_hours)+1,len(no_of_hours)))) as permissionminutes 
            into #Permission_Details  from ta_tbl_permission P inner join 
            ta_tbl_employee E on E.employee_id=P.employee_id WHERE       (p.Permission_Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
            AND (p.Permission_Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
            and P.IsDeleted=0 and P.Permission_Status = 'Approved'
            group by E.employee_code_id
            update #TempPayrollProcessDetails set TotalPermissionHours=
            case when   len(convert(varchar(20),PermissionHours + permissionminutes/60))=1 and len(convert(varchar(20),permissionminutes%60))=1 then             
                        '0'+convert(varchar(20),PermissionHours + permissionminutes/60)      +':0'+convert(varchar(20),permissionminutes%60)
            when  len(convert(varchar(20),PermissionHours + permissionminutes/60))=1 and len(convert(varchar(20),permissionminutes%60))!=1 then
                        '0'+convert(varchar(20),PermissionHours + permissionminutes/60)      +':'+convert(varchar(20),permissionminutes%60)
            when  len(convert(varchar(20),PermissionHours + permissionminutes/60))!=1 and len(convert(varchar(20),permissionminutes%60))=1 then
                        '0'+convert(varchar(20),PermissionHours + permissionminutes/60)      +':'+convert(varchar(20),permissionminutes%60)
            else
                        '0'+convert(varchar(20),PermissionHours + permissionminutes/60)      +':'+convert(varchar(20),permissionminutes%60)
            end
            from #TempPayrollProcessDetails PD
            inner join #Permission_Details PerD on PD.Employee_Id=PerD.employee_code_id
            
            update #TempPayrollProcessDetails 
            set NormOT=convert(varchar, cast(T1.OTMins as int) / 60) + ':' + right(convert(char(3), 100 + cast(cast(T1.OTMins as int) as numeric) % 60), 2)
            from (select sum(OTMins) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus='Approved' and NormOT is not null and NormOT<>'' and NormOT<>'00:00'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id     
            update #TempPayrollProcessDetails set NormOT=isnull(NormOT,'00:00')
            
            /**********************/
            update TPP set SPEC_NormOT1=TP.SPEC_NormOT1,
            SPEC_NormOT2=TP.SPEC_NormOT2,
            SPEC_HOLOT1=TP.SPEC_HOLOT1,
            SPEC_HOLOT2=TP.SPEC_HOLOT2,
            SPEC_OffOT1=TP.SPEC_OffOT1,
            SPEC_OffOT2=TP.SPEC_OffOT2
            from #TempPayrollProcessDetails TPP inner join #TempProcessedData TP
            on TPP.Employee_Id=TP.Employee_Code_Id     
            
            update #TempPayrollProcessDetails 
            set OffOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then '0'+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+':'+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       '00' else case when len(convert(varchar(20),T1.OTMins%60))=1 then '0'+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus='Approved' and OffOT is not null and OffOT<>'' and OffOT<>'00:00'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id  
            
            
            update #TempPayrollProcessDetails 
            set OffOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then '0'+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+':'+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       '00' else case when len(convert(varchar(20),T1.OTMins%60))=1 then '0'+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus='Approved' and OffOT is not null and OffOT<>'' and OffOT<>'00:00'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id  
            
               
            update #TempPayrollProcessDetails set OffOT=isnull(OffOT,'00:00')
            update #TempPayrollProcessDetails 
            set HolOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then '0'+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+':'+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       '00' else case when len(convert(varchar(20),T1.OTMins%60))=1 then '0'+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus='Approved' and HolOT is not null and HolOT<>''  and HolOT<>'00:00'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id     
            update #TempPayrollProcessDetails set HolOT=isnull(HolOT,'00:00') 
            update #TempPayrollProcessDetails 
            set HrsWork=case when len(convert(varchar(20),T1.HrsWork/60))=1 then '0'+convert(varchar(20),T1.HrsWork/60)
       else convert(varchar(20),T1.HrsWork/60)end+':'+
       case when convert(varchar(20),T1.HrsWork%60)=0 then
       '00' else case when len(convert(varchar(20),T1.HrsWork%60))=1 then '0'+convert(varchar(20),T1.HrsWork%60)
       else convert(varchar(20),T1.HrsWork%60)end end
            from (
            select employee_code_id , CONVERT(int,SUM(HoursWorkInMins)) as HrsWork
            from #TempProcessedData group by employee_code_id ) as T1 
            inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id           
            --select * from #TempProcessedData
            update #TempPayrollProcessDetails 
            set WorkHrs=case when (charindex(':',T1.WorkHrs)=2 and charindex(':',reverse(T1.WorkHrs))=2) then '0'+T1.WorkHrs + '0'  
            when charindex(':',reverse(T1.WorkHrs))=2 then T1.WorkHrs +'0'
            when charindex(':',T1.WorkHrs)=2 then '0'+T1.WorkHrs
            when T1.WorkHrs is null then '00:00'
            else T1.WorkHrs end
            from (select cast(cast((sum(DATEPART(hour,WorkHrs)) * 60 + (sum(DATEPART(minute,WorkHrs)))) / 60  as int) as varchar(50)) + ':' + cast(sum(DATEPART(minute,WorkHrs)) % 60 as varchar(2)) as WorkHrs,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set EarlyOut=case when len(convert(varchar(20),T1.EarlyOut/60))=1 then '0'+convert(varchar(20),T1.EarlyOut/60)
       else convert(varchar(20),T1.EarlyOut/60)end+':'+
       case when convert(varchar(20),T1.EarlyOut%60)=0 then
       '00' else case when len(convert(varchar(20),T1.EarlyOut%60))=1 then '0'+convert(varchar(20),T1.EarlyOut%60)
       else convert(varchar(20),T1.EarlyOut%60)end end
            from (select CONVERT(int,sum(EarlyOutMins)) as EarlyOut,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set LateIn=case when len(convert(varchar(20),T1.LateIn/60))=1 then '0'+convert(varchar(20),T1.LateIn/60)
       else convert(varchar(20),T1.LateIn/60)end+':'+
       case when convert(varchar(20),T1.LateIn%60)=0 then
       '00' else case when len(convert(varchar(20),T1.LateIn%60))=1 then '0'+convert(varchar(20),T1.LateIn%60)
       else convert(varchar(20),T1.LateIn%60)end end
            from (select CONVERT(int,SUM(LateInMins)) as LateIn,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Added where condition by Manjula.P on 07-Oct-2013 to avoiding Date out of range error Mantis : 0019299  
            update #TempPayrollProcessDetails 
            set HrsLess=case when len(convert(varchar(20),T1.HrsLess/60))=1 then '0'+convert(varchar(20),T1.HrsLess/60)
       else convert(varchar(20),T1.HrsLess/60)end+':'+
       case when convert(varchar(20),T1.HrsLess%60)=0 then
       '00' else case when len(convert(varchar(20),T1.HrsLess%60))=1 then '0'+convert(varchar(20),T1.HrsLess%60)
       else convert(varchar(20),T1.HrsLess%60)end end
            from (select CONVERT(int,SUM(LessHoursInMins)) as HrsLess,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set HrsExtra=convert(char(5), dateadd(MINUTE, T1.HrsExtra, ''), 114)                
            from (select sum(ExtraMins) as HrsExtra,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Leave Days update
            update #TempPayrollProcessDetails 
            set Leavedays=isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode in (Select LeaveType from Ta_Tbl_LeaveType where IsDeleted=0)
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Secod Half Leave Days update
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode in (Select LeaveType from Ta_Tbl_LeaveType where IsDeleted=0)
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode in ('RH')
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode in ('RH')
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Present Days update
            update #TempPayrollProcessDetails 
            set Presentdays=isnull(T1.Presentdays,0.0) *0.5
            from (select count(*) as Presentdays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode='Present' or FNAttendanceCode='Comp Off'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Present Days update
            update #TempPayrollProcessDetails 
            set Presentdays=#TempPayrollProcessDetails.Presentdays + isnull(T1.Presentdays,0.0) *0.5
            from (select count(*) as Presentdays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode='Present'  or ANAttendanceCode='Comp Off'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Absent Days update
            update #TempPayrollProcessDetails 
            set Absentdays=isnull(T1.Absentdays,0.0) *0.5
            from (select count(*) as Absentdays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode='Absent'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Absent Days update
            update #TempPayrollProcessDetails 
            set Absentdays=#TempPayrollProcessDetails.Absentdays + isnull(T1.Absentdays,0.0) *0.5
            from (select count(*) as Absentdays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode='Absent'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Holiday/Weekly Off Days update
            update #TempPayrollProcessDetails 
            set WeekOffDays=isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode='Weekly Off'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails        
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Holidays=isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode='Holiday'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Holiday/Weekly  Days update
            update #TempPayrollProcessDetails 
            set WeekOffDays=#TempPayrollProcessDetails.WeekOffDays + isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode='Weekly Off'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Holidays=#TempPayrollProcessDetails.Holidays + isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode='Holiday'
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half LOP Days update
            update #TempPayrollProcessDetails 
            set LOPDays=isnull(T1.LOPDays,0.0) *0.5
            from (select count(*) as LOPDays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode='LOP' 
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half LOP Days update
            update #TempPayrollProcessDetails 
            set LOPDays=#TempPayrollProcessDetails.LOPDays + isnull(T1.LOPDays,0.0) *0.5
            from (select count(*) as LOPDays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode='LOP' 
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails set Emp_Id=@AuditEmpId
            update #TempPayrollProcessDetails set [TimeStamp]=getdate()       
            if(@ProcessType='Process')
            BEGIN
                  if(@ProcessCount=0)
                  BEGIN
                              insert into  TA_Tbl_PayrollProcessDetails (MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                              LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2)
                              select MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                              LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2 from #TempPayrollProcessDetails
                  END
                  else
                  BEGIN
                              update TA_Tbl_PayrollProcessDetails set HrsWork=T1.HrsWork, HrsOT=T1.HrsOT, NormOT=T1.NormOT, OffOT=T1.OffOT, HolOT=T1.HolOT, EarlyOut=T1.EarlyOut, LateIn=T1.LateIn, WorkHrs=T1.WorkHrs, HrsLess=T1.HrsLess, HrsExtra=T1.HrsExtra, 
                              LeaveDays=T1.LeaveDays, AbsentDays=T1.AbsentDays, PresentDays=T1.PresentDays, Holidays=T1.Holidays, LOPDays=T1.LOPDays,TotalPermissionHours=T1.TotalPermissionHours
                              ,WeekOffDays=T1.WeekOffDays
                              ,SPEC_NormOT1=T1.SPEC_NormOT1,SPEC_NormOT2=T1.SPEC_NormOT2,SPEC_OffOT1=T1.SPEC_OffOT1,SPEC_OffOT2=T1.SPEC_OffOT2,
                              SPEC_HOLOT1=T1.SPEC_HOLOT1,SPEC_HOLOT2=T1.SPEC_HOLOT2
                              from #TempPayrollProcessDetails T1 inner join TA_Tbl_PayrollProcessDetails T2
                              on T1.MonthClosure_Id=T2.MonthClosure_Id and T1.Employee_Id=T2.Employee_Id
                  END               
      END
      else if (@ProcessType='Preview')
      BEGIN
                  delete from TA_Tbl_TempPayrollProcessDetails where MonthClosure_Id=@MonthCloseID
                  insert into  TA_Tbl_TempPayrollProcessDetails (MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                  LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2)
                  select MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                  LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2
                  from #TempPayrollProcessDetails
      END
            select MonthClosure_Id, Employee_Id as Employee_Code_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
            LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1=isnull(SPEC_NormOT1,'00:00'),SPEC_NormOT2=isnull(SPEC_NormOT2,'00:00'),SPEC_OffOT1=isnull(SPEC_OffOT1,'00:00'),SPEC_OffOT2=isnull(SPEC_OffOT2,'00:00'),SPEC_HOLOT1=isnull(SPEC_HOLOT1,'00:00'),SPEC_HOLOT2=isnull(SPEC_HOLOT2,'00:00') from #TempPayrollProcessDetails
            --Remove the temporary tables here  
            drop table #TempPayrollProcessDetails
      end
      COMMIT
END TRY
BEGIN CATCH
      -- Whoops, there was an error
      IF @@TRANCOUNT > 0
      ROLLBACK
      -- Raise an error with the details of the exception
      DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
      SELECT @ErrMsg = ERROR_MESSAGE(),
      @ErrSeverity = ERROR_SEVERITY()
      RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
      --Remove the temporary tables here  
      drop table #EmpLevel
      drop table #LevelRights
      drop table #TempProcessedData
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForSearch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
exec Proc_TA_EmployeeDetailsForSearch @EmployeeName=N'',@empId=N'MK1005',@UserGroupName=N'SuperAdmin',
@UserLevel='0',@GradeLevel=N'0',@SwipeOpt='Select',@EmpSwipeCard='',@ParentId=0,@LoginEmployeeAutoId=1,@ApplnMode=1,@Filter= 0
,@EmployeeCategory=0,@employeetype=0,@Gender='Both',@EmpAutoID=1,@ScheduleID=0,@FilterUserGroup=0,@LeavePolicy=0,@Reportingto=0,@ApprovalAuthority=0,
@EmailAvail=0,@expiryNo=0
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForSearch]    
(    
	@EmployeeName			NVARCHAR(MAX)='',
	@empId					NVARCHAR(MAX)='',
	@UserGroupName			NVARCHAR(250),
	@UserLevel				VARCHAR(8000),
	@GradeLevel				NVARCHAR(20) ,
	@SwipeOpt				VARCHAR(25),
	@EmpSwipeCard			VARCHAR(20),
	@ParentId				INT,
	@LoginEmployeeAutoId	INT,
	@ApplnMode				BIT,
	@Filter					INT,
	@EmployeeCategory		INT,
	@EmployeeType			INT,
	@Gender					VARCHAR(10),
	@EmpAutoID int,
	@ScheduleID int		=	null,	
	@FilterUserGroup int,  
	@LeavePolicy int,  
    @Reportingto int,  
    @ApprovalAuthority int, 
    @EmailAvail int,
    @expiryNo int
)    
AS
BEGIN 
	--insert into TestingEmployee values
	--(
	--	@EmployeeName,
	--	@empId		,
	--	@UserGroupName,
	--	@UserLevel	,
	--	@GradeLevel	,
	--	@SwipeOpt	,
	--	@EmpSwipeCard,
	--	@ParentId	,
	--	@LoginEmployeeAutoId	,
	--	@ApplnMode				,
	--	@Filter					,
	--	@EmployeeCategory		,
	--	@EmployeeType			,
	--	@Gender					,
	--	@EmpAutoID ,
	--	@ScheduleID ,
	--	@FilterUserGroup ,
	--	@LeavePolicy ,
	--	@Reportingto ,
	--	@ApprovalAuthority ,
	--	@EmailAvail 
	--)
	SET NOCOUNT ON;
	DECLARE @IndividualUserStatus int
	DECLARE @sql AS VARCHAR(8000) 	
	DECLARE @EmpId_Numeric table (EmployeeCodeId VARCHAR(15))
	CREATE table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) AS LevelId
	CREATE table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	CREATE table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	CREATE table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	CREATE table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	declare @isReportingto as int
	
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
    CREATE table #EmployeeID(EmployeeID VARCHAR(25))
    CREATE table #EmployeeName(EmployeeID VARCHAR(25))
    
	if(@empId is not null and @empId <> '')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
	(
		select max(el.EffectiveDate) AS EffectiveDate,el.EmployeeId from TA_Tbl_EmployeeLevel el  
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
		INNER JOIN #LevelRights LR ON LR.LevelId=el.LevelId
		Left outer JOIN #EmployeeID TEmpID ON TEmpID.EmployeeID=Employee_Code_Id 
		Left Outer JOIN #EmployeeName TEmpName ON TEmpName.EmployeeID=Employee_Code_Id
		left outer join TA_Tbl_Emp_LeavePolicyDetails LP on emp.Employee_Id=LP.EmpID
		Where 1=1
		and
		(
			(@Filter=0) or 
			(@Filter=1 and OT_Eligible=1 and CompOff_Eligible=0) or 
			(@Filter=2 and OT_Eligible=0 and CompOff_Eligible=1) or
			(@Filter=3 and OT_Eligible=1 and CompOff_Eligible=1) or
			(@Filter=4 and LP.Policy_Id is null)  or
			(@Filter=5 and Employee_Status=0) or
			(@Filter=6 and Hostel=1) or
			(@Filter=7 and Report_Exclude=1) or
			(@Filter=8 and (UserGroup_Id is null or UserGroup_Id='')) or
			(@Filter=9 and OT_Eligible=0 and CompOff_Eligible=0) or
			(@Filter=10 and Employee_Status=1)			
		)
		and(@Gender='Both' or Gender=@Gender)
		and(isnull(@expiryNo,0)=0 or ((Passport_expirydate is not null and Passport_expirydate<=DATEADD(d,@expiryNo,getdate())) or (Visa_expirydate is not null and Visa_expirydate<=DATEADD(d,@expiryNo,getdate()))))
		and(@isReportingto=0 or (Employee_ID IN (select * from #EmployeeIds)))
		and(ISNULL(@empId,'')='' or (Employee_Code_Id IN (select EmployeeID from #EmployeeID)))
		and(ISNULL(@EmployeeName,'')='' or (Employee_Code_Id IN (select * from #EmployeeName)))
		group by el.EmployeeId
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from 
	(
		select max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		group by ed.EmployeeId
	) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	and ED.DesignationId is not null
	
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeCategory,0)=0 or ec.CategoryId=@EmployeeCategory)
		group by ec.EmployeeId,Employee_Code_Id,emp.SwipeCardNo 
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeType,0)=0 or et.TypeId=@EmployeeType)
		group by et.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	and EType.TypeId is not null
	
	insert into @EmpId_Numeric 
	select Employee_code_Id  AS EmpId from TA_Tbl_Employee 
	INNER JOIN #EmpLevel EL ON TA_Tbl_Employee.Employee_Id=EL.EmployeeId 
	where TA_Tbl_Employee.Employee_Firstname<>'Administrator' and PatIndex('%[^0-9]%',Employee_code_Id) = 0 order by EmpId ASc
	
	select @IndividualUserStatus=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0
	--Testing purpose commented this line on 21-07-2022
	--IF(@ApplnMode = 0)
	--	BEGIN
	--		DECLARE @Deleted int	
	--		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
	--		begin
	--			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
	--			SET @Deleted=1
	--		end			
	--		UPDATE TA_Tbl_Employee SET
	--		Isdeleted = 1,
	--		Employee_Status = 0,
	--		InActiveDate = DATEADD(D, 1, DateOfJoining)
	--		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> '18000000') AND
	--		Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
	--		if @Deleted=1
	--			begin
	--				ENABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
	--			end
	--	END
		

	Create table #Temp_TA_Tbl_EmailScheduled_Employees(Employee_id int,ScheduleId int)
	Insert into #Temp_TA_Tbl_EmailScheduled_Employees
	select Employee_id,ScheduleId from TA_Tbl_EmailScheduled_Employees where ScheduleId=@ScheduleID
	SELECT	E.Employee_Id,
			E.Employee_Code_Id,
			E.Employee_FirstName + ' '+ isnull(E.Employee_LastName,'')AS Employee_FirstName,
			case when E.Employee_Status=1 then 'Active' else 'InActive' end Employee_Status,
			case when E.IsDeleted=1 then 'True' else 'False' end Isdeleted,
			T.TitleName,
			case when isnull(ESE.Employee_id,0)=0 then 0 else 1 end emailScheduler_flag,
			E.EmailId,
			E.Mobile_number,
			E.SwipeCardNo,
			E.Contact_Address,
			groupName, 
			E.Father_name,
			E.Mother_name,
			E.DateofBirth,
			E.DateofBirth_Record,
			E.Blood_Group,
			E.Permanent_Address,
			E.Phone_Number,
			E.Mobile_Number,
			E.Gender,
			E.Marital_status,
			E.Personal_mailid,
			E.Passport_No,
			E.Passport_expirydate,
			E.Visa_No,
			E.Visa_expirydate,
			E.Vehicle_No,
			E.Anniversary_Date,
			E.DateOfJoining,
			Reporting_To=ER.Employee_Code_Id + ' - '+ ER.Employee_FirstName + ' '+ isnull(ER.Employee_LastName,''),
			Leave_Sanc_Authority=ES.Employee_Code_Id + ' - '+es.Employee_FirstName + ' '+ isnull(es.Employee_LastName,''),
			CompOff_Eligible=case when E.CompOff_Eligible=1 then 'Yes' else 'No' end,
			OT_Eligible=case when E.OT_Eligible=1 then 'Yes' else 'No' end,
			Report_Exclude=case when E.Report_Exclude=1 then 'Yes' else 'No' end,
			E.InActiveDate,
			E.CustomField1,
			E.CustomField2,
			E.CustomField3,
			E.CustomField4,
			E.CustomField5,
			[Imported]=case when E.IsImported=1 then 'Yes' else 'No' end,
			MobileClockIn=case when E.MobileClockInOUt=1 then 'Yes' else 'No' end,
			DepartmentName=ld.name,
			C.CategoryName,
			Typ.TypeName,
			E.Time_Stamp as CreatedDate
			FROM TA_Tbl_Employee E
			inner JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
			inner JOIN #EmpLevel ON E.Employee_Id = #EmpLevel.EmployeeId
			inner JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
			INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId
			Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId
			inner join Ta_Tbl_levelDetails ld on #LevelRights.LevelId=ld.id
			left outer join #EmpType on #EmpType.employeeid=e.Employee_Id
			inner join TA_Tbl_Type typ on typ.TypeId=#EmpType.TypeId
			left outer join #Temp_TA_Tbl_EmailScheduled_Employees ESE on ESE.Employee_id=e.Employee_Id
			left outer join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id
			inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
			left outer join ta_tbl_usergroup ug on E.UserGroup_Id=ug.groupId
			left outer join TA_Tbl_Employee er on e.Reporting_To=er.Employee_Id
			left outer join TA_Tbl_Employee es on e.Leave_Sanc_Authority=es.Employee_Id
			WHERE E.Employee_FirstName<>'Administrator' and (ESE.ScheduleId is null or ESE.ScheduleId = @ScheduleID)
			and(@SwipeOpt='Not Exists' or e.swipecardno is not null and e.swipecardno!='')
			and(@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			and(ISNULL(@FilterUserGroup,0)=0 or E.UserGroup_Id= @FilterUserGroup)
			and(ISNULL(@Reportingto,0)=0 or E.Reporting_To=@Reportingto)
			and(ISNULL(@ApprovalAuthority,0)=0 or E.Leave_Sanc_Authority=@ApprovalAuthority)
			and(ISNULL(@EmailAvail,0)=0 or (@EmailAvail=1 and E.EmailId is not null and E.EmailId<>'') or (@EmailAvail=2 and (E.EmailId is null or E.EmailId='' )))
			and(isnull(@IndividualUserStatus,0)=0 or E.Employee_Id =@IndividualUserStatus)
			ORDER BY E.Employee_Id	
	drop table #EmpLevel      
	drop table #LevelRights
	drop table #EmpDesignation	 
	drop table #EmployeeID
	drop table #EmployeeName
	drop table #EmpCategory
	drop table #EmpType
	drop table #Temp_TA_Tbl_EmailScheduled_Employees
	drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_EmployeeDetailsForUpdate 'A' , '' , '','1,2,3,47,113,132,133,134,136,135','2'
CREATE      PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForUpdate]
@type CHAR(1)='',
@EmployeeName NVARCHAR(50)='',
@UserGroupName NVARCHAR(250),
@UserLevels nvarchar(2000),
@GradeLevel nvarchar(20),
@ParentId int 
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--selecting Employee for Grid
declare @Query as varchar(7000)
IF @type='A'
BEGIN
	IF(@UserGroupName='SuperAdmin')
			BEGIN
					set @Query= 'SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''') as Employee_FirstName, E.Employee_Status, T.TitleName,E.SwipeCardNo,E.Isdeleted	'
					set @Query= @Query +' FROM TA_Tbl_Employee E'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
                    set @Query= @Query +' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid'
					set @Query= @Query +' WHERE E.Employee_Firstname<>''Administrator'' AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id)  '
					set @Query= @Query +' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)'
					--set @Query= @Query +' and TA_Tbl_EmployeeLevel.Levelid in (' + @UserLevels + ')'
			END
	ELSE
			BEGIN
					set @Query= 'SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''') as Employee_FirstName,E.Employee_Status,T.TitleName,E.SwipeCardNo,E.Isdeleted'
					set @Query= @Query +' FROM TA_Tbl_Employee E'			
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'
					set @Query =@Query +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
					set @Query= @Query +' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid'
					set @Query= @Query +' WHERE E.IsDeleted=0 and Employee_Firstname<>''Administrator'' AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id)  '
					set @Query= @Query +' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)'
					--set @Query= @Query +' and TA_Tbl_EmployeeLevel.Levelid in (' + @UserLevels + ')'
					set @Query= @Query +' and TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
			END
exec(@Query)
--selecting employee using search option
END
ELSE IF @type='N'
BEGIN
	IF(@UserGroupName='SuperAdmin')
			BEGIN
					set @Query= 'SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''') as Employee_FirstName,E.Employee_Status,T.TitleName'
					set @Query= @Query +' FROM TA_Tbl_Employee E'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
					set @Query= @Query +' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid'
					set @Query= @Query +' WHERE Employee_FirstName LIKE ''' + @EmployeeName +'+%''  and Employee_Firstname<>''Administrator'' '
					set @Query= @Query +' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)'
					--set @Query= @Query +' and TA_Tbl_EmployeeLevel.Levelid in (' + @UserLevels + ')'
			END
	ELSE
			BEGIN
					set @Query= 'SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''') as Employee_FirstName,E.Employee_Status,T.TitleName'
					set @Query= @Query +' FROM TA_Tbl_Employee E'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'
					set @Query =@Query +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '					
					set @Query= @Query +' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'					
					set @Query= @Query +' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid'
					set @Query= @Query +' WHERE E.IsDeleted=0 AND Employee_FirstName LIKE ''' + @EmployeeName + '+%''  and Employee_Firstname<>''Administrator'' '
					set @Query= @Query +' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)'
					--set @Query= @Query +' and TA_Tbl_EmployeeLevel.Levelid in (' + @UserLevels + ')'
					set @Query= @Query +' and TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
			END
			drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_EmployeeErrorLog]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_EmployeeErrorLog]
	-- Add the parameters for the stored procedure here
	@EmployeeCode nvarchar(200),
	@Error nvarchar(MAX)

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO [dbo].[ta_tbl_EmployeeErrorLog]([EmployeeCode],[Error],[ErrorTimestamp]) VALUES (@EmployeeCode,@Error,GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	Proc_TA_EmployeeLeaveDetailsByDate    
Description 	:	Selecting the Leave Details of the particular Employee and Date
Tables Included :	TA_Tbl_LeaveApplication
Created By 	:	Kumuthini.L    
Created On 	:	21-Jan-09
Modified By 	:	
Modified On 	:	
*/
CREATE   Procedure [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]              
(               
   @EmployeeId int,
   @LeaveDate nVarchar(20)             
)               
AS                     
BEGIN
SET NOCOUNT ON;
 SELECT la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate,la.Leave_SessionFrom,la.Leave_SessionTo FROM TA_Tbl_LeaveApplication la where la.Employee_Id = @EmployeeId AND la.Leave_FromDate <= @LeaveDate and la.Leave_ToDate >= @LeaveDate and la.Status = 'Approved' and la.IsDeleted = 0
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeMasterDocumentUpload]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeMasterDocumentUpload]
	-- Add the parameters for the stored procedure here
	@CusFieldValue nvarchar(max),
	@CusFlag nvarchar(max),
	@EmployeeCodeID nvarchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@CusFlag='cusField1')
	begin
		update TA_Tbl_Employee set CustomField1=@CusFieldValue where Employee_Code_Id=@EmployeeCodeID
	End
	if(@CusFlag='cusField2')
	begin
		update TA_Tbl_Employee set CustomField2=@CusFieldValue where Employee_Code_Id=@EmployeeCodeID
	End
	if(@CusFlag='cusField3')
	begin
		update TA_Tbl_Employee set CustomField3=@CusFieldValue where Employee_Code_Id=@EmployeeCodeID
	End
	if(@CusFlag='cusField4')
	begin
		update TA_Tbl_Employee set CustomField4=@CusFieldValue where Employee_Code_Id=@EmployeeCodeID
	End
	if(@CusFlag='cusField5')
	begin
		update TA_Tbl_Employee set CustomField5=@CusFieldValue where Employee_Code_Id=@EmployeeCodeID
	End

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_EmployeeOTLeaveApplication 182
Description		:	Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	
Modified On		:	
*/
CREATE    PROCEDURE [dbo].[Proc_TA_EmployeeOTLeaveApplication] 
@EmployeeId varchar(50)
AS
Declare @FromDate as datetime
Declare @ToDate as datetime
Declare @CompOffDays as bigint
Declare @NumberOfDays as bigint
Declare @OtMinHrs as nvarchar(20)
Declare @OtHrs as bigint
Declare @OtMin as bigint
Declare @OtMinProcessedData as bigint
Declare @TotalOtMin as bigint
Declare @Employee_code_Id as nvarchar(50)
BEGIN
	SET NOCOUNT ON; 
	set @Employee_code_Id=(select SwipeCardNo from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
	set @FromDate=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
	set @ToDate=(select ToDate from TA_Tbl_YearSetting where IsActive=1)
	set @OtMinHrs=(select isnull(OtMinHrs,'00:00') as OtMinHrs from TA_Tbl_LeavePolicy lp
	inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lp.Policy_Id
	where elp.EmployeeId=@EmployeeId 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
	set @OtHrs=(select left(@OtMinHrs,2))
	set @OtMin=(select right(@OtMinHrs,2))
	set @TotalOtMin=(@OtHrs*60) + @OtMin
	set @OtMinProcessedData=(select sum(OtMins) from TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id=@Employee_code_Id AND OvertimeStatus='Approved')
	set @NumberOfDays=(select sum(isnull(NumberOfDays,0)) as NumberOfDays from TA_tbl_LeaveApplication 
	WHERE ((Leave_FromDate BETWEEN  @FromDate AND @ToDate) AND (Leave_ToDate BETWEEN  @FromDate AND @ToDate))
	AND Employee_Id=@EmployeeId and Type='Comp Off' and Status NOT IN ('Rejected') and IsDeleted=0)
	if(@NumberOfDays is null or @NumberOfDays='')
		BEGIN
		set @NumberOfDays=0
		END
	IF(@TotalOtMin > 0)
		BEGIN
			set @TotalOtMin=@TotalOtMin * @NumberOfDays
		END
	ELSE
		BEGIN
			set @TotalOtMin=0
		END
	select @TotalOtMin as OTMinsLeaveApplication,@OtMinProcessedData as OTMinsProcessedData,@OtMinHrs as OtMinHrs
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_EmployeeOTSanction  
Description : To get the OT Employee with Approval Status
Tables Included : TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
				  TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
				  TA_Tbl_Grade,ta_tbl_shift
Created By : Sasireka  
Created On : 08-Jan-2009 
Modified By :  Karthikeyan.R
Modified On :  14-Mar-2017
*/  
-- Proc_TA_EmployeeOTSanction '','2022/04/01','2025/05/01','','','0','','','SuperAdmin','1','All','',0,'compoff'
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeOTSanction]
(
	@Employee_ID int,
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(50),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @SanctionType varchar(25)   
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
	--select * from #EmpDesignation
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
		;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	--inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	--select @TopLevelId
	--update TA_Tbl_ShiftSettings set isRequestingforCompOff=1
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@TopLevelId
	if(@isRequestCompOff is null or @isRequestCompOff='')
	BEGIN
		select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
	END
	CREATE TABLE #TempProcessedData
			(
				[Process_Rec_ID] bigint,
				[Employee_Code_Id] nvarchar(20),
				[Date] datetime,
				[Shift_Id] int,
				[InTime] nvarchar(25),
				[OutTime] nvarchar(25),
				[HrsWork] nvarchar(10),
				[HrsOT] nvarchar(10),
				[NormOT] nvarchar(10),
				[OffOT] nvarchar(10),
				[HolOT] nvarchar(10),
				[EarlyOut] nvarchar(10),
				[LateIn] nvarchar(10),
				[Attendance] nvarchar(20),
				[WorkHrs] nvarchar(10),
				[HrsLess] nvarchar(10),
				[HrsExtra] nvarchar(10),
				[LateInMins] float,
				[EarlyOutMins] float,
				[ExtraMins] float,
				[OtMins] float,
				[OvertimeStatus] nvarchar(50),
				[TotalDays] numeric(18, 1),
				[LeaveCode] nvarchar(20),
				[LateEntryReason] nvarchar(260),
				[EarlyOutReason] nvarchar(260),
				[ProcessFlag] bit,
				[Status] nvarchar(50),
				[FNAttendanceCode] nvarchar(15),
				[ANAttendanceCode] nvarchar(15),
				[ActHrsOT] nvarchar(10),
				[ActNormOT] nvarchar(10),
				[ActOffOT] nvarchar(10),
				[ActHolOT] nvarchar(10),
				[ActOtMins] float,
				[AvailOtMins] float,
				[ExtraTime_Id] bigint,
				-----
				SPEC_NormOT1	varchar(10),
				SPEC_NormOTMins1	int,
				SPEC_NormOT2	varchar(10),
				SPEC_NormOTMins2	int,
				SPEC_OffOT1		varchar(10),
				SPEC_OffOTMins1	int,
				SPEC_OffOT2		varchar(10),
				SPEC_OffOTMins2	int,
				SPEC_HOLOT1		varchar(10),
				SPEC_HOLOTMins1	int,
				SPEC_HOLOT2		varchar(10),
				SPEC_HOLOTMins2	int,			
				Modified_Spec_NormOTMins1 int,
				Modified_Spec_NormOTMins2 int,
				Modified_Spec_OffOTMins1 int,
				Modified_Spec_OffOTMins2 int,
				Modified_Spec_HolOTMins1 int,
				Modified_Spec_HolOTMins2 int,
				Modified_Spec_NormOTHrs1 varchar(10),
				Modified_Spec_NormOTHrs2 varchar(10),
				Modified_Spec_OffOTHrs1 varchar(10),
				Modified_Spec_OffOTHrs2 varchar(10),
				Modified_Spec_HolOTHrs1 varchar(10),
				Modified_Spec_HolOTHrs2 varchar(10),
				[Expiry Date] datetime
		  )
		 --select @isRequestCompOff
		if(@isRequestCompOff=0 or @SanctionType = 'OverTime')
			BEGIN
				update TA_Tbl_ProcessedData set 
				OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
				
				insert into #TempProcessedData 
				select [Process_Rec_ID],PD.[Employee_Code_Id],pd.[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
				[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
				[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[ActHrsOT],[ActNormOT],[ActOffOT],[ActHolOT],[ActOtMins],case when ISNULL(ActOTMins,0)=0 then [OtMins] else ActOTMins end,0,
				PD.SPEC_NormOT1,
				PD.SPEC_NormOTMins1,
				PD.SPEC_NormOT2,
				PD.SPEC_NormOTMins2,
				PD.SPEC_OffOT1,
				PD.SPEC_OffOTMins1,
				PD.SPEC_OffOT2,
				PD.SPEC_OffOTMins2,
				PD.SPEC_HOLOT1,
				PD.SPEC_HOLOTMins1,
				PD.SPEC_HOLOT2,
				PD.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2,
				null
				from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee e on PD.Employee_Code_Id=e.SwipeCardNo
				inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
				Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
				where (OtMins <> 0 or ActOTMins <> 0)  and 
				pd.[Date] between @fromDat and @ToDat 
				
				update #TempProcessedData set [Expiry Date]=OT.DateToExpired
				from #TempProcessedData TP 
				inner join TA_Tbl_OverTimeStatus OT on TP.Process_Rec_ID=OT.Process_RecID
					
				
			END
		Else
			BEGIN
				--select 1
				insert into #TempProcessedData 
				select OT.Process_RecID as 'Process_Rec_ID',E.Employee_Code_Id,OT.Date,p.Shift_Id,
				P.InTime,P.OutTime,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,
				p.EarlyOut,p.LateIn,p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,
				p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
				p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,
				p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id,
				P.SPEC_NormOT1,
				P.SPEC_NormOTMins1,
				P.SPEC_NormOT2,
				P.SPEC_NormOTMins2,
				P.SPEC_OffOT1,
				P.SPEC_OffOTMins1,
				P.SPEC_OffOT2,
				P.SPEC_OffOTMins2,
				P.SPEC_HOLOT1,
				P.SPEC_HOLOTMins1,
				P.SPEC_HOLOT2,
				P.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2,
				DateToExpired
				from TA_Tbl_OverTimeStatus OT 
				inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
				inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.SwipeCardNo=P.Employee_Code_Id  
				inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
				Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
				where P.[Date] between @fromDat and @ToDat and OT.isDelete=0 
				--and OT.isRequest=1
			END
	DECLARE @dateFormat as int
	select @dateFormat =dbo.Fun_TA_GetDateFormat();	--select @dateFormat	
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''	
	set @sqlQuery = @sqlQuery + 'select 
	E.Employee_Code_Id,
	E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'''') as Employee_FirstName,
	replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],
	convert(varchar(20),TPD.Date,101) as date,
	TPD.NormOt as HrsOT,
	ISNULL(TPD.ActNormOT,TPD.NormOt) ActHrsOT,
	TPD.OffOT,
	ISNULL(TPD.ActOffOT,TPD.OffOT) ActOffOT,
	TPD.HolOT,
	ISNULL(TPD.ActHolOT,TPD.HolOT) ActHolOT,
	SPEC_NormOT1,
	Modified_Spec_NormOTHrs1=ISNULL(Modified_Spec_NormOTHrs1,SPEC_NormOT1),
	SPEC_NormOT2,
	Modified_Spec_NormOTHrs2=ISNULL(Modified_Spec_NormOTHrs2,SPEC_NormOT2),
	SPEC_OffOT1,
	Modified_Spec_OffOTHrs1=ISNULL(Modified_Spec_OffOTHrs1,SPEC_OffOT1),
	SPEC_OffOT2,
	Modified_Spec_OffOTHrs2=ISNULL(Modified_Spec_OffOTHrs2,SPEC_OffOT2),
	SPEC_HOLOT1,
	Modified_Spec_HolOTHrs1=ISNULL(Modified_Spec_HolOTHrs1,SPEC_HOLOT1),
	SPEC_HOLOT2,	
	Modified_Spec_HolOTHrs2=ISNULL(Modified_Spec_HolOTHrs2,SPEC_HOLOT2),
	ISNULL(TPD.OverTimeStatus,''Pending'') as OverTimeStatus, 	
	E.Employee_Id,TPD.OTMins,
	''0'' as SelectedRecords,
	ISNULL(TPD.ActOtMins,TPD.OtMins) ActOtMins,'+@isRequestCompOff +' as isRequestCompOff,TPD.ExtraTime_Id,	
	TPD.Process_Rec_ID,
	TPD.shift_id,
	TPD.HrsWork,
	case when [Expiry Date] is not null and [Expiry Date]!='''' then case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, [Expiry Date],'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
												else CONVERT(VARCHAR,[Expiry Date], '+CONVERT(varchar,@dateFormat)+') 
										end
		 else ''-'' end
										[Expiry Date] 
	from #TempProcessedData TPD 
	INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.Employee_Code_Id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'	 
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' where TPD.AvailOtMins <> 0 '
	if(@SanctionType = 'OverTime')
		begin
			set @sqlQuery = @sqlQuery + ' AND E.OT_Eligible = 1 AND E.CompOff_Eligible = 0 '
		end
	ELSE IF(@SanctionType = 'compoff')
		BEGIN
			set @sqlQuery = @sqlQuery + ' AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 '
		END	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end
	set @sqlQuery = @sqlQuery + ' And E.isdeleted=0 and E.report_exclude=0 and E.employee_status=1'
	if not(@EmployeeName='')
	begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@empId='')
	begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
	end
	If Not (@EmpSwipeCard = '')
    Begin  
		  Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End
	if not(@status='' or @status='All')
	begin
	 	IF(@status = 'Pending')
			BEGIN
				set @sqlQuery = @sqlQuery + ' AND (TPD.OvertimeStatus IS NULL OR TPD.OvertimeStatus = ''' + @status + ''')'
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + ' AND TPD.OvertimeStatus = ''' + @status + ''''
			END
	end 
	set @sqlQuery = @sqlQuery + ' order by Employee_Code_Id , Date'
	exec (@sqlQuery)
	--print (@sqlQuery)
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_EmployeeOTStatus  
Description : To Update the OverTime Status in ta_tbl_processedData  table
Tables Included : ta_tbl_ProcessedData,ta_tbl_Employee  
Created By : Sasireka  
Created On : 09-Jan-2009  
Modified By :  
Modified On :  
*/  
--Proc_TA_EmployeeOTStatus '100','Approved','2017-03-23','<DocumentElement><Table><Process_Rec_ID>20575</Process_Rec_ID><Employee_Id>2</Employee_Id><ActHrsOT>13:30</ActHrsOT><ActOffOT>13:30</ActOffOT><ActHolOT>13:30</ActHolOT><ActOtMins>810</ActOtMins><ExtraTime_Id>258</ExtraTime_Id></Table></DocumentElement>',1
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeOTStatus]
(
@EmployeeCode nvarchar(20),
@Status varchar(20),
@OtDate datetime,
@xml xml,
@isRequest int
)
As
BEGIN 
		set nocount on
		Declare @Index int
		Set @Index = 0;
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		update ta_tbl_ProcessedData set ta_tbl_ProcessedData.OverTimeStatus=@Status
		from OpenXML(@Index, '/DocumentElement/Table')
		--With (Process_Rec_ID Bigint 'Process_Rec_ID',SelectedRecords int 'SelectedRecords')) OT ON OT.Process_Rec_ID=PD.Process_Rec_ID
		With (Process_Rec_ID Bigint 'Process_Rec_ID') as OT 
		inner join ta_tbl_ProcessedData pd
		ON OT.Process_Rec_ID=PD.Process_Rec_ID
		--Where OT.SelectedRecords=1		 
		Exec sp_xml_removedocument @Index
		if(@isRequest=1)
			BEGIN
			EXEC sp_xml_preparedocument @Index OUTPUT, @xml
			--Update the OverTime Status
			update TA_Tbl_OverTimeStatus set TA_Tbl_OverTimeStatus.OverTimeStatus=@Status
			from OpenXML(@Index, '/DocumentElement/Table')
			With (ExtraTime_Id Bigint 'ExtraTime_Id') as OT 
			inner join TA_Tbl_OverTimeStatus OTT
			ON OT.ExtraTime_Id=OTT.ExtraTime_Id
			Exec sp_xml_removedocument @Index
			--Create the Temp table for the OverTime Status
			CREATE table #TblRecords (ID int identity(1,1),Process_RecID BIGINT, Employee_Id INT, ExtraMins INT, OverTimeStatus VARCHAR(50),ExtraTime_Id int)
			DECLARE @Index1 INT 
			set @Index1= 0
			EXEC sp_xml_preparedocument @Index1 OUTPUT, @Xml
			--Insert the temp table value
			insert into #TblRecords select Process_Rec_ID,Employee_Id,ActOtMins,@Status,ExtraTime_Id
			FROM OPENXML(@Index1, '/DocumentElement/Table')	WITH(
			Process_Rec_ID BIGINT 'Process_Rec_ID',
			Employee_Id INT 'Employee_Id',
			ActHrsOT varchar(50) 'ActHrsOT',
			ActOtMins VARCHAR(5) 'ActOtMins',
			ExtraTime_Id INT 'ExtraTime_Id'
		   ) AS OT 	
			--select * from #TblRecords
			DECLARE @FromDate DATETIME, @ToDate DATETIME, @MaxDate DATETIME, @DateFormt DATETIME
			DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT
			DECLARE @Employee_code_Id NVARCHAR(50), @OtText VARCHAR(MAX)
			DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT
			DECLARE @ValidDates INT
			declare @EmployeeId bigint
			DECLARE @ExtraOT_ID INT
			Declare @i int=1
			Declare @j int
			select @j=COUNT(*) from #TblRecords
			while(@i<=@j)
				BEGIN
					select @EmployeeId=Employee_Id,@ExtraOT_ID=ExtraTime_Id from #TblRecords where ID=@i
					SELECT @TypeOfOT = OtHourWise,@HalfDayOTMins = DATEDIFF(MI,'00:00', ISNULL(OtMinHrs, '00:00')),@FullDayOTMins = DATEDIFF(MI,'00:00',ISNULL(FullDayOTMinHrs, '00:00')),@ValidDates = ISNULL(LP.CompOffValidDays, 60) FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id WHERE ELP.EmployeeId = @EmployeeId AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeId ORDER BY ELP.ToDate DESC)
					--If the leave policy is Day wise then calculate the overtime hours in day wise
					IF(@TypeOfOT=1)
						BEGIN
							SELECT @SumOfOTMins = (@SumOfOTMins + ExtraMins),@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),@OtText = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @OtText ELSE (@OtText + ';' + CAST(Process_RecID AS VARCHAR(50)) + '&' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),@MaxDate = NULL FROM TA_Tbl_OverTimeStatus WHERE Employee_Id = @EmployeeId AND OvertimeStatus='Approved' and ExtraTime_Id=@ExtraOT_ID
							update TA_Tbl_OverTimeStatus set 
							NoOfDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							RemainingDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),T.[Date]) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END)  FROM TA_Tbl_OverTimeStatus T  where T.ExtraTime_Id=@ExtraOT_ID
						END
					--If the leave policy is hours wise then calculate the overtime hours
					ELSE
						BEGIn
							update TA_Tbl_OverTimeStatus set 
							NoOfDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							RemainingDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),T.[Date]) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END)  FROM TA_Tbl_OverTimeStatus T  where T.ExtraTime_Id=@ExtraOT_ID
						END
				set @i=@i+1
				END
				drop table #TblRecords
	  END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeProcessBonusLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_EmployeeProcessBonusLeave]
@EmployeeSwipeCardNo nvarchar(20),
@FromDate datetime,
@ToDate datetime
AS
BEGIN
SET NOCOUNT ON;
	select count(PD.Employee_Code_Id) as BonusLeaveCount,PD.Employee_Code_Id from ta_tbl_processeddata PD 
	where PD.status='BL' and PD.Employee_Code_Id=@EmployeeSwipeCardNo
	and Date between @FromDate and @ToDate Group by PD.Employee_Code_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeRecentPunchesInDashboard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_EmployeeRecentPunchesInDashboard @Fromdate='2023-09-07'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeRecentPunchesInDashboard] 
	-- Add the parameters for the stored procedure here
	@Fromdate varchar(20),
	@Tag char(10),
	@EmployeeID int=0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	if(@Tag='A')
	begin
		SELECT 
		Top 5
		Emp.Employee_Code_Id,
		Emp.Employee_FirstName as EmployeeName,
		Convert(Date,CR.CLK_DATE)As ShiftDate,
		PunchType,
		CR.CLK_TIME As PunchTime,
		sh.Shift_ShortName As shiftName
		FROM 
			TA_Tbl_Clk_RawData CR
		LEFT JOIN 
			TA_Tbl_Employee Emp
		ON 
			Emp.Employee_Code_Id = CR.CLK_CARDID
		LEFT JOIN 
			TA_Tbl_PunchTypes 
		ON 
			PunchType_Id = CR.CLK_TYPE
			--CASE 
			--    WHEN clk.Clk_InPunchType != '' 
			--    THEN CONVERT(int, clk.Clk_InPunchType) 
			--    ELSE CONVERT(int, clk.Clk_OutPunchType) 
			--END
		LEFT JOIN 
			TA_Tbl_ClockDetails clk 
		ON 
			CR.CLK_CARDID = clk.Clk_EmpId 
			AND clk.Clk_Date = CR.CLK_DATE
		Left Join 
			TA_Tbl_ProcessedData  pd on 
			Emp.Employee_Code_Id=pd.Employee_Code_Id and pd.Date=CR.CLK_DATE
		Left Join
			TA_Tbl_Shift sh 
		oN
			sh.Shift_Id=pd.Shift_Id

		WHERE 
			CR.CLK_DATE = CONVERT(VARCHAR, CONVERT(DATE, @Fromdate, 101), 120) and CR.ReasonId=0  order by  CR.Clk_Time desc

	End
	if(@tag='I')
	begin

			Declare @ReportingtoSanction As Table (id Int Identity(1,1),EmployeeId int)

			Declare @ReportCount int
			Declare @SanctionCount int

			--select @ReportCount=Count(*) from fn_TA_GetMappedEmployees_ReportingTo (34)

			insert into @ReportingtoSanction
				select * from fn_TA_GetMappedEmployees_ReportingTo (@EmployeeID)

			insert into @ReportingtoSanction
				select * from fn_TA_GetMappedEmployees_SancAuthority(@EmployeeID)

			Declare @TempTbl as Table (id int identity(1,1),EmpId int)

			SELECT 
			Top 5
			Emp.Employee_Code_Id,
			Emp.Employee_FirstName as EmployeeName,
			Convert(Date,CR.CLK_DATE)As ShiftDate,
			PunchType,
			CR.CLK_TIME As PunchTime,
			sh.Shift_ShortName As shiftName
			FROM 
			TA_Tbl_Clk_RawData CR
			LEFT JOIN 
				TA_Tbl_Employee Emp
			ON 
				Emp.Employee_Code_Id = CR.CLK_CARDID
			LEFT JOIN 
				TA_Tbl_PunchTypes 
			ON 
				PunchType_Id = CR.CLK_TYPE
				--CASE 
				--    WHEN clk.Clk_InPunchType != '' 
				--    THEN CONVERT(int, clk.Clk_InPunchType) 
				--    ELSE CONVERT(int, clk.Clk_OutPunchType) 
				--END
			LEFT JOIN 
				TA_Tbl_ClockDetails clk 
			ON 
				CR.CLK_CARDID = clk.Clk_EmpId 
				AND clk.Clk_Date = CR.CLK_DATE
			Left Join 
				TA_Tbl_ProcessedData  pd on 
				Emp.Employee_Code_Id=pd.Employee_Code_Id and pd.Date=CR.CLK_DATE
			Left Join
				TA_Tbl_Shift sh 
			oN
				sh.Shift_Id=pd.Shift_Id

			WHERE 
				CR.CLK_DATE = CONVERT(VARCHAR, CONVERT(DATE, @Fromdate, 101), 120) and CR.ReasonId=0 and Employee_Id in (Select DISTINCT EmployeeID From @ReportingtoSanction )  order by  CR.Clk_Time desc

	End
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employees_ForShiftReAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Proc_Ta_Employees_ForShiftReAllocation '04/01/2011','04/30/2011','',18,'','SuperAdmin',323,1
--drop procedure Proc_Ta_Employees_ForShiftReAllocation
CREATE PROCEDURE [dbo].[Proc_Ta_Employees_ForShiftReAllocation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''') as EmployeeName '
	set @sqlQuery = @sqlQuery + ' from ta_tbl_Employee '
    set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)'
	if not(@EmployeeName='')
	begin
		set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if not (@empId='')
	begin
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_Employee.Employee_code_id= ''' + @empId + ''' )'
	end
	set @sqlQuery = @sqlQuery + '  order by ta_tbl_Employee.Employee_FirstName '
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,'0' as SelectedRecords from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	--insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat))
	--update A set A.PreviousDayShift = B.CurrentShiftId
	--from #TempShiftIdForShiftReAllocation A inner join #TempShiftIdForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--update A set A.NextDayShift = B.CurrentShiftId
	--from #TempShiftIdForShiftReAllocation A inner join #TempShiftIdForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeTransferBranch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeTransferBranch]

@ParentID nvarchar(50) = '1'
--@Tag nvarchar = ''
AS
BEGIN

	select id,name from Ta_Tbl_levelDetails where parentId = @ParentID
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeTransferDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeTransferDelete]

@TrnsfrID int 


AS
BEGIN
	
	declare @Employeeid nvarchar(100) 
declare @OldLevelID nvarchar(100) 
Declare @OldDsgtonID nvarchar(100)
--Declare @Trnsfr_Dte date



	Select @Employeeid=Employeeid,@OldDsgtonID=OldDsgtonID,@OldLevelID=OldLevelID from TA_Tbl_EmployeeTransferModule 
WHERE  TrnsfrID = @TrnsfrID

update TA_Tbl_EmployeeLevel set LevelId = @OldLevelID   where EmployeeId =@Employeeid

Update TA_Tbl_EmployeeDesignation Set DesignationID = @OldDsgtonID   where EmployeeID =@Employeeid

Update TA_Tbl_EmployeeTransferModule set  IsDelete=1  where TrnsfrID = @TrnsfrID

	
	   	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeTransferGridSelect]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeTransferGridSelect] 

@Tag nvarchar(50)= '1',
@Employee_Code_Id nvarchar(100) = '',
@FromDate nvarchar(100)='1990-01-01',
@Todate nvarchar(100)='',
@EmployeeName Nvarchar(MAx)=''
AS
BEGIN

declare @EmployeeCode nvarchar(100) , @DateFormate nvarchar(100),@FromatCode int 
Select @DateFormate=DateFormat from TA_Tbl_DateandTimeFormat
	print @DateFormate

	if (@DateFormate ='MM/dd/yyyy')
	begin 
	print @DateFormate
	 set @FromatCode =110
	end 
	else if (@DateFormate ='dd-MMM-yyyy')
	 begin
	 print @DateFormate

	 set @FromatCode =106
	 end 
	 else if (@DateFormate ='dd/MM/yyyy')
	 begin 
	 print @DateFormate
	 set @FromatCode =105
	 end 

if(@Tag = '1')
begin



Select  TrnsfrID, Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Convert(varchar,Convert(date, Trnsfr_From),@FromatCode) as Trnsfr_From,
Convert(varchar,Convert(date, EmployeeTrans_fr_Date),@FromatCode)+ ' To ' +Convert(varchar,Convert(date,EmployeeTrans_To_Date),@FromatCode) as Trnsfr_Dte, 
	 NwOrganizationLevels, NwDsgtonID, NwDsgton, Remarks, 
                         Trnsfr_EtyDteTme, Trnsfr_Emp_ID
 from  TA_Tbl_EmployeeTransferModule 
 
 where Trnsfr_From between case when @FromDate='1990-01-01'then Trnsfr_From else @FromDate end and 
 case when @Todate ='' then Trnsfr_From else @Todate end and 
 Employee_Code =case when  @Employee_Code_Id ='' then Employee_Code else @Employee_Code_Id end
 and Employee_Name = case when @EmployeeName ='' then Employee_Name else @EmployeeName end
and IsDelete =0

 end
else if(@Tag = '2')
 begin 

 Select [dbo].[Func_TA_GetParentIds](Ta_Tbl_levelDetails.id) as PerantID, 
 TA_Tbl_Employee.Employee_FirstName +TA_Tbl_Employee.Employee_MiddleName + TA_Tbl_Employee.Employee_LastName as Employee_Name,
dbo.Fn_GetWholeLevelName(Ta_Tbl_levelDetails.id) as ORGDetails, 
 TA_Tbl_Title.TitleName as Design,TA_Tbl_Employee.Employee_id,TA_Tbl_EmployeeLevel.LevelId,TA_Tbl_EmployeeDesignation.DesignationID
 from TA_Tbl_Employee 
 inner join TA_Tbl_EmployeeDesignation on TA_Tbl_EmployeeDesignation.EmployeeID = TA_Tbl_Employee.Employee_Id 
 inner join TA_Tbl_Title on TA_Tbl_Title.TitleId = TA_Tbl_EmployeeDesignation.DesignationID
 inner join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id 
 inner join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id = TA_Tbl_EmployeeLevel.levelId
 Where Employee_Code_Id = @Employee_Code_Id

 
 end
 End


 --Select * from TA_Tbl_EmployeeDesignation
 --Select * from TA_Tbl_Title
 --Select * from TA_Tbl_EmployeeLevel 
 
 --Select * from Ta_Tbl_levelDetails
 --Select * from TA_Tbl_EmployeeTransferModule
-- select * from TA_Tbl_EmployeeDesignation where EmployeeId = 14
--Update TA_Tbl_EmployeeDesignation set DesignationID = 10 Where EmployeeID =11






--Select * From dbo.[fn_TA_GetParentChild]('superAdmin',)


--select * from TA_Tbl_Title where TitleId ='5'
--Select * from TA_Tbl_EmployeeDesignation where EmployeeID = '74'
--select * from Ta_Tbl_levelDetails where id = 10
--Select * from TA_Tbl_Employee   Where Employee_Code_Id = 'E015'

--select * from TA_Tbl_EmployeeLevel where EmployeeId = 54
--select * from Ta_Tbl_levelDetails where parentId = 1
--Select [dbo].[Split](dbo.Fn_GetWholeLevelName(7),2)
--Select [dbo].Split (dbo.Fn_GetWholeLevelName(7),'/')
--Angler Technologies India Pvt Ltd / Timecheck / Testing
 --select * from dbo.Split(dbo.Fn_GetWholeLevelName(7),'/')
--CREATE TABLE #EmailCheckPerson (

--Employeeid int,
--Employee_Code int,
--Employee_Name nvarchar(Max) ,
--OldCompany nvarchar(max),
--OldBranch int ,
--Olddepartment int,
--Trnsfr_From datetime ,
--Trnsfr_Dte datetime  ,
--NwCompany int ,
--NwBranch int ,
--Nwdepartment int ,
--NwDsgtonID int,
--Trnsfr_EtyDteTme datetime ,
--Remarks nvarchar(Max)

--);

--Declare @query nvarchar(MAX)=''

----select * from TA_Tbl_EmployeeTransferModule where Employee_Code =@Employee_Code_Id and Employee_Name =@EmployeeName
--	set @query= 'Select  TrnsfrID, Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Trnsfr_From, Trnsfr_Dte, 
--	NwCompanyID, NwCompany, NwBranchID, NwBranch, NwdepartmentID, Nwdepartment, NwDsgtonID, NwDsgton, Remarks, 
--                         Trnsfr_EtyDteTme, Trnsfr_Emp_ID

-- from  TA_Tbl_EmployeeTransferModule'


-- if(@FromDate ='')
-- begin
--  Set @query=''
-- end
-- else
-- begin
-- set @query= 'Select  TrnsfrID, Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Trnsfr_From, Trnsfr_Dte, 
--	NwCompanyID, NwCompany, NwBranchID, NwBranch, NwdepartmentID, Nwdepartment, NwDsgtonID, NwDsgton, Remarks, 
--                         Trnsfr_EtyDteTme, Trnsfr_Emp_ID

-- from  TA_Tbl_EmployeeTransferModule where Trnsfr_From between '''+CONVERT(datetime,@FromDate )  +''' and '''+ CONVERT(datetime,@Todate ) +''''
-- end
-- if(@Employee_Code_Id ='' and @FromDate ='')
-- begin
--  Set @query = ''
-- end
-- else
-- begin
 
-- if(@Employee_Code_Id ='')
-- begin
-- Set @query = 'Select  TrnsfrID, Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Trnsfr_From, Trnsfr_Dte, 
--	NwCompanyID, NwCompany, NwBranchID, NwBranch, NwdepartmentID, Nwdepartment, NwDsgtonID, NwDsgton, Remarks, 
--                         Trnsfr_EtyDteTme, Trnsfr_Emp_ID

-- from  TA_Tbl_EmployeeTransferModule where Trnsfr_From between '''+CONVERT(datetime, @FromDate)+''' and '''+ CONVERT(datetime,@Todate )+''''
--end
-- else
-- begin
-- Set @query = 'Select  TrnsfrID, Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Trnsfr_From, Trnsfr_Dte, 
--	NwCompanyID, NwCompany, NwBranchID, NwBranch, NwdepartmentID, Nwdepartment, NwDsgtonID, NwDsgton, Remarks, 
--                         Trnsfr_EtyDteTme, Trnsfr_Emp_ID

-- from  TA_Tbl_EmployeeTransferModule where Trnsfr_From between '''+CONVERT(datetime, @FromDate )+''' and '''+ CONVERT(datetime,@Todate ) +''' and Employee_Code = '''+@Employee_Code_Id+''''
-- end
-- end
-- --if(@EmployeeName !='')
-- --begin
-- --set @query ='Employee_Name = @EmployeeName'
-- --end
 
  
--Exec @query 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeTransferInsert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeTransferInsert]

--SP_Help TA_Tbl_EmployeeTransferModule
@Employeeid int = 74,
@Employee_Code nvarchar(50) = '0421',
@Employee_Name nvarchar (100) = 'Transfer module',
@Trnsfr_From nvarchar(50) ='2023-08-26',
--@Trnsfr_Dte nvarchar(50) ='2023-08-28' ,
@OrganizationLevels nvarchar(Max)='Angler Technologies India Pvt Ltd / Timecheck / Testing',
@Trnsfr_EtyDteTme nvarchar(50) ='2023-08-26',
@Remarks nvarchar(Max)='Needs',
@Trnsfr_Emp_ID nvarchar(100)='1',
@NwOrganizationLevels nvarchar(MAX)= 'Angler Technologies India Pvt Ltd/Timecheck/PC',
@NwDsgton nvarchar(Max)='Associative Product Leader',
@NwDsgtonID int ='5',
@OldLevelID int ='8',
@NwLevelID int ='6',
@Flag int ='0',
@EmployeeTrans_fr_Date Date ='',
@EmployeeTrans_To_Date date ='',
@OldDsgtonID int ='',
@IsDelete int =0


AS
BEGIN
	 Insert into TA_Tbl_EmployeeTransferModule ( Employeeid, Employee_Code, Employee_Name, OrganizationLevels, Trnsfr_From,
	NwOrganizationLevels ,OldLevelID,NwLevelID, NwDsgtonID,NwDsgton, Remarks, Trnsfr_EtyDteTme, Trnsfr_Emp_ID,Flag,
	EmployeeTrans_fr_Date,EmployeeTrans_To_Date,OldDsgtonID,IsDelete) 
	
	Values ( @Employeeid, @Employee_Code, @Employee_Name, @OrganizationLevels, @Trnsfr_From,
	@NwOrganizationLevels, @OldLevelID,@NwLevelID, @NwDsgtonID,@NwDsgton, @Remarks, @Trnsfr_EtyDteTme, 
	@Trnsfr_Emp_ID,@Flag,@EmployeeTrans_fr_Date,@EmployeeTrans_To_Date,@OldDsgtonID,@IsDelete)

	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]'2014-09-11','787,788,789,8,888',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpType]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeType int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql='
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 '
	if (@Employee_Code_Id<>'')
		if(@employeeType<>0 and @employeeType!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and et.TypeId='+CONVERT(varchar(20),@employeeType)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	else 
		if(@employeeType<>0 and @employeeType!='')
			BEGIN					
				Set @sql=@sql+' and et.TypeId='+CONVERT(varchar(20),@employeeType)
			End
		else
			Begin				
				Set @sql=@sql 
			end				
	Set @sql=@sql+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102)  and EType.TypeId is not null'	
	execute(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType_MusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]'2014-09-11','787,788,789,8,888',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpType_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeType int,
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if (@Employee_Code_Id<>'')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = ','
			set @NextString = ''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''
					begin
						set @NextString =''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				else
					begin
						set @NextString =@NextString+','+''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql='	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
					inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 group by et.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				) EmpType
				inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
				AND EType.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102)  and EType.TypeId is not null'
	if (@Employee_Code_Id<>'')
		if(@employeeType<>0 and @employeeType!='')
			BEGIN									
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+') and EType.TypeId='+CONVERT(varchar(20),@employeeType)
			End
		else
			begin					
				Set @sql=@sql+' and Employee_Code_Id in('+cast(@Employee_Code_Id as varchar(max))+')'
			End
	else 
		if(@employeeType<>0 and @employeeType!='')
			BEGIN					
				Set @sql=@sql+' and EType.TypeId='+CONVERT(varchar(20),@employeeType)
			End
		else
			Begin				
				Set @sql=@sql 
			end				
	execute(@sql)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterpriseGradeUpdation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	03-Oct-2013
Descriptinos	:	For updating grade while uploading LIC file as Enterprise
*/
CREATE proc [dbo].[Proc_TA_EnterpriseGradeUpdation]
as 
begin
	set nocount on
	UPDATE TA_Tbl_Grade SET Isdeleted =1 where Grade_ID=(select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade')
	UPDATE TA_Tbl_Grade SET Isdeleted =0 where Grade_ID!=(select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade')
	update TA_Tbl_Employee set Leave_Sanc_Authority=Te.Leave_Sanc_Authority,Reporting_To=TE.Reporting_To from TA_Tbl_Employee E
	inner join tempemployee Te on E.Employee_Id=Te.Employee_Id
	WHERE Employee_Code_Id <> '18000000'	
	update TA_Tbl_Title set GradeID=tt.GradeID from TA_Tbl_Title t
	inner join temptitle tt on t.TitleId =tt.TitleId 
	Insert into TA_Tbl_ApprovalSettings
	select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry ,Approval,0,shiftRequitionSaction
	from TempApprovalSettings
	delete from TempApprovalSettings	
End


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_EarlyOut]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 August 2007
-- Description:	Enter Reason for Late entry in Processed data table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EnterReason_EarlyOut] 
	-- Add the parameters for the stored procedure here
	@Reason NVARCHAR(255),
	@ID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET EarlyOutReason=@Reason WHERE Process_Rec_ID=@ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_LateIn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 August 2007
-- Description:	Enter Reason for Late entry in Processed data table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EnterReason_LateIn] 
	-- Add the parameters for the stored procedure here
	@Reason NVARCHAR(255),
	@ID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET LateEntryReason=@Reason WHERE Process_Rec_ID=@ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ErrorsOfWindowsService_Abraj]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <12-Feb-2020>
-- Description:	<Error writting in database>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_ErrorsOfWindowsService_Abraj]
@EmployeeId varchar(50), @Erormsg varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	insert into Ta_Tbl_Error_ImportData_Samsung values (@EmployeeId, @Erormsg,getdate())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportDataCentena]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ExportDataCentena]
AS
BEGIN
	declare @StartDate as datetime
	declare @EndDate as datetime
	set @EndDate = convert(varchar(10),getdate(),101)
	set @StartDate = dateadd(day, -6, @EndDate)
	insert into TA_Tbl_ExportDataCentena
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id, 
	'AB' as type ,count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,'Absent') as remarks
	from ta_tbl_processedData 
	where attendance ='Absent' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
	union all
--Sick Leave
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id, 
	'SL' as type ,count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,'SL') as remarks
	from ta_tbl_processedData 
	where LeaveCode ='SL' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
	union all
-- Annual Leave
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id,
	'AL' as type , count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,'AL') as remarks
	from ta_tbl_processedData 
	where LeaveCode ='AL' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportLeaveData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 18-Aug-2011
-- Description:	ihave
-- =============================================
--Proc_TA_ExportLeaveData ' Employee_Code_Id, Leave_FromDate, Leave_Todate, LeaveType, NoOfDays, TransactionType',4,'SuperAdmin',1,'D',1
CREATE PROCEDURE [dbo].[Proc_TA_ExportLeaveData]
(
 @SelectedFieldNames nvarchar(2000),
 @MonthClosureId int,
 @UserGroupName varchar(250),
 @ParentID int,
 @Option varchar(10),
 @strFTPOption varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @QUERY VARCHAR(250)
	declare @FromDate datetime
	set @FromDate = (select MonthClosure_Startdate from TA_Tbl_MonthClosure where MonthClosure_Id=@MonthClosureId)
	declare @ToDate datetime
	set @ToDate = (select MonthClosure_Enddate from TA_Tbl_MonthClosure where MonthClosure_Id=@MonthClosureId)
	create table #LevelRights(LevelId int)
    insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
    create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempLeaveData (	
									LeaveApplication_Id int,
									Employee_Code_Id nvarchar(15),
									Employee_Name nvarchar(150),
									Leave_FromDate varchar(25),
									Leave_ToDate varchar(25),
									LeaveType varchar(30),
									LeaveType_Id int,
									NoOfDays numeric(18,1),
									TransactionType varchar(5)
									,ExportSummary_InsertFlag bit default(0),
									ExportSummary_DeleteFlag bit default(0),
									ExportDetail_InsertFlag bit default(0),
									ExportDetail_DeleteFlag bit default(0),
									IsDeleted bit default (0)
								)
    if (@strFTPOption='1')
		BEGIN
			insert into #TempLeaveData 					
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + ' ' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then 'D' else 'I' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = 'Approved' 
					and (ExportDetail_InsertFlag=0 and ExportDetail_DeleteFlag=0)
		END
   else
		BEGIN
			insert into #TempLeaveData 						
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + ' ' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then 'D' else 'I' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = 'Approved' 
		END
	update #TempLeaveData set LeaveType = LT.LeaveType from #TempLeaveData
	left join TA_tbl_LeaveType LT on #TempLeaveData.LeaveType_Id = LT.LeaveType_Id
	where #TempLeaveData.LeaveType = 'Leave'
	if(@Option = 'D')
	Begin
	    SET @QUERY=''
	    SET @QUERY='select '+ @SelectedFieldNames + ' from #TempLeaveData'
	    update #TempLeaveData set ExportDetail_InsertFlag=1 where TransactionType='I' 
	    update #TempLeaveData set ExportDetail_DeleteFlag =1 where TransactionType='D'
	End
	else
	Begin 
		SET @QUERY=''
		SET @QUERY='SELECT ' + @SelectedFieldNames + ' from (select Employee_Code_Id,sum(NoOfDays) as NoOfDays from #TempLeaveData where TransactionType=''I'' group by Employee_Code_Id) ppd '
		  update #TempLeaveData set ExportSummary_InsertFlag=1 where TransactionType='I' 
	      update #TempLeaveData set ExportSummary_DeleteFlag =1 where TransactionType='D'
	End
	EXEC(@QUERY)
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + ' ' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then 'D' else 'I' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = 'Approved' 
					and (ExportDetail_InsertFlag=0 and ExportDetail_DeleteFlag=0)
	drop table #EmpLevel
	drop table #TempLeaveData
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptShiftAllocation '01/01/2014','12/31/2014','','','','','','SuperAdmin',1,'',0,0,'Both'
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By : Manjula.P  
Created on : 27-Aug-14    
-- Description	:	SQL Query Optimazation & Emp name filtering
exec Proc_TA_ExportShiftAllocation @fromDat='2014-01-01 00:00:00',
@ToDat='2014-08-19 00:00:00',@EmployeeName=N'',@LevelID=N'1',
@EmployeeId=N'',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',
@EmpSwipeCard=N'',@ParentId=1,@DesignationID=0,@Gender=N'Both'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ExportShiftAllocation] 
(
 @Employee_ID int,
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000), 
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10)		
)	
AS  
BEGIN  
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Level insert in Temporary table
Declare @sqlEmpLevel nvarchar(4000)
Declare @sqlCommon nvarchar(4000)
set @sqlEmpLevel=
	'insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''')'
Execute(@sqlEmpLevel)
	--Employee Designation insert in Temporary table
Declare @sqlEmpDesi nvarchar(4000)
set @sqlEmpDesi=
'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(8)) + ''')'
Execute(@sqlEmpDesi)
--Employee Type insert in Temporary table
Declare @sqlEmpType nvarchar(4000)
set @sqlEmpType=
'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
Execute(@sqlEmpType)
--Employee Category insert in Temporary table
Declare @sqlEmpCategory nvarchar(4000)
set @sqlEmpCategory=
'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
Execute(@sqlEmpCategory)
--select * from #EmpLevel
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
	set @sqlQuery = 'select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') as Employee_FirstName,
	e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,
	ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,
	ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,
	ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender,
	[dbo].[Func_TA_GetParentIds](Ta_Tbl_levelDetails.id) as ParentLevelId
	from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	--set @sqlQuery = @sqlQuery + ' left outer join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId  '
	set @sqlQuery=@sqlQuery + ' where e.Isdeleted=0 and 
	 e.Report_exclude=0 and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat as nvarchar(20)) +''', 102 ))as nvarchar(10)),102) '
	set @sqlQuery=@sqlQuery + ' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102 ))as nvarchar(10)),102)'
	if not(@EmployeeName='')  
		begin  
			--set @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		Declare @Tempname nvarchar(200)
         set @Tempname= '(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')'
	     set @sqlQuery = @sqlQuery + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 
		end  
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>=' + @GradeLevel  
		end
	if not(@EmployeeId='')  
		begin  
			set @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
		end
	set @sqlQuery = @sqlQuery + ' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month'   
	create table #TempExportShift
	(
	Employee_FirstName varchar(250),
	employee_id varchar(50),
	Year int,
	Month int,
	Day1Shift int,
	Day2Shift int,
	Day3Shift int,
	Day4Shift int,
	Day5Shift int,
	Day6Shift int,
	Day7Shift int,
	Day8Shift int,
	Day9Shift int,
	Day10Shift int,
	Day11Shift int,
	Day12Shift int,
	Day13Shift int,
	Day14Shift int,
	Day15Shift int,
	Day16Shift int,
	Day17Shift int,
	Day18Shift int,
	Day19Shift int,
	Day20Shift int,
	Day21Shift int,
	Day22Shift int,
	Day23Shift int,
	Day24Shift int,
	Day25Shift int,
	Day26Shift int,
	Day27Shift int,
	Day28Shift int,
	Day29Shift int,
	Day30Shift int,
	Day31Shift int,
	emp_id int,
	TimeStamp datetime,
	DateShift datetime,
	TitleName varchar(250),
	Gender varchar(100),
	ParentLevelId int
	)	
	insert into #TempExportShift 
	exec(@sqlQuery)  
	create table #TempParentLevels
	(
	ParentId int,
	CompanyName varchar(300)
	)
	insert into #TempParentLevels
	select id,name from Ta_Tbl_levelDetails where parentId=0
	select Employee_FirstName,
	employee_id ,
	Year ,
	Month ,
	Day1Shift ,
	Day2Shift ,
	Day3Shift ,
	Day4Shift ,
	Day5Shift ,
	Day6Shift ,
	Day7Shift ,
	Day8Shift ,
	Day9Shift ,
	Day10Shift ,
	Day11Shift ,
	Day12Shift ,
	Day13Shift ,
	Day14Shift ,
	Day15Shift ,
	Day16Shift ,
	Day17Shift ,
	Day18Shift ,
	Day19Shift ,
	Day20Shift ,
	Day21Shift ,
	Day22Shift ,
	Day23Shift ,
	Day24Shift ,
	Day25Shift ,
	Day26Shift ,
	Day27Shift ,
	Day28Shift ,
	Day29Shift ,
	Day30Shift ,
	Day31Shift ,
	emp_id ,
	TimeStamp ,
	DateShift ,
	TitleName ,
	Gender ,LD.CompanyName as Company_Name from #TempExportShift
	inner join #TempParentLevels LD on LD.ParentId=#TempExportShift.ParentLevelId
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights 	
	drop table #TempExportShift
	drop table #TempParentLevels
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 
Procedure Name : Proc_TA_RptTempShiftAllocation  '01/01/2008','12/27/2012','','','','','','SuperAdmin','','',0,0,'Both'
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ExportTempShiftAllocation]  
(
 @Employee_ID int,
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10)	
)	
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) AS LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level INSERT in Temporary table
	INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	SELECT max(el.EffectiveDate) AS EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	SELECT max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type INSERT in Temporary table
	INSERT INTO #EmpType SELECT EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	SELECT max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category INSERT in Temporary table
	INSERT INTO #EmpCategory SELECT EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	SELECT max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @sqlQuery AS varchar(8000)  
	SET @sqlQuery=''  
	SET @sqlQuery = 'SELECT e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') AS Employee_FirstName,e.employee_code_id AS employee_id,ts.Year,ts.Month,ts.Day1Shift,ts.Day2Shift,ts.Day3Shift,ts.Day4Shift,ts.Day5Shift,ts.Day6Shift,ts.Day7Shift,ts.Day8Shift,ts.Day9Shift,ts.Day10Shift,ts.Day11Shift,ts.Day12Shift,ts.Day13Shift,ts.Day14Shift,ts.Day15Shift,ts.Day16Shift,ts.Day17Shift,ts.Day18Shift,ts.Day19Shift,ts.Day20Shift,ts.Day21Shift,ts.Day22Shift,ts.Day23Shift,ts.Day24Shift,ts.Day25Shift,ts.Day26Shift,ts.Day27Shift,ts.Day28Shift,ts.Day29Shift,ts.Day30Shift,ts.Day31Shift,ts.emp_id,ts.TimeStamp,ts.DateShift,TA_Tbl_Title.TitleName AS TitleName,e.Gender,
	[dbo].[Func_TA_GetParentIds](Ta_Tbl_levelDetails.id) as ParentLevelId 
	from TA_Tbl_TemporaryShiftAllocation ts 
	inner join TA_Tbl_Employee e on e.Employee_Id=ts.EmployeeId '
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	SET @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.employee_Status=1 and e.Report_exclude=0 '  
	SET @sqlQuery=@sqlQuery + ' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat AS nvarchar(20)) + ''', 102)) AS nvarchar(20))+''/''+ cast(1 AS nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat AS nvarchar(20)) +''', 102 ))AS nvarchar(10)),102) '
	SET @sqlQuery=@sqlQuery + ' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat AS nvarchar(20)) + ''', 102)) AS nvarchar(20))+''/''+ cast(1 AS nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat AS nvarchar(20)) + ''', 102 ))AS nvarchar(10)),102)'
	if not(@EmployeeName='')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName + '' '' +  isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' AS nvarchar(100)) + ''')'
		END
	If Not (@EmpSwipeCard = '')  
		BEGIN  
			Set @sqlQuery = @sqlQuery + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if not(@EmployeeId='')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId AS nvarchar(100)) + ''')'  
		END  
	if(@Gender<>'Both')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender AS nvarchar(8)) + ''' '
		END	
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID AS nvarchar(8))
		END	
	if(@UserGroupName<>'SuperAdmin')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType AS nvarchar(8))
		END		
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpCategory.CategoryId = ' + cast(@employeeCategory AS nvarchar(8))
		END
	SET @sqlQuery = @sqlQuery + ' order by e.employee_code_id,e.Employee_FirstName,ts.Year,ts.Month'   
	create table #TempExportShift
	(
	Employee_FirstName varchar(250),
	employee_id varchar(50),
	Year int,
	Month int,
	Day1Shift int,
	Day2Shift int,
	Day3Shift int,
	Day4Shift int,
	Day5Shift int,
	Day6Shift int,
	Day7Shift int,
	Day8Shift int,
	Day9Shift int,
	Day10Shift int,
	Day11Shift int,
	Day12Shift int,
	Day13Shift int,
	Day14Shift int,
	Day15Shift int,
	Day16Shift int,
	Day17Shift int,
	Day18Shift int,
	Day19Shift int,
	Day20Shift int,
	Day21Shift int,
	Day22Shift int,
	Day23Shift int,
	Day24Shift int,
	Day25Shift int,
	Day26Shift int,
	Day27Shift int,
	Day28Shift int,
	Day29Shift int,
	Day30Shift int,
	Day31Shift int,
	emp_id int,
	TimeStamp datetime,
	DateShift datetime,
	TitleName varchar(250),
	Gender varchar(100),
	ParentLevelId int
	)	
	insert into #TempExportShift  
	exec(@sqlQuery)  
	create table #TempParentLevels
	(
	ParentId int,
	CompanyName varchar(300)
	)
	insert into #TempParentLevels
	select id,name from Ta_Tbl_levelDetails where parentId=0
	select Employee_FirstName,
	employee_id ,
	Year ,
	Month ,
	Day1Shift ,
	Day2Shift ,
	Day3Shift ,
	Day4Shift ,
	Day5Shift ,
	Day6Shift ,
	Day7Shift ,
	Day8Shift ,
	Day9Shift ,
	Day10Shift ,
	Day11Shift ,
	Day12Shift ,
	Day13Shift ,
	Day14Shift ,
	Day15Shift ,
	Day16Shift ,
	Day17Shift ,
	Day18Shift ,
	Day19Shift ,
	Day20Shift ,
	Day21Shift ,
	Day22Shift ,
	Day23Shift ,
	Day24Shift ,
	Day25Shift ,
	Day26Shift ,
	Day27Shift ,
	Day28Shift ,
	Day29Shift ,
	Day30Shift ,
	Day31Shift ,
	emp_id ,
	TimeStamp ,
	DateShift ,
	TitleName ,
	Gender ,LD.CompanyName as Company_Name from #TempExportShift
	inner join #TempParentLevels LD on LD.ParentId=#TempExportShift.ParentLevelId
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
	drop table #TempExportShift
	drop table #TempParentLevels
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FencingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_FencingDetails 0

-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_FencingDetails]
	-- Add the parameters for the stored procedure here
	@fencingId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	
	Select * From TA_tbl_Fencing where (FencingId=@fencingId or @fencingId=0 )
   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Modified BY		: Manikandan.RR
Created Date	:	17-03-2018
-- Modified By:Manikandan.RR
-- Modified Date:12-Jul-2019 03:45 PM
Descriptions	:	Creating Proc_TA_FillingLeaveTypesforEmployeeMaster proc for loading leave type details for employee modifiy page
[Proc_TA_FillingLeaveTypesforEmployeeMaster] 4,2
*/
CREATE proc [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]
(
	@EmployeeId int,
	@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	--Declaring variables
	declare @CurrentYear as int;
	declare @getFirstPreviousYearCount as int;
	declare @EndYear as int;
	declare @UsedCount as int;
	--Initializing variables
	set @EndYear=0;
	set @getFirstPreviousYearCount=0;
	set @CurrentYear=0;
	set @UsedCount=0;
	--getting current financial year
	select @CurrentYear=StartYear,@EndYear=EndYear from TA_Tbl_YearSetting where YearSettings_Id=@YearSettingsId and IsActive=1
	--select @getFirstPreviousYearCount=COUNT(*) from TA_Tbl_YearSetting where StartYear<@CurrentYear and EndYear<@EndYear
	--select @getFirstPreviousYearCount
	--Commented by Manikandan.RR for loading leaveType for every year concept. on 17-03-2018	
	--This point implemented for version 2.7 below version it wont load the controls for every year.i.e it will load for current year only.
	--if(@getFirstPreviousYearCount=0)
	--	begin
	Declare @PrevYear int
	set @PrevYear=0
	--if(@getFirstPreviousYearCount!=0)
	--begin
	Declare @PrevYearID int
	select top 1 @PrevYearID=YearSettings_Id from TA_Tbl_YearSetting where YearSettings_Id<@YearSettingsId order by YearSettings_Id desc
	if Exists(select YearClosed from TA_Tbl_YearClosure where Year_SettingID=@PrevYearID and YearClosed is not null)
	begin
		set @PrevYear=1
	end
	--end
	if(@PrevYear=0)
	begin
		if ((select count(LeaveTypeDetailsId) from ta_tbl_emp_LeaveTypedetails where EmployeeId=@EmployeeId and YearSettingsId=@YearSettingsId)>0)
			begin
				select LT.LeaveType_Id as Emp_LeaveType_Id,LeaveType=LT.LeaveDescription+' ('+LT.LeaveType+')',LTD.PreviousYearBalance,LTD.NoOffLeaveAvailed from ta_tbl_emp_LeaveTypedetails LTD
				right join	ta_tbl_leaveType LT on LTD.LeaveTypeId=LT.LeaveType_Id
				where (LTD.EmployeeId=@EmployeeId and LTD.YearSettingsId=@YearSettingsId and lt.IsDeleted=0)
				or(LT.LeaveType_Id not in(select ELTemp.LeaveTypeId from ta_tbl_emp_LeaveTypedetails ELTemp))
				select 'true' as valid
				select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
			end
		else
			begin
				select LeaveType_Id as Emp_LeaveType_Id,LeaveType=LeaveDescription+' ('+LeaveType+')',0 as PreviousYearBalance,0 as NoOffLeaveAvailed from ta_tbl_leavetype where IsDeleted=0
				select 'false' as valid
				select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
			end
	end
	else
		begin
			select LeaveType_Id as Emp_LeaveType_Id,LeaveType=LeaveDescription+' ('+LeaveType+')',isnull(LEV.PreviousYearBalance,0) as PreviousYearBalance,isnull(LEV.NoOffLeaveAvailed,0) as NoOffLeaveAvailed from TA_Tbl_LeaveType
			left outer join ta_tbl_emp_LeaveTypedetails LEV on LEV.EmployeeId = @EmployeeId and TA_Tbl_LeaveType.LeaveType_Id = LEV.LeaveTypeId
			select 'false' as valid
			select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
		end
	select @UsedCount as UsedCount;
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_FillTempProcessTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_FillTempProcessTable]
	-- Add the parameters for the stored procedure here
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	DELETE FROM TA_Tbl_DataProcessTemp
    -- Insert statements for procedure here
	;WITH CTE AS
	(    
		SELECT @date as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,convert(datetime,convert(varchar(11),[DATE])))FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FinalProgressUpdation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_FinalProgressUpdation '06/10/2020',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_FinalProgressUpdation]
	@ShiftDate datetime,
	@empID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	update Ta_tbl_TaskProgressDetails set isSubmitted_Completely=1 where shiftDate=@ShiftDate and TaskSubmittedby=@empID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GeoFencingAllocationGridSelect]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GeoFencingAllocationGridSelect]

@EmployeeName nvarchar (100) ='',
@FromDate Datetime = '1990-01-01',
@ToDate DAtetime = '2023-07-30',
@EmployeeCode Nvarchar(100) =''
 --@EmployeeId int,
 --@FromDate Datetime,
 --@ToDate DateTime,


AS
BEGIN

select TA_tbl_Fencing .Fencing_Name,TA_Tbl_Employee.Employee_FirstName + TA_Tbl_Employee.Employee_MiddleName + TA_Tbl_Employee.Employee_LastName as EmployeeName ,TA_Tbl_Employee.Employee_Code_Id,* from TA_tbl_GeoFencingAllocation
 inner join TA_tbl_Fencing on TA_tbl_Fencing .FencingId =TA_tbl_GeoFencingAllocation.FencingId
 inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = TA_tbl_GeoFencingAllocation.EmployeeId

 where  TA_Tbl_Employee.Employee_FirstName + TA_Tbl_Employee.Employee_MiddleName + TA_Tbl_Employee.Employee_LastName 
 = Case when @EmployeeName != '' then  @EmployeeName else TA_Tbl_Employee.Employee_FirstName + TA_Tbl_Employee.Employee_MiddleName + TA_Tbl_Employee.Employee_LastName  end

 and TA_Tbl_Employee.Employee_Code_Id = case when @EmployeeCode !='' then @EmployeeCode else TA_Tbl_Employee.Employee_Code_Id end 
 and TA_tbl_GeoFencingAllocation.FromDate between @FromDate and @ToDate 

 --case when   @FromDate != '' then  @FromDate & @ToDate  else TA_tbl_GeoFencingAllocation.FromDate end
 

	--select * from TA_tbl_GeoFencingAllocation

	--select * from TA_tbl_Fencing
	--Select * From  Ta_tbl_LandMarks
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GeoFencingAllocationInsert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GeoFencingAllocationInsert]


@EmployeeId int, 
@FencingId int,
@FromDate Date,
@Todate Date,
@CreatedBy int,
@CreatedOn Datetime,
@ModifyBy int,
@ModifyOn Datetime, 
@months nvarchar,
@years nvarchar

AS
BEGIN

--select * from TA_tbl_GeoFencingAllocation

Insert into TA_tbl_GeoFencingAllocation (  EmployeeId, FencingId, FromDate, Todate, CreatedBy, CreatedOn, ModifyBy, ModifyOn, months, years)
values (@EmployeeId, @FencingId, @FromDate, @Todate, @CreatedBy, @CreatedOn, @ModifyBy, @ModifyOn, @months, @years)


	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GeoFencingAllocationSelect]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_GeoFencingAllocationSelect]
AS
BEGIN

--select * from TA_tbl_GeoFencingAllocation

select * from TA_tbl_Fencing
	
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_one]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_get_level_one]
	@para int
AS
BEGIN
	SELECT levelID,levelname from Ta_Tbl_level where isdeleted=0 and parentlevelId=2  order by levelname
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org]
(
	@para1 int	
	--@LevelIDs nvarchar(1000)
)
AS
BEGIN
	declare @Query as nvarchar(4000)
	SELECT id,name from Ta_Tbl_levelDetails where parentId=@para1  and isdeleted=0 order by Name
	--set @Query = 'SELECT id,name from Ta_Tbl_levelDetails where parentId=' + cast (@para1 as nvarchar(100)) + '  and isdeleted=0 and id in (' + @LevelIDs + ')  order by Name'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_get_level_Org_Updated 917,'533',917,'SuperAdmin'
--Proc_TA_get_level_Org_Updated 40,'533',40,'SuperAdmin'
--Proc_TA_get_level_Org_Updated 0,'533',0,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated]
(
	@para1 int	,
	@LevelIDs nvarchar(2000),
	@ParentID int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights] 
	(
		[LevelId] ASC
	) ON [PRIMARY]		
	SELECT id,name,ParentId from Ta_Tbl_levelDetails 
	inner join #LevelRights on #LevelRights.LevelId=Ta_Tbl_levelDetails.id 
	where isdeleted=0 order by id
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]
(
	@para1 int	,
	@LevelIDs nvarchar(2000)
)
AS
BEGIN
	SELECT id,name from Ta_Tbl_levelDetails where parentId=@para1  and isdeleted=0 order by Name
	--set @Query = 'SELECT id,name from Ta_Tbl_levelDetails where parentId=' + cast (@para1 as nvarchar(100)) + '  and isdeleted=0 and id in (' + @LevelIDs + ')  order by id '
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 16-9-2011
-- Description:	To Get the ReportingTo Employee Names
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select employee_id,Employee_FirstName + ' ' + Employee_LastName as Name from ta_tbl_employee where employee_id in (select distinct reporting_to from ta_tbl_employee where reporting_to is not null and reporting_to<>0)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 16-9-2011
-- Description:	To Get the Sanctioning EmployeeDetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select employee_id,Employee_FirstName + ' ' + Employee_LastName as Name from ta_tbl_employee where employee_id in (select distinct Leave_Sanc_Authority from ta_tbl_employee where reporting_to is not null and reporting_to<>0)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_get_Total_Level]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_Ta_get_Total_Level] 	
AS
BEGIN	
	--SELECT count(*) as tot from ta_tbl_level where parentLevelid<>0 group by parentLevelId
	select count(*)  as tot from ta_tbl_level where isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAccessDeniedSettingEntries]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Author                  : Kumuthini.L
-- Procedure Name  : Proc_TA_GetAccessDeniedSettingEntries
-- Tables Used         :TA_Tbl_AccessDeniedSettings
-- Created On           : 12-Mar-2008
CREATE PROCEDURE [dbo].[Proc_TA_GetAccessDeniedSettingEntries]
AS
BEGIN
    SELECT A.AccessDenied_Id,A.Terminal_ReaderID,(ISNULL(E.Employee_FirstName,'') + ' ' + ISNULL(E.Employee_LastName,'')) AS Employee_Name,A.AccessDeniedKey FROM TA_Tbl_AccessDeniedSettings A,TA_Tbl_Employee E WHERE A.Employee_Code_Id = E.Employee_Code_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveLanguageDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
Procedure Name	:	Proc_TA_GetActiveLanguageDetails
Description	:	Get Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	27-Jul-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetActiveLanguageDetails] 
as
select * from TA_Tbl_MultiLingual where IsActive=1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveYearSettingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_GetActiveYearSettingDetails
Description	:	Get year settings details
Tables Included	:	TA_Tbl_YearSetting
Created By	:	Prabakaran
Created On	:	30-Jul-07
Modified By	:
Modified On	:
*/
CREATE Procedure [dbo].[Proc_TA_GetActiveYearSettingDetails]
@IsActive bit
as
Select * from TA_Tbl_YearSetting where IsActive=@IsActive
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
	Procedure Name : Proc_TA_GetAdditionalWeekOffByLevel  
	Description : Get Additional WeekOff Details of Employees Based on their Level
	Tables Included : TA_Tbl_Additional_WeeklyOff, TA_Tbl_Employee 
	Created By : Kumuthini.L 
	Created On : 19-Feb-08  
	Modified By :  
	Modified On :  
*/  
 --Proc_TA_GetAdditionalWeekOffByLevel '30','03/10/2012' 
CREATE PROCEDURE [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]
(
   @EmpSwipeCardNo nVarchar(25),
   @Date nVarchar(15)
)
AS
SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW 
inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id
INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId
INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID
WHERE emp.SwipeCardNo = @EmpSwipeCardNo AND AW.IsDeleted = 0 AND 
EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,@Date, 102) order by EffectiveDate desc)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <23-Jan-2019 03:28 PM>
-- Description:	<Get Reporting to and Leave Sanctioning Person details of particular employee and which employees he is also the samething>
-- Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]
	@EmpAutoID varchar(50)=null
AS
BEGIN	
	SET NOCOUNT ON;
	Declare @EmployeeAutoID int
	set @EmployeeAutoID=@EmpAutoID;
	--Each person, whose is the reportingTo and Leave Sanctioning.
	--Particular employee whose is reproting To and leave sacntioning
	;with cte
	as
	(
		select AutoId=Employee_Id,Employee_Code_Id,Employee_FirstName as empName,Reporting_To as reportingToID,Leave_Sanc_Authority as leaveSanc 
		from TA_Tbl_Employee where (@EmployeeAutoID	IS NULL OR Employee_Id=@EmployeeAutoID)
	)
	select	EmployeeID=C.Employee_Code_Id,
			EmployeeName=C.empName,
			E1.Employee_Code_Id +' - '+ E1.Employee_FirstName 
			+ case when E1.EmailId IS not null and E1.EmailId<>'' then ' ('+ E1.EmailId +')' else '' end as ReportingTo_EmpName,
			E2.Employee_Code_Id +' - '+ E2.Employee_FirstName + case when E2.EmailId IS not null and E2.EmailId<>'' then ' ('+ E2.EmailId +')' else '' end as LeaveSanc_EmpName from cte C
	inner join TA_Tbl_Employee E1 on C.reportingToID=E1.Employee_Id
	inner join TA_Tbl_Employee E2 on C.leaveSanc=E2.Employee_Id

	--Which persons,this employee is reproting To and leave sacntioning
	--Declare @EmployeeAutoID int
	set @EmployeeAutoID=@EmpAutoID;
	;with cte
	as
	(
		select AutoId=Employee_Id,Employee_Code_Id,Employee_FirstName as empName,Reporting_To as reportingToID,Leave_Sanc_Authority as leaveSanc 
		from TA_Tbl_Employee where (@EmployeeAutoID	IS not NULL and Employee_Id=@EmployeeAutoID)
	)
	select ReportingTo=E1.Employee_Code_Id+' - '+ E1.Employee_FirstName+ case when E1.EmailId IS not null and E1.EmailId<>'' then ' ('+ E1.EmailId +')' else '' end,Sanctioning='' from cte C
	Left outer join TA_Tbl_Employee E1 on E1.Reporting_To=C.AutoId
	where E1.Employee_Id is not null
	union all
	select '',Sanctioning=E2.Employee_Code_Id+' - '+E2.Employee_FirstName + case when E2.EmailId IS not null and E2.EmailId<>'' then ' ('+ E2.EmailId +')' else '' end from cte C
	Left outer join TA_Tbl_Employee E2 on E2.Leave_Sanc_Authority=C.AutoId
	where E2.Employee_Id is not null
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getAllNews]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		SENTHIL
-- ALTER  date: 15-Aug-07
-- Description:	Selecting News
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getAllNews]
   @userGroupName nvarchar(50)
AS	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END	
if(@userGroupName='SuperAdmin')
	begin  
		select NewsEvent_Id, 
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventFromDate,@dateFormat),' ','-') 
		else CONVERT(VARCHAR, NewsEventFromDate, @dateFormat) end	
		as NewsEventFromDate,
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventToDate,@dateFormat),' ','-') 
		else CONVERT(VARCHAR, NewsEventToDate, @dateFormat) end	
		as NewsEventToDate,
		NewsEventTitle	= (Case NewsEventTitle When '' then 'Banner' When NULL then 'Banner' else NewsEventTitle End),NewsEventDescription, IsDeleted from ta_tbl_newsEvents order by TimeStamp desc
	END
else
	begin  
        select NewsEvent_Id,case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventFromDate,@dateFormat),' ','-') 
		else CONVERT(VARCHAR, NewsEventFromDate, @dateFormat) end	
		as NewsEventFromDate,
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventToDate,@dateFormat),' ','-') 
		else CONVERT(VARCHAR, NewsEventToDate, @dateFormat) end	as NewsEventToDate,
        NewsEventTitle	= (Case NewsEventTitle When '' then 'Banner' When NULL then 'Banner' else NewsEventTitle End),
		NewsEventDescription, IsDeleted from ta_tbl_newsEvents where isdeleted=0 order by TimeStamp desc
  END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetAllShift] 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	select * from ta_tbl_shift where Isdeleted=0 and cast(CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112)  + ' ' + CONVERT(CHAR(8), Shift_StartTime, 108)) as datetime) between DATEADD(MINUTE,-10,getdate()) and DATEADD(MINUTE,10,getdate())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllShiftPatterns]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/* Abul: Gets all the shift patterns */
CREATE Proc [dbo].[Proc_TA_GetAllShiftPatterns]
As
select * from TA_Tbl_ShiftPattern
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetApprovalAuthority]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_GetApprovalAuthority
Description		:	Get First and Second Level Authority Ids by passing the Applicant Id
Tables Included		:	TA_TBL_Employee
Created By		:	Kumuthini
Created On		:	06-Apr-2009
Modified By		:	Kumuthini
Modified On		:	07-Apr-2009
-- Proc_TA_GetApprovalAuthority 5
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetApprovalAuthority] 
(
	@Applicant_Id int
)
AS
BEGIN
	SELECT R.Employee_FirstName AS ReportingToEmployee,E.Reporting_To,S.Employee_FirstName AS SanctioningEmployee,E.Leave_Sanc_Authority 
	FROM TA_Tbl_Employee E  
	LEFT OUTER JOIN TA_Tbl_Employee R ON R.Employee_Id = E.Reporting_To
	LEFT OUTER JOIN TA_Tbl_Employee S ON S.Employee_Id = E.Leave_Sanc_Authority
	WHERE E.Employee_Id = @Applicant_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetApprovalStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:           <R.Manikandan>
-- Create date: <26-04-2017,10.23 AM,>
-- Description:      <Get the Approval Status for each Transaction>
-- We got some issue in onduty screen due to that we changed this procedue coding on 30-12-2019 06:02 PM by Manikandan.rr
-- Proc_Ta_GetApprovalStatus 1,3,0
-- Mobile app will not worked if WHERE Employee_Id=@EmpCodeID and Isdeleted=0
-- if you change Employee_Id means, application will not work. verified on 06Feb2020 05:35 PM
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetApprovalStatus]
       @EmpAutoId bigint,
       @EmpCodeID varchar(20),
       @ReportBasedOn bit
AS
BEGIN
	SET NOCOUNT ON;
	Declare @ReportingTo varchar(50)
	Declare @SanctioningAuthority varchar(50)
	Declare @Status varchar(20)
	set @Status =''
	Declare @EnteredEmployeeAutoID varchar(20)
	Declare @UserGroup_Id varchar(50)
	Declare @UserGroup_Name varchar(50)
	select @UserGroup_Id=UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId and Isdeleted=0
	select @UserGroup_Name=groupName from ta_tbl_usergroup where groupId=@UserGroup_Id
	SELECT @ReportingTo=Reporting_To,@SanctioningAuthority=Leave_Sanc_Authority,@EnteredEmployeeAutoID=Employee_Id from TA_Tbl_Employee
	WHERE Employee_Id=@EmpCodeID and Isdeleted=0
	--select @ReportingTo,@SanctioningAuthority
	IF(@EmpAutoId=@ReportingTo and @EmpAutoId=@SanctioningAuthority)
	BEGIN
		SET @Status='Approved'
	END
	ELSE IF(@EmpAutoId=@SanctioningAuthority)
	BEGIN
		SET @Status='Approved'
	END
	ELSE IF(@EmpAutoId=@ReportingTo)
	BEGIN
		SET @Status='Forwarded'
	END
	ELSE
	BEGIN
		IF (@UserGroup_Name!='Superadmin')
		begin
			IF(@EmpAutoId!=@EnteredEmployeeAutoID)
			BEGIN
				IF(@ReportBasedOn=0 OR @ReportBasedOn=1)
				BEGIN
					IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
					BEGIN
						SET @Status='Forwarded'
					END
					Else
					BEGIN
						SET @Status='Pending'
					END
				END				
			END
			--this part added newly by Manikandan.RR on 30-12-2019 06:02 PM
			ELSE
			BEGIN
				IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
				BEGIN
					SET @Status='Forwarded'
				END
				Else
				BEGIN
					SET @Status='Pending'
				END
			END
		END
		ELSE
		BEGIN
			IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
			BEGIN
				SET @Status='Forwarded'
			END
			Else
			BEGIN
				SET @Status='Pending'
			END
		END
	END
	select @Status as Status
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAttendanceData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_GetAttendanceData]   
 -- Add the parameters for the stored procedure here  
 @AttendanceDate datetime  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
 select TA_Tbl_Employee.Employee_Code_id as 'Employee Code',Employee_FirstName as 'Employee Name',InTime as 'In Time',OutTime as 'Out Time',HrsWork as  'No of Hours',HrsOt as 'No of OT Hours'  
from ta_tbl_processeddata INNER JOIN   
TA_Tbl_Employee on TA_Tbl_Employee.SwipeCardNo=ta_tbl_processeddata.Employee_Code_id  
where ta_tbl_processeddata.Date=@AttendanceDate  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetails]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if Exists(SELECT ShiftSettingId FROM TA_Tbl_ShiftSettings WHERE CompanyId = @CompanyId)
		begin
			SELECT ShiftSettingId,HolidayOT,WeekOffOT,otOption,IsFlexible,FlexibleFlag,HalfDayAttendance,OTRoundoffEnable,DefaultMonthClosureDate as MonthClosure_EndDate FROM TA_Tbl_ShiftSettings WHERE CompanyId = @CompanyId
		end
	else
		begin
			SELECT ShiftSettingId,HolidayOT,WeekOffOT,otOption,IsFlexible,FlexibleFlag,HalfDayAttendance,OTRoundoffEnable,DefaultMonthClosureDate as MonthClosure_EndDate FROM TA_Tbl_ShiftSettings WHERE CompanyId = -1
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	To get the shift settings details by using company id
-- Proc_Ta_GetBasicShiftSettingDetailsForService 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]
	@COMPANYID INT
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		BEGIN TRANSACTION
		IF EXISTS(SELECT SHIFTSETTINGID FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID)
		BEGIN			
			SET @COMPANYID=@COMPANYID
		END	
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT SHIFTSETTINGID FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = -1)
				BEGIN
					INSERT INTO TA_Tbl_ShiftSettings([CompanyId],[MaxHoursBeforeShift],[MaxHoursAfterShift],[ShiftBreak],[ShiftMaxBreakHours],	 
					[MonthlyWorkingHours],[WeeklyWorkingHours],[EmpID],[HolidayOT],[WeekOffOT],[otOption],[DefaultMonthClosureDate],[IsFlexible],
					[FlexibleFlag],[OTRoundoffEnable],[FullDayAttendanceHrs],[HalfDayAttendanceHrs],[HalfDayAttendance],[FullDayAttendance],
					[WeeklyOffStartHours],[IgnoreDuplicatePunch],[PunchInterval],[AfterShiftTime],[BeforeShiftTime],[DefinedWorkhrs],
					[NoOfSuccessiveDaysInYear],[CompensationValitityDays],[VaildityCompOffDays],[HalfDayCompOff],[FullDayCompOff],
					[LateEntry],[EarlyEntry],[EarlyExit],[LateExit])
					VALUES(-1,'02:00','02:00','','','','','1','1','1','WeeklyOff',
					DATEADD(MONTH,DATEDIFF(MONTH,0,dateadd(month,-1,GETDATE())),-1)
					,'0','0','0','','','1','1','16:00','1','00:10','1','1','1',30,'0',90,'11:00','12:00','1','1','1','1')
				END						
			SET @COMPANYID=-1
		END
		SELECT	SHIFTSETTINGID,COMPANYID,MAXHOURSBEFORESHIFT,MAXHOURSAFTERSHIFT,SHIFTBREAK,SHIFTMAXBREAKHOURS, 
				MONTHLYWORKINGHOURS,WEEKLYWORKINGHOURS,EMPID,HOLIDAYOT, 
				WEEKOFFOT,OTOPTION,CONVERT(VARCHAR(25),DEFAULTMONTHCLOSUREDATE,120) AS MONTHCLOSURE_ENDDATE, 
				ISFLEXIBLE,FLEXIBLEFLAG,OTROUNDOFFENABLE,FULLDAYATTENDANCEHRS, 
				HALFDAYATTENDANCEHRS,HALFDAYATTENDANCE,FULLDAYATTENDANCE, WEEKLYOFFSTARTHOURS, 
				IGNOREDUPLICATEPUNCH,PUNCHINTERVAL,AFTERSHIFTTIME,BEFORESHIFTTIME, 
				DEFINEDWORKHRS,NOOFSUCCESSIVEDAYSINYEAR,COMPENSATIONVALITITYDAYS,VAILDITYCOMPOFFDAYS, 
				HALFDAYCOMPOFF, FULLDAYCOMPOFF,LATEENTRY,EARLYENTRY, 
				EARLYEXIT,LATEEXIT, TIMESTAMP,TIMESTAMP1, 
				ISLUNCHDEDUCTION,LUNCHDEDUCTIONHOURS,FLEXI_AFTERSHIFTTIME,FLEXI_BEFORESHIFTTIME,FLEXI_DEFINEDWORKHRS
		FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID= @COMPANYID			
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBlockedEmployeedetailsForMailSend]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetBlockedEmployeedetailsForMailSend]
	@tag nvarchar(100),
	@AutoID bigint=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@tag='SM')
		begin
			Select * from ta_tbl_BlockedEmployeeLogs where isMailSent=0
		end
	else if(@tag='U')
		begin
			update ta_tbl_BlockedEmployeeLogs  set isMailSent=1, SentDatetime=GETDATE() where AutoID=@AutoID
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetBrandDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 10-Nov-2010
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetBrandDetails]		
AS
BEGIN
	set nocount on
    select DisplayName,KeyValue from TA_Tbl_TerminalBrand	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Designation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the Designation based on the organization for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroup_Designation] 
@LevelID int
AS
BEGIN
	SET NOCOUNT ON;
    select distinct TitleId as DesignationId,TitleName as DesignationName from TA_Tbl_title T
    inner join  TA_Tbl_EmployeeDesignation ED on ED.DesignationId=T.TitleId
    inner join  TA_tbl_EmployeeLevel EL on EL.EmployeeID=ED.EmployeeID
    where EL.LevelID=@LevelID and T.IsDeleted=0 order by TitleName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Details]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Fetches the Organization,Designation and UserGroup details for CC mail group.
-- =============================================
--exec Proc_TA_GetCCGroup_Details
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroup_Details] 
@UserGroupName varchar(250),
@LevelRights varchar(8000)
AS
BEGIN
	SET NOCOUNT ON;
    --Added by Gopinath on 9th MAy 2014 for loading organization details and session Level issues
    SELECT @LevelRights=COALESCE(@LevelRights+',','')+LevelId FROM TA_Tbl_LevelRights L
	inner join TA_Tbl_Usergroup U on L.GroupId=U.groupId
	where U.groupName=@UserGroupName
    declare @Script varchar(8000)
    set @Script=''
    set @Script=@Script + 'select Id as CompanyId,name as CompanyName from TA_tbl_LevelDetails 
    where IsDeleted=0 and Id in (select distinct LevelId from TA_Tbl_EmployeeLevel where LevelId in ('+@LevelRights+')) order by name'
    exec(@Script)
    --select TitleId as DesignationId,TitleName as DesignationName from TA_Tbl_title where TitleId in (select distinct DesignationId from TA_Tbl_EmployeeDesignation)
    select groupId as UserGroupId,groupname as UserGroupName from Ta_tbl_Usergroup where isDeleted=0 order by groupname
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroupById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the Designation based on the organization for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroupById] 
@CCGroupID int
AS
BEGIN
	 SET NOCOUNT ON;
    select * from TA_tbl_CcMailGroup where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_Planned where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_UnPlanned where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_Others where CcGroupId=@CCGroupID
	select * from TA_Tbl_CCGroup_ODApproval where CcGroupId=@CCGroupID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Proc_TA_getChildLevelDetails]
(
	@levelId int,
	@UserGroupName nVarchar(250)
)
as
Begin
	IF(@UserGroupName = 'SuperAdmin')
		BEGIN
			select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId, b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId
		End
	Else
		Begin
			select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
		End
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsForSearch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_getChildLevelDetailsForSearch 1,0,'SuperAdmin','10'
CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsForSearch]
(
      @levelId int='',
      @ParentLevelId int='',
      @UserGroupName nVarchar(250)='',
      @UserLevelId nvarchar(4000)=''
)
as
Begin
      create table #LevelRights(LevelId int)
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId
      declare @Query as varchar(8000)           
      IF(@ParentLevelId!=0)
            BEGIN
                  IF(@UserGroupName = 'SuperAdmin')
                        BEGIN
                              select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId,case when b.IsDeleted=1 then 'True' else 'False' end IsDeleted 
                              from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid 
                              where a.levelid=@levelId and b.parentId=@ParentLevelId and b.id is not null order by childLevelName
                        End
                  Else
                        Begin
                              --select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
                              if (@UserLevelId='' or @userLevelId is null)
                                    begin 
                                          set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.parentId=' + cast (@ParentLevelId as nvarchar(20)) + ' and b.Isdeleted=0 and b.id is not null order by childLevelName' 
                                          --and b.id in (' + @UserLevelId + ')'
                                    End
                              else
                                    begin
                                          set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 and b.id in (' + @UserLevelId + ') and b.id is not null order by childLevelName'
                                    End
                        End   
            END
      ELSE
            BEGIN
                  IF(@UserGroupName = 'SuperAdmin')
                        BEGIN
                              select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId,case when b.IsDeleted=1 then 'True' else 'False' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.id is not null order by childLevelName
                        End
                  Else
                        Begin
                              if (@UserLevelId='' or @userLevelId is null)
                                    begin 
                                          set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 and b.id is not null order by childLevelName' 
                                          --and b.id in (' + @UserLevelId + ')'
                                    End
                              else
                                    begin
                                          set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 and b.id is not null order by childLevelName'
                                    End
                        End
            END         
      exec(@Query)
      drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsUpdated]
(
	@levelId int='',
	@UserGroupName nVarchar(250)='',
	@UserLevelId nvarchar(4000)='',
	@ParentId int
)
as
Begin
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(7000)
	--IF(@UserGroupName = 'SuperAdmin')
	--	BEGIN
	--		select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId, b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId order by childLevelName
	--	End
	--Else
	--	Begin
	--		--select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
	--if (@UserLevelId='' or @userLevelId is null)
	--		begin 
	--			set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 order by childLevelName' 
	--				--and b.id in (' + @UserLevelId + ')'
	--		End
	--else
	--	begin
			--set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 and b.id in (' + @UserLevelId + ') order by childLevelName'
			set @Query = 'select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted,b.TimezoneId from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid=' + cast (@levelId as nvarchar(20)) + ' and b.Isdeleted=0 order by childLevelName'
		--End
exec(@Query)
drop table #LevelRights
		--End
End


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevels]
(
	@levelId int
)
as
BEGIN
	--select a.id,a.levelid,a.name,b.name as childLevelName,b.parentId,b.levelid as childId,b.description from ta_tbl_leveldetails a inner join ta_tbl_leveldetails b  on b.parentid=a.levelid where b.parentid=@levelId 
  	select * from ta_tbl_leveldetails where parentid=@levelId and isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetChildMenu]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <08-06-2016>
-- Description:	<Getting child menus for usergroup>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetChildMenu]
	-- Add the parameters for the stored procedure here
	@pageid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	create table #temppage(id int identity(1,1),pageid int,displayName varchar(200),parentid int)
	create table #tempResult(id int identity(1,1),pageid int,displayName varchar(200),parentid int)
	insert into #temppage 
	select pageId,displayname+'_Title',parentId from TA_Tbl_Page where parentId=@pageid	order by orderBy
	Declare @Count int
	Declare @i int
	Declare @parentid int
	set @Count=(select COUNT(*)from #temppage)
	set @i=1
	while @i<=@Count
	begin
		insert into #tempResult
		select pageId,displayName,parentId from #temppage where id=@i
		set @parentid=(select pageid from #temppage where id=@i)
		insert into #tempResult
		select pageId,displayname+'_Title',parentId from TA_Tbl_Page where parentId=@parentid order by orderBy
		set @i=@i+1
	end	
	select *,case when pageId IN(205,42,84,192,144,145,147,118,41,30,40,45,39,105,180,183,127,37,34,43,79,160,171,232,233,234,36,175,219,70,71,208,44,32,
	211,89,117,35,213,33,92,103,116) then 1 else 0 end 'ReportMenus' from #tempResult order by id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Created By	: Prabakaran.P
Created On	: 5-Mar-09
Description	: Store the child Levels for the Company, For Data Process Service
Modified By		:	Manjula.P
Modified On		:	05-Feb-2014
Descriptions	:	Issue : in Dataprocess service there is no process if the employee is under parent id directly
				:	Adding this line by Manjula.P on 05-Feb-2014 for inserting passing parent levelid into Ta_Tbl_DataProcessCompanyLevelTemp for process 
					INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
Proc_Ta_GetChildrenLevels 1
select *  from Ta_Tbl_DataProcessCompanyLevelTemp
delete from Ta_Tbl_DataProcessCompanyLevelTemp
*/
CREATE PROCEDURE [dbo].[Proc_Ta_GetChildrenLevels]
(
	@ParentID int
) 
AS
Begin
	SET NOCOUNT ON
	DELETE FROM Ta_Tbl_DataProcessCompanyLevelTemp
	INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	---------------------------------------------------------------------------------------------------
	--DECLARE @NextLevel int, @Counter int, @PostKey varchar(200)
	--SET @Counter = 1
	---- Build a cursor to loop through all the kids of this post
	--DECLARE c1 CURSOR LOCAL FOR 
	--SELECT [ID] FROM ta_tbl_leveldetails WHERE ParentID = @ParentID and IsDeleted=0 Order by [ID] ASC
	--Declare @LevelIds as int
	--set @LevelIds=(select count(LevelId) from Ta_Tbl_DataProcessCompanyLevelTemp where LevelId=@ParentID)
	--if(@LevelIds=0)
	--	begin
	--		INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	--	end
	--OPEN c1
	--FETCH NEXT FROM c1
	--INTO @ParentID
	--WHILE @@FETCH_STATUS = 0
	--	BEGIN
	--		-- Put this record in the temp table
	--		INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	--		-- Process all the children for this post
	--		EXEC Proc_Ta_GetChildrenLevels @ParentID
	--		SET @Counter = @Counter + 1
	--		-- And get the next record at this level
	--		FETCH NEXT FROM c1 INTO @ParentID 
	--	END
	--CLOSE c1
	--DEALLOCATE c1	
	;WITH ChildLevelDetails as
	(
		select id as parentAutoid,name FROM ta_tbl_leveldetails WHERE ParentID = @ParentID and IsDeleted=0
		UNION ALL
		select ld.id,ld.name FROM ta_tbl_leveldetails ld
		INNER JOIN ChildLevelDetails CL ON CL.parentAutoid = ld.parentId
	)
	Insert into Ta_Tbl_DataProcessCompanyLevelTemp
	SELECT parentAutoid From ChildLevelDetails
	--SELECT * FROM Ta_Tbl_DataProcessCompanyLevelTemp
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevelsCollectData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 /*  
Created By : Prabakaran.P  
Created On : 5-Mar-09  
Description : Store the child Levels for the Company, For Data Process Service  
Proc_Ta_GetChildrenLevelsCollectData  1  
select *  from Ta_Tbl_CollectRawDataCompanyLevelTemp  
delete from Ta_Tbl_CollectRawDataCompanyLevelTemp  
*/    
CREATE PROCEDURE [dbo].[Proc_Ta_GetChildrenLevelsCollectData] 
(@ParentID int) AS  
SET NOCOUNT ON  
DECLARE @NextLevel int, @Counter int, @PostKey varchar(200)  
SET @Counter = 1  
-- Build a cursor to loop through all the kids of this post  
DECLARE c1 CURSOR LOCAL FOR  
SELECT [ID]   
FROM ta_tbl_leveldetails  
WHERE ParentID = @ParentID and IsDeleted=0  
Order by [ID] ASC  
Declare @LevelIds as int  
set @LevelIds=(select count(LevelId) from Ta_Tbl_CollectRawDataCompanyLevelTemp where LevelId=@ParentID)  
if(@LevelIds=0)  
begin  
INSERT Ta_Tbl_CollectRawDataCompanyLevelTemp (LevelId) VALUES (@ParentID)  
end  
OPEN c1  
FETCH NEXT FROM c1  
INTO @ParentID  
WHILE @@FETCH_STATUS = 0  
BEGIN  
  -- Put this record in the temp table  
  INSERT Ta_Tbl_CollectRawDataCompanyLevelTemp (LevelId) VALUES (@ParentID)  
  -- Process all the children for this post  
  EXEC Proc_Ta_GetChildrenLevelsCollectData @ParentID  
  SET @Counter = @Counter + 1  
  -- And get the next record at this level  
  FETCH NEXT FROM c1  
  INTO @ParentID   
END  
CLOSE c1  
DEALLOCATE c1  
SET NOCOUNT OFF  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCityDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCityDetails]
	@ID int,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if @Type='C'
		Begin
			SELECT L.Title AS city,L.Parent AS stateID	FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3 and l.ID =@ID
		end
	Else if @Type='N'
		begin			
			SELECT L.Title AS country FROM TA_Tbl_Lookup L WHERE L.Type=1 and l.ID =@ID	
		end
	Else if @Type='S'
		begin			
			SELECT L.Title AS state,L.Parent AS countryID FROM TA_Tbl_Lookup L INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2 and l.ID =@ID	
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


---------------------------------------------------------------------------------------------
-- AutoShift Updated Script 

CREATE PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]
	@SwipeCardNo varchar(max),
	@inClk_Date datetime,
	@inClk_Time varchar(20),
	@CompanyId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DateOfJoining datetime
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	DECLARE @SHIFTID INT
	Declare @PrevEndtime  Datetime	
	set @SHIFTID =0
	CREATE TABLE #TEMP (SHIFTID INT)
	Declare @flag char(1)
	set @flag='F'
	Select @DateOfJoining = DateOfJoining,@EMPLOYEEAUTOID =Employee_Id from TA_Tbl_Employee where SwipeCardNo =  @SwipeCardNo and Isdeleted=0
	if(@inClk_Date > @DateOfJoining)
	Begin
		Declare @PrevDay datetime
		Declare @PrevSatrtTime datetime
		DECLARE @QUERY VARCHAR(2000)
		Declare @WeekoffHours varchar(20)
		SET @SHIFTID=0
		SET  @PrevDay = DATEADD(d, -1, @inClk_Date)
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)
		Declare @MaxHoursAfterShift Nvarchar(100)
		select @WeekoffHours = WeeklyOffStartHours,@MaxHoursAfterShift=MaxHoursAfterShift from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
		
		
		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
		SET @QUERY = '	SELECT (TSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
						WHERE TSA.[YEAR]= ' + @YEAR + '  AND  TSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = '''+ @EMPLOYEEAUTOID +''' '	
		print @QUERY
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID,0)
		DELETE FROM #TEMP
		Declare @WeekOffcount  int
		set @WeekOffcount=1
		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
		IF(@SHIFTID = 0)
			BEGIN
				
				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				print @SHIFTID
				DELETE FROM #TEMP				
			END	
		--Check Starttime and End time for weeklyoff--
		if(@SHIFTID=-1)
		begin
			Declare @i int
			Declare @PreviousOneMoreDay datetime
			SET  @PreviousOneMoreDay = DATEADD(d,-1, @PrevDay)
			set @i=1
			while @i>0
			begin				
				  --dec 18 shift 5
				SET @QUERY = ' SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(DAY,@PreviousOneMoreDay)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA
					WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + CONVERT(VARCHAR(10),DATEPART(DAY,@PreviousOneMoreDay)) + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP
				set @WeekOffcount=@WeekOffcount+1
				if(@SHIFTID!=-1)
				begin
					set @i=-1
					break
				end				
				set @PreviousOneMoreDay=dateadd(d,-1,@PreviousOneMoreDay)
				set @i=@i+1	
			end
			if(@SHIFTID!=-1)
			begin
				Declare @Start int
				set @Start=1
				Declare @MaxShiftWorkHours datetime
				Declare @Shift_StartTime datetime
				select @Shift_StartTime=convert(datetime,Shift_StartTime),@MaxShiftWorkHours=convert(datetime,MaxShiftWorkHours)
				from TA_Tbl_Shift where Shift_Id = @SHIFTID			
				set @PrevSatrtTime= @PreviousOneMoreDay+@Shift_StartTime
				while @WeekOffcount>=@Start
				begin
					if(@Start=1)
					begin					
						set @PrevEndtime=@PrevSatrtTime+@WeekoffHours					
					end
					else
					begin
						set @PrevSatrtTime=DATEADD(minute,1,@PrevEndtime)
						set @PrevEndtime=@PrevEndtime+@WeekoffHours
					end
					--select @PrevSatrtTime,@PrevEndtime
					set @Start=@Start+1
				end			
		   End 		  
		end
		else if(@SHIFTID=0) --leave , lop days for auto shift configured employee
		begin
				IF EXISTS(select FNAttendanceCode from TA_Tbl_ProcessedData where Date = @PrevDay and Employee_Code_Id=@SwipeCardNo
				and FNAttendanceCode not in ('Present', 'Weekly Off', 'Holiday')
				and ANAttendanceCode not in ('Present', 'Weekly Off', 'Holiday'))
				Begin
					select @PrevDay = @inClk_Date
					select @PrevDay
					set @day =DATEPART(DAY,@PrevDay)
					SET @YEAR=DATEPART(YEAR,@PrevDay)
					SET @MONTH=DATEPART(MONTH,@PrevDay)	
					SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
									WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
					INSERT INTO #TEMP EXEC(@QUERY)
					SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
					DELETE FROM #TEMP
					if(@SHIFTID=-1) --for weeklyoff
					begin
						set @SHIFTID=0;
					end
					if(@SHIFTID=0)
					begin
						set @flag='T'
						goto GetShift;
					end
					goto UpdateShift_Permanent;
				End				
		end
		else
		begin
			select @PrevSatrtTime = @PrevDay+convert(datetime,Shift_StartTime),
			@PrevEndtime= @PrevDay+convert(datetime,Shift_EndTime)+convert(datetime,MaxShiftWorkHours)
			from TA_Tbl_Shift where Shift_Id = @SHIFTID
			
		end
		--For Night shift Add one day for the end date
		if(@PrevSatrtTime>=@PrevEndtime)
			begin
				set @PrevEndtime=dateadd(DAY,1,@PrevEndtime)
				
				set @PrevEndtime=DATEADD(MINUTE,dbo.[ConvertHoursToMinites](@MaxHoursAfterShift),@PrevEndtime)
				
			end
		--select @PrevSatrtTime,@PrevEndtime
		IF(@inClk_Date+@inClk_Time between @PrevSatrtTime and @PrevEndtime)
		BEGIN
			if(@WeekOffcount>1)
			begin
				SELECT @PrevDay=dateadd(d,-(@WeekOffcount-1),@inClk_Date)
				set @SHIFTID=-1
				SELECT @PrevDay
			end
			else
			begin
				SELECT @PrevDay
			end
		END
		ELSE
		BEGIN
			--1.31 pm AND OUT CAME ON THE SAME DAY.	
			--Aug 1 9:30 pm to Aug 2 07:00 am	Shift name 930
			--Aug 2 03:00 pm to Aug 2 09:30 pm  Shift name 3pm
			--Aug 3 weeklyoff but still he came for work means Initial shift Id = -1
			-- Aug 3 07am Aug 3 03:00pm so new shift id will be allocated through autoshift shifts.
			select @PrevDay = @inClk_Date
			select @PrevDay
			set @SHIFTID=0;
			set @day =DATEPART(DAY,@PrevDay)
			SET @YEAR=DATEPART(YEAR,@PrevDay)
			SET @MONTH=DATEPART(MONTH,@PrevDay)	
			IF(@SHIFTID = 0)  -- It runs for current day , whatever shift id updated in permenent shift table will be taken here. If shift id not present, new shift id wil be find out
			BEGIN
				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
			set @flag='T'
			goto GetShift;
			goto UpdateShift_Permanent;
		End		
	End	
	Else	
	Begin
		select @PrevDay = @inClk_Date
		select @PrevDay
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
						WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID ,0)
		DELETE FROM #TEMP
		if(@SHIFTID=-1)
		begin
			set @SHIFTID=0;
		end
		if(@SHIFTID=0)
		begin
			set @flag='T'
			goto GetShift;
		end
		goto UpdateShift_Permanent;
	End
	GetShift:
	begin
		--set @SHIFTID=0
		if(@flag='T')
		begin
			IF(@inClk_Time !='00:00' and @SHIFTID = 0 and @SHIFTID != -1)
			BEGIN
				Declare @Count int
				set @Count=0;
				Create Table #TempAutoShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40));
				Create Table #TempAutoShiftSingleShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40), shiftstartTime varchar(40), minutesdiffStart bigint, orderby int);
				insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId1,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId1 !=0
				insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId2,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId2 !=0
				insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId3,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId3 !=0
				insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId4,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId4 !=0
				insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId5,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId5 !=0	
				select @Count = isnull(count(EmpId),0)from #TempAutoShift				
				IF(@Count = 1)
				BEGIN
					select @SHIFTID = ISNULL(ShiftId,0)	from #TempAutoShift							
				END
				--ELSE IF(@Count = 0)
				--BEGIN
				--	set @SHIFTID = 0						
				--END
				ELSE
				BEGIN
					insert into #TempAutoShiftSingleShift
					select b.EmpId,b.ShiftId,b.clkDate, b.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
					RANK()over(order by diff) from
					(
						select a.EmpId,a.ShiftId,a.clkDate, a.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
						case when datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)<0 then -datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)
						else datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime) end as diff
						from #TempAutoShift a
						inner join TA_Tbl_Shift b on b.Shift_Id = a.ShiftId
					)as b		
					declare @loopcount int
					Declare @ShiftNewtime datetime
					set @loopcount = 1
					while (@loopcount <= 5)
					Begin		
							select @ShiftNewtime = clkDate+shiftstartTime from #TempAutoShiftSingleShift  where orderby=@loopcount	
							if(@ShiftNewtime < @PrevEndtime)
							Begin
								set @loopcount = @loopcount + 1;													
							End			
							else
							begin
								select @SHIFTID = ShiftId from #TempAutoShiftSingleShift  where orderby=@loopcount	
								break;					
							End			
					End								
				END
				set @flag='T'
				DROP TABLE #TempAutoShiftSingleShift
				DROP TABLE #TempAutoShift
			END
			ELSE
			BEGIN
				-- if employee forgot to mark clock in time and manual entry got entered for that entry means, the shift id is not updating	properly.
				--Client need to reprocess the logs once again.Implemented on 10-mar-2020. 05:54 pm			
				IF NOT EXISTS(SELECT Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId=@SwipeCardNo and
				Clk_Date+Clk_InTime<@inClk_Date+@inClk_Time and Clk_Date=@inClk_Date)
				BEGIN
					--select 1
					set @SHIFTID=0;
					set @flag='T'
					goto GetShift;
				END				
			END
		end
	end	
	UpdateShift_Permanent:
	Begin
		if(@flag='T')
		begin
			DECLARE @DynamicQuery VARCHAR(MAX)
			SELECT @year=DATEPART(YEAR,@PrevDay),@month=DATEPART(MONTH,@PrevDay),@day=DATEPART(DAY,@PrevDay) 	
			SET @DynamicQuery =''
			--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
			IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID)
			Begin
				if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EMPLOYEEAUTOID)
				begin
					SET @DynamicQuery =@DynamicQuery +'update TA_Tbl_PermanentShiftAllocation set day'+CONVERT(VARCHAR(2),@day)+'shift='+CONVERT(VARCHAR(2),@SHIFTID)+ ' where
					month='+CONVERT(VARCHAR(2),@month)+' and year='+CONVERT(VARCHAR(4),@year)+' and employeeid='+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)
				end
				else
				begin
					SET @DynamicQuery =@DynamicQuery +'insert into TA_Tbl_PermanentShiftAllocation (day'+CONVERT(VARCHAR(2),@day)+'shift,month,year,employeeid,Emp_id,dateshift)
					values('+CONVERT(VARCHAR(2),@SHIFTID)+ ','+CONVERT(VARCHAR(2),@month)+','+CONVERT(VARCHAR(4),@year)+','+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)+',1,'''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+''')'
				end
				exec (@DynamicQuery)
			End
		end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <Aug 16 2019,,>
-- Description:	<This procedure works for getclock date for auto shift in 1 weeklyoff scenario>
-- ============================================
--Aug 2 -- 9 30 pm
--Aug 3 -- 07 20 am
-- Proc_TA_GetClockDateForAutoShiftEmployee '1001','2019-08-01 00:00:00.000','11:30:00','1'


CREATE PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]
	@SwipeCardNo varchar(max), 
	@inClk_Date datetime, 
	@inClk_Time varchar(20),
	@CompanyId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DateOfJoining datetime
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	DECLARE @SHIFTID INT
	Declare @PrevEndtime  Datetime	
	set @SHIFTID =0
	CREATE TABLE #TEMP (SHIFTID INT)
	Select @DateOfJoining = DateOfJoining,@EMPLOYEEAUTOID =Employee_Id from TA_Tbl_Employee where SwipeCardNo =  @SwipeCardNo and Isdeleted=0
	if(@inClk_Date > @DateOfJoining)
	Begin
		Declare @PrevDay datetime
		Declare @PrevSatrtTime datetime
			
		DECLARE @QUERY VARCHAR(2000)   
		Declare @WeekoffHours varchar(20)
		
		SET @SHIFTID=0
			
		SET  @PrevDay = DATEADD(d, -1, @inClk_Date)
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		select @WeekoffHours = WeeklyOffStartHours from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
		
		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
		SET @QUERY = '	SELECT (TSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
						WHERE TSA.[YEAR]= ' + @YEAR + '  AND  TSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = '''+ @EMPLOYEEAUTOID +''' '	
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID,0) 
		DELETE FROM #TEMP
		
		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
		IF(@SHIFTID = 0)
			BEGIN
				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
		--Check Starttime and End time for weeklyoff--
		if(@SHIFTID=-1)
		begin
			SET  @PrevDay = DATEADD(d, -2, @inClk_Date)
			SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)
			DELETE FROM #TEMP	
			select @PrevEndtime= @PrevDay+convert(datetime,Shift_StartTime)+convert(datetime,MaxShiftWorkHours) 
			from TA_Tbl_Shift where Shift_Id = @SHIFTID
			set	@PrevSatrtTime=dateadd(minute,1,@PrevEndtime)
			set @PrevEndtime=@PrevSatrtTime+convert(datetime,@WeekoffHours)  -- weeklyoff hours defined in shift setting need to be added.
		end
		else if(@SHIFTID=0) --leave , lop days for auto shift configured employee
		begin
				IF EXISTS(select FNAttendanceCode from TA_Tbl_ProcessedData where Date = @PrevDay and Employee_Code_Id=@SwipeCardNo
				and FNAttendanceCode not in ('Present', 'Weekly Off', 'Holiday')
				and ANAttendanceCode not in ('Present', 'Weekly Off', 'Holiday'))
				Begin
					select @PrevDay = @inClk_Date
					select @PrevDay
					
					set @day =DATEPART(DAY,@PrevDay)
					SET @YEAR=DATEPART(YEAR,@PrevDay)
					SET @MONTH=DATEPART(MONTH,@PrevDay)	
					SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
									WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
					INSERT INTO #TEMP EXEC(@QUERY)
					SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
					DELETE FROM #TEMP
					if(@SHIFTID=-1) --for weeklyoff
					begin
						set @SHIFTID=0;
					end
					if(@SHIFTID=0)
					begin
						goto GetShift;
					end
					goto UpdateShift_Permanent;
				End				
		end
		else
		begin
			select @PrevSatrtTime = @PrevDay+convert(datetime,Shift_StartTime), 
			@PrevEndtime= @PrevDay+convert(datetime,Shift_StartTime)+convert(datetime,MaxShiftWorkHours) 
			from TA_Tbl_Shift where Shift_Id = @SHIFTID


		end
		
		--select @PrevSatrtTime,@PrevEndtime
		IF(@inClk_Date+@inClk_Time between @PrevSatrtTime and @PrevEndtime)
		BEGIN
			SELECT @PrevDay
		END
		ELSE
		BEGIN
			--1.31 pm AND OUT CAME ON THE SAME DAY.	
			
			--Aug 1 9:30 pm to Aug 2 07:00 am	Shift name 930
			--Aug 2 03:00 pm to Aug 2 09:30 pm  Shift name 3pm
			--Aug 3 weeklyoff but still he came for work means Initial shift Id = -1
			-- Aug 3 07am Aug 3 03:00pm so new shift id will be allocated through autoshift shifts.
			select @PrevDay = @inClk_Date
			select @PrevDay
			set @SHIFTID=0;
			set @day =DATEPART(DAY,@PrevDay)
			SET @YEAR=DATEPART(YEAR,@PrevDay)
			SET @MONTH=DATEPART(MONTH,@PrevDay)	
			IF(@SHIFTID = 0)  -- It runs for current day , whatever shift id updated in permenent shift table will be taken here. If shift id not present, new shift id wil be find out 
			BEGIN
				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
			goto GetShift;
			goto UpdateShift_Permanent;
		End		
	End	
	Else	 
	Begin
		select @PrevDay = @inClk_Date
		select @PrevDay
		
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),@day) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
						WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID ,0)
		DELETE FROM #TEMP
		if(@SHIFTID=-1)
		begin
			set @SHIFTID=0;
		end
		if(@SHIFTID=0)
		begin
			goto GetShift;
		end
		goto UpdateShift_Permanent;
	End 
	
	GetShift:
	begin
		--set @SHIFTID=0
		IF(@inClk_Time !='00:00' and @SHIFTID = 0 and @SHIFTID != -1)
		BEGIN
			Declare @Count int
			set @Count=0;
			Create Table #TempAutoShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40));
			Create Table #TempAutoShiftSingleShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40), shiftstartTime varchar(40), minutesdiffStart bigint, orderby int);
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId1,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId1 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId2,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId2 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId3,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId3 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId4,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId4 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId5,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId5 !=0	
			select @Count = isnull(count(EmpId),0)from #TempAutoShift				
			IF(@Count = 1)
			BEGIN
				select @SHIFTID = ISNULL(ShiftId,0)	from #TempAutoShift							
			END
			--ELSE IF(@Count = 0)
			--BEGIN
			--	set @SHIFTID = 0						
			--END
			ELSE
			BEGIN
				insert into #TempAutoShiftSingleShift 
				select b.EmpId,b.ShiftId,b.clkDate, b.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
				RANK()over(order by diff) from 
				(
					select a.EmpId,a.ShiftId,a.clkDate, a.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
					case when datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)<0 then -datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)
					else datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime) end as diff
					from #TempAutoShift a
					inner join TA_Tbl_Shift b on b.Shift_Id = a.ShiftId 
				)as b		

				declare @loopcount int
				Declare @ShiftNewtime datetime
				set @loopcount = 1
				while (@loopcount <= 5)
				Begin		
						select @ShiftNewtime = clkDate+shiftstartTime from #TempAutoShiftSingleShift  where orderby=@loopcount	
						if(@ShiftNewtime < @PrevEndtime)
						Begin
							set @loopcount = @loopcount + 1;													
						End			
						else
						begin
							select @SHIFTID = ShiftId from #TempAutoShiftSingleShift  where orderby=@loopcount	
							break;					
						End			
				End								
			END
			DROP TABLE #TempAutoShiftSingleShift
			DROP TABLE #TempAutoShift
		END
	end	
	UpdateShift_Permanent:
	Begin
		DECLARE @DynamicQuery VARCHAR(MAX)
		SELECT @year=DATEPART(YEAR,@PrevDay),@month=DATEPART(MONTH,@PrevDay),@day=DATEPART(DAY,@PrevDay) 	
		SET @DynamicQuery =''
		--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
		IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID)
		Begin
			if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EMPLOYEEAUTOID)
			begin
				SET @DynamicQuery =@DynamicQuery +'update TA_Tbl_PermanentShiftAllocation set day'+CONVERT(VARCHAR(2),@day)+'shift='+CONVERT(VARCHAR(2),@SHIFTID)+ ' where
				month='+CONVERT(VARCHAR(2),@month)+' and year='+CONVERT(VARCHAR(4),@year)+' and employeeid='+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)
			end
			else
			begin
				SET @DynamicQuery =@DynamicQuery +'insert into TA_Tbl_PermanentShiftAllocation (day'+CONVERT(VARCHAR(2),@day)+'shift,month,year,employeeid,Emp_id,dateshift)
				values('+CONVERT(VARCHAR(2),@SHIFTID)+ ','+CONVERT(VARCHAR(2),@month)+','+CONVERT(VARCHAR(4),@year)+','+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)+',1,'''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+''')'
			end
			exec (@DynamicQuery)
		End
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetClockID_FirstData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016 14.46,,>
-- Description:	<Proc_Ta_GetClockID_FirstData>
-- Proc_Ta_GetClockID_FirstData 5,'07/23/2020 03:57:00 PM','07/23/2020','T'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetClockID_FirstData]
	@inClk_EmpId varchar(50),
	@strInDateTime varchar(30),
	@gstrClockDate varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='R')
	begin
		select Clk_Id from TA_Tbl_Clockdetails 
		where clk_empid = @inClk_EmpId and (Clk_InDate+Clk_InTime) = 
		(SELECT Min(Clk_InDate+Clk_InTime) FROM TA_Tbl_Clockdetails 
		where clk_empid = @inClk_EmpId AND (Clk_InDate+Clk_InTime) > Cast(@strInDateTime as DateTime) 
		AND Clk_Date = Cast(@gstrClockDate as DateTime)  AND IsVoid = 0)
	end
	else if(@Type='U')
	begin
		SELECT Clk_Id FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND Clk_Date =  Cast(@gstrClockDate as DateTime)
		AND (Clk_InDate = '' OR Clk_InDate IS NULL) AND Clk_OutDate <> '' AND Clk_OutDate IS NOT NULL 
		AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND IsVoid = 0
	end
	else if(@Type='T')
	begin
		SELECT TOP 1 Clk_Id,Clk_Date,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails 
		WHERE Clk_EmpId = @inClk_EmpId AND Clk_Date = Cast(@gstrClockDate as DateTime)
		AND (Clk_OutDate = '' OR Clk_OutDate IS NULL) AND Clk_InDate <> '' AND Clk_InDate IS NOT NULL AND IsVoid = 0
		AND (Clk_InDate+Clk_InTime) <= Cast(@strInDateTime as DateTime) ORDER BY (Clk_InDate+Clk_InTime) DESC
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCommaSeparatedValues]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 03-May-2011
-- Description:	To get comma separated values by passing the data table as xml and also passing the column name
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCommaSeparatedValues]
(
	@xml xml
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @String varchar(max)
   Declare @Index int
   Set @Index = 0;
   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	set @String = (select E.Employee_Code_Id  + ',' 
	from OpenXML(@Index, '/DocumentElement/Table') 
	With (EmployeeAutoId Bigint 'EmployeeAutoId') as xm 
	inner join TA_Tbl_Employee E on xm.EmployeeAutoId = E.Employee_Id
	for xml path(''))
   Exec sp_xml_removedocument @Index
   --select @String
   SET @String = LEFT(@String, LEN(@String) - 1)
SELECT @String
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompanyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Getting Company Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCompanyDetails]
	@LevelId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]= @LevelId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompanyDetailsUsingEmpCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetCompanyDetailsUsingEmpCode 741
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCompanyDetailsUsingEmpCode]
	@EmpCode varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @today datetime =getdate()
	select @EmpCode=Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmpCode
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @today,@EmpCode
	declare @GetLevelID as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	Declare @CompanyID int
	;WITH ParentLevel AS
	(
		SELECT id,parentId, 1 AS Lvl FROM Ta_Tbl_levelDetails 
		WHERE id = @GetLevelID
		UNION ALL
		SELECT rh.id,rh.parentId, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
		INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
	)
	SELECT top 1 @CompanyID =id FROM ParentLevel where parentId=0
	select isLOPDisplayed=isnull(isLOPDisplayed,0)  from TA_Tbl_ShiftSettings where CompanyId=isnull(@CompanyID,0)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIdForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetCompanyIdForService]
	-- Add the parameters for the stored procedure here
	@LevelId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]=@LevelId
	WHILE((SELECT parentId from TA_tbl_LevelDetails where id=@Levelid)!=0) 
		BEGIN 
			SELECT @Levelid=parentId from TA_tbl_LevelDetails where id=@Levelid
		END
	SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]= @LevelId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetCompanyIds]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ld.id as CompanyId,replace(ld.name,'&amp;','&') as CompanyName  
	from TA_Tbl_LevelDetails ld inner join TA_Tbl_Level l on l.LevelId=ld.LevelId  
	where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.parentid=0 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Proc_TA_GetCompOffDays 10860,2
Procedure Name		:		Proc_TA_GetCompOffDays 10947,2
Description			:		Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included		:		Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By			:		Prabakaran
Created On			:		18-Feb-07
Description			:		Remove The Date Convertion In Expaire Date Calculation
EXEC Proc_TA_GetCompOffDays @EmployeeId=947,@YearSettingId=3,@Date='02-May-2019'
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetCompOffDays] 
	@EmployeeId BIGINT,
	@YearSettingId INT,
	@Date VARCHAR(50) = NULL
AS
BEGIN
	set nocount on
	DECLARE @FromDate DATETIME, @ToDate DATETIME, @MaxDate DATETIME, @DateFormt DATETIME
	DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT
	DECLARE @Employee_code_Id NVARCHAR(50), @OtText VARCHAR(MAX)
	DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT
	DECLARE @ValidDates INT
	declare @employeeCodeID as nvarchar(20)
	declare @RequestCOff int
	declare @today datetime =getdate()
	select @employeeCodeID=Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmployeeId
	declare @LevelId varchar(2000)
	 create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
      insert into #EmpLevel exec [Proc_TA_EmpLevel] @today,@employeeCodeID 
      declare @GetLevelID as int
            set @GetLevelID=(select top 1 LevelId from #EmpLevel)
            DECLARE @childID INT 
             ;WITH ParentLevel AS
            (
                  SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
                  UNION ALL
                  SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
                  INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
            )
            SELECT TOP 1 @LevelId=id
            FROM ParentLevel r
            --inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
            ORDER BY lvl DESC
	select @RequestCOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	if(@RequestCOff is null)
		begin
			select @RequestCOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		end
	BEGIN TRY
			BEGIN TRAN
			-- Get From Date/To Date from Active year
				SELECT @ToDate = ToDate ,@FromDate = FromDate FROM TA_Tbl_YearSetting WHERE YearSettings_Id = @YearSettingId
				IF ((ISNULL(@Date, '') = '') OR (@Date = ''))
				BEGIN
					SET @Date = CONVERT(VARCHAR(11), GETDATE(), 101)
				END
				DECLARE @Denamitator VARCHAR(1), @Dt VARCHAR(10), @Mon VARCHAR(10),  @Year VARCHAR(10)
				DECLARE @PI INT
				BEGIN TRY
					BEGIN TRAN
						SET @DateFormt = CAST(@Date AS DATETIME)
						IF(@@ERROR = 0)
							COMMIT TRAN
				END TRY
				BEGIN CATCH
						IF(@@ERROR <> 0)
							ROLLBACK TRAN
						SET @Denamitator =  CASE WHEN @Date LIKE '%/%' THEN '/' WHEN @Date LIKE '%-%' THEN '-' ELSE ' ' END
						SET @PI = 0
						SET @Dt = SUBSTRING(@Date,@PI,CHARINDEX(@Denamitator, @Date, @PI))
						SET @PI = @PI + CHARINDEX(@Denamitator, @Date, 0) 
						SET @Mon = SUBSTRING(@Date,@PI+1,CHARINDEX(@Denamitator, @Date, @PI)-1)
						SET @PI = @PI + CHARINDEX(@Denamitator, @Date, 0)
						SET @Year = SUBSTRING(@Date,@PI+1,CHARINDEX(@Denamitator, @Date, @PI)-1)
						SET @DateFormt = CAST((@Mon + '-' + @Dt + '-' + @Year) AS DATETIME)
				END CATCH
				SET @CompOffDays = 0
				SET @SumOfOTMins = 0
				SET @OtText = ''
				IF EXISTS(SELECT CompOff_Eligible FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeId AND IsDeleted = 0 AND CompOff_Eligible = 1 AND CompOff_Eligible IS NOT NULL AND OT_Eligible = 0 AND OT_Eligible IS NOT NULL)
				BEGIN
					DELETE FROM TA_Tbl_OverTimeStatus FROM TA_Tbl_OverTimeStatus OT
						LEFT OUTER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OT.Process_RecID
					WHERE ISNULL(LeaveApplicationId, '') = '' AND OT.Employee_Id = @EmployeeId AND ISNULL(PD.Process_Rec_ID, '') = '' and ISNULL(OT.isRequest,0)=0
					-- Get Employee code Id based on Employee Id
					SELECT @Employee_code_Id = SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeId AND IsDeleted=0
					--for the below reason Commented by Manikandan.RR on 16-Oct-2020.
					--if we approve past days record after current month data means, quota is not generating. we got this issue in scufe client.					
					--SELECT @FromDate = ISNULL(MAX([Date]) + 1, @FromDate) FROM TA_Tbl_OverTimeStatus OTS WHERE OTS.OverTimeStatus = 'Approved' AND OTS.CompOffEligible = 1 AND OTS.Employee_Id = @EmployeeId
					-- Get OtMinHrs (Over Time Minimum Hours)
					SELECT 			
						@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,'00:00', ISNULL(OtMinHrs, '00:00')),
						@FullDayOTMins = DATEDIFF(MI,'00:00',ISNULL(FullDayOTMinHrs, '00:00')),
						@ValidDates = ISNULL(LP.CompOffValidDays, 60)
					FROM TA_Tbl_LeavePolicy LP
					INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
					WHERE ELP.EmployeeId = @EmployeeId AND
						ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
							INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
							WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeId ORDER BY ELP.ToDate DESC)
					-- Get CompOff (Compensation Off) days
					IF(@TypeOfOT=1)
					BEGIN
						SELECT 
							@SumOfOTMins = (@SumOfOTMins + OtMins),
							@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),
							--@OtText = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @OtText ELSE (@OtText + ';' + CAST(Process_Rec_ID AS VARCHAR(50)) + '&' + CONVERT(VARCHAR(11), @MaxDate, 101) + '&' + CAST(ISNULL(HrsExtra, '00:00') AS VARCHAR(10)) + '&' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
							@OtText = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @OtText ELSE (@OtText + ';' + CAST(Process_Rec_ID AS VARCHAR(50)) + '&' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
							@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),
							@MaxDate = NULL
						FROM TA_Tbl_ProcessedData
							WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND OvertimeStatus='Approved'
							AND (DATEADD(D, @ValidDates, [Date])) >= @DateFormt AND OtMins > 0 AND ISNULL(OtMins, '') != ''
						ORDER BY [Date]
						if(@RequestCOff=0)
						begin
							INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest, isDelete)
								SELECT PD.Process_Rec_ID, @EmployeeId, PD.[Date], PD.HrsExtra, T.OverTimeMins, PD.OverTimeStatus, 1, 0, (DATEADD(D, @ValidDates, PD.[Date])), (CASE WHEN T.OverTimeMins >= @FullDayOTMins THEN 1.0 WHEN T.OverTimeMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN T.OverTimeMins >= @FullDayOTMins THEN 1.0 WHEN T.OverTimeMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),PD.[Date]) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END),0,0 FROM TA_Tbl_ProcessedData PD 
									INNER JOIN (SELECT CAST((SUBSTRING(Value, 0, CHARINDEX('&', Value,0))) AS INT) Process_RecID, (CAST(SUBSTRING(Value, CHARINDEX('&', Value,0)+1, LEN(Value)) AS INT)) OverTimeMins  FROM [dbo].Split(@OtText, ';') WHERE Value != '') T ON PD.Process_Rec_ID = T.Process_RecID
								WHERE Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus OS WHERE OS.Employee_Id = @EmployeeId) AND
								([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND
								OvertimeStatus='Approved' AND  T.OverTimeMins >= @HalfDayOTMins
						END
					END
					ELSE 
					BEGIN
						if(@RequestCOff=0)
						begin
							INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest, isDelete)
								SELECT Process_Rec_ID, @EmployeeId, [Date], HrsExtra, OtMins, OverTimeStatus, 1, 0, (DATEADD(D, @ValidDates, [Date])), (CASE WHEN OtMins >= @FullDayOTMins THEN 1.0 WHEN OtMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN OtMins >= @FullDayOTMins THEN 1.0 WHEN OtMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),[Date])< GETDATE() THEN 'Expired' ELSE 'Not Taken' END),0,0 FROM TA_Tbl_ProcessedData WHERE 
								Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus OS WHERE OS.Employee_Id = @EmployeeId) AND
								([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND
								OvertimeStatus='Approved' AND  OtMins >= @HalfDayOTMins
						END
					END
				END	
				-- Get Number of CompOff days from Leave Application	
				 update TA_Tbl_ProcessedData set 
			  OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
				SELECT @CompOffDays = ISNULL(SUM(OTS.RemainingDays), 0) FROM TA_Tbl_OverTimeStatus OTS WHERE 
					OTS.OverTimeStatus = 'Approved' AND ISNULL(OTS.CompOffSatus, 'Not Taken') = 'Not Taken' AND
					OTS.CompOffEligible = 1 AND OTS.Employee_Id = @EmployeeId AND
					OTS.[DateToExpired] >= @DateFormt and OTS.Date<=@DateFormt
			IF(@@ERROR = 0)
				COMMIT TRAN
		END TRY
		BEGIN CATCH
		END CATCH
		SELECT (CASE WHEN @CompOffDays < 0 THEN 0 ELSE ISNULL(@CompOffDays, 0) END) [CompOffDays]
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_GetCompOffDays 210
Description		:	Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	Prabakaran
Modified On		:	03-Nov-09
*/
Create   PROCEDURE [dbo].[Proc_TA_GetCompOffDays_Angler] 
@EmployeeId bigint
AS
Declare @FromDate as datetime
Declare @ToDate as datetime
Declare @CompOffDays as bigint
Declare @NumberOfDays as bigint
Declare @OtMinHrs as nvarchar(20)
Declare @OtHrs as bigint
Declare @OtMin as bigint
Declare @TotalOtMin as bigint
Declare @Employee_code_Id as nvarchar(50)
BEGIN
declare @intCompEligible as int
set @intCompEligible=(select isnull(CompOff_Eligible,0) as CompOff_Eligible from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
--set @intCompEligible=1
if(@intCompEligible>0)
begin
	-- Get Employee code Id based on Employee Id
	set @Employee_code_Id=(select SwipeCardNo from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
	-- Get From Date from Active year
	set @FromDate=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
	-- Get To Date from Active year
	set @ToDate=(select ToDate from TA_Tbl_YearSetting where IsActive=1)
/*
	-- Get OtMinHrs (Over Time Minimum Hours)
	set @OtMinHrs=(select isnull(OtMinHrs,'00:00') as OtMinHrs from TA_Tbl_LeavePolicy lp
	inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lp.Policy_Id
	where elp.EmployeeId=@EmployeeId 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
	--and (getdate() between elp.FromDate and elp.ToDate))
	-- Get Overtime Hours
	set @OtHrs=(select left(@OtMinHrs,2))
	-- Get Overtime Minutes
	set @OtMin=(select right(@OtMinHrs,2))
	-- Get Total Over Time Minutes from Over Time Hours and Over Time Minutes
	set @TotalOtMin=(@OtHrs*60) + @OtMin
	-- Get CompOff (Compensation Off) days
	set @CompOffDays=(select sum(OtMins) from TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id=@Employee_code_Id AND OvertimeStatus='Approved')
*/
	-- Get Number of CompOff days from Leave Application
	-- Get CompOff (Compensation Off) days using Weekly Off Days and Global Holidays
	set @CompOffDays=(select count(*) from TA_Tbl_ProcessedData 
	where ((FNAttendanceCode='Weekly Off' 
	and Attendance='Present') or (FNAttendanceCode='Holiday' 
	and Attendance='Present')) and Employee_Code_Id=@Employee_code_Id and ([Date] BETWEEN @FromDate AND @ToDate))
--select @CompOffDays
	set @NumberOfDays=(select sum(isnull(NumberOfDays,0)) as NumberOfDays from TA_tbl_LeaveApplication 
	WHERE ((Leave_FromDate BETWEEN  @FromDate AND @ToDate) AND (Leave_ToDate BETWEEN  @FromDate AND @ToDate))
	AND Employee_Id=@EmployeeId and Type='Comp Off' and Status NOT IN ('Rejected') and IsDeleted=0)
--select @NumberOfDays
	-- Check Number of Days applied Empty or null
	if(@NumberOfDays is null or @NumberOfDays='')
		BEGIN
		set @NumberOfDays=0
		END
set @CompOffDays=@CompOffDays-@NumberOfDays
/*
	IF(@TotalOtMin > 0)
		BEGIN
			-- Find Remaining CompOff days
			set @CompOffDays=(@CompOffDays/@TotalOtMin)-@NumberOfDays
		END
	ELSE
		BEGIN
			set @CompOffDays=0
		END
*/
end
else
begin
set @CompOffDays=0
end
	IF(@CompOffDays<=0)
		BEGIN
			select 0 as CompOffDays
		END
	ELSE
		BEGIN
			select isnull(@CompOffDays,0) as CompOffDays
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountFlexibleTimings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_GetCountFlexibleTimings 4
CREATE   PROCEDURE [dbo].[Proc_TA_GetCountFlexibleTimings]
(
    @Org_LevelID int
)
AS
begin
select count(*) as FlexibleCount from ta_tbl_shiftsettings Where CompanyId=@Org_LevelID and IsFlexible=1 and FlexibleFlag=2
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountInterveningWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_GetCountInterveningWeekOff 
Description	:	Get weekly off count exist within given Fromdate and Todate
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By	:	Prabakaran
Created On	:	16-Aug-07
Modified By	:
Modified On	:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetCountInterveningWeekOff] 
@EmployeeId int,
@FromDate datetime,
@ToDate datetime,
@Type varchar(10)
as
declare @query as Varchar(3000)
Declare @TempShiftId as int
Declare @CountDays as int
create table #Temp(ShiftTemp int)
declare @vFromDate as datetime
declare @vToDate as datetime
set @vFromDate=DateAdd(day,-1,@FromDate)
set @vToDate=DateAdd(day,-1,@ToDate)
while(@vFromDate<=@vToDate)
begin
set @vFromDate=DateAdd(day,1,@vFromDate)
if(@Type='P')
set @query = ('select Day' + Cast(Day(@vFromDate) as Varchar(25)) + 'Shift from  TA_Tbl_PermanentShiftAllocation where Year = year(''' + cast(@vFromDate as Varchar(25)) + ''') and Month = month('''+ cast(@vFromDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
if(@Type='T')
set @query = ('select Day' + Cast(Day(@vFromDate) as Varchar(25)) + 'Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year(''' + cast(@vFromDate as Varchar(25)) + ''') and Month = month('''+ cast(@vFromDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
insert into #Temp EXEC(@query)
end
select * from #Temp
drop table #Temp
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCurrentDateProgressDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetCurrentDateProgressDetails '2020/06/12',4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCurrentDateProgressDetails]
	@ShiftDate datetime,
	@EmployeeID bigint
AS
BEGIN
	SET NOCOUNT ON;	
	SELECT 	
	Project_Name,
	TaskName,		
	TaskDescription,
	PT.TaskHours,
	SpentHours,
	TaskSubmittedDate,
	TaskSubmittedBy,
	TaskModifiedDate,
	TaskModifiedBy,
	ModificationReason,
	ApprovedHours,
	ApprovedBy1,
	ApprovedDate1,
	ApprovedBy2,
	ApprovedDate2,
	TaskDetailID,
	ShiftDate,
	Status,
	Project_Code,
	PT.ProjectId,
	Client_Name,
	Project_Description,
	Project_StartTime,
	Project_EndTime,
	Project_Status,
	IsDeleted,
	Created_By,
	Created_On,
	Modified_By,
	Modified_On,
	LevelID,
	Mandays,
	ManHours,	
	isSubmitted_Completely,
	SpentMinuts=dbo.ConvertHoursToMinites(spenthours),
	PT.TaskID from TA_Tbl_Project P 
	Inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
	Inner join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and PT.taskID=TPD.TaskID)
	where TPD.TaskSubmittedBy=@EmployeeID and TPD.ShiftDate=@ShiftDate and isnull(isSubmitted_Completely,0)=0	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.manikandan>
-- Create date: <15-Nov-2021 09:00 am>
-- Description:	<Get Maximum hours exceed employees for both weekly and Quarterly Overtime policy concept>
-- Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails '2022-03-21','a'
-- Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails '2021-08-23','WO'
-- Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails null,'QO'
-- Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails '2021-08-23','QO'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCurrentWeekOrQuarter_WorkHoursDetails]
	@Given_Fromdate datetime=null,	
	@flag varchar(2) --Weekly or Overtime
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @MaxExceedHours  int
    Declare @FromDate datetime
    set @FromDate=@Given_Fromdate
	Declare @Todate Datetime
	Declare @Fromdate_Day varchar(10)
	Declare @Todate_Day varchar(10)
	Declare @GivenDate datetime
	Create Table #TempEmployeeDetails(EmployeeID varchar(20),EmployeeName varchar(250),TotalWorkHours varchar(10),ReasonID varchar(1))
	if(@flag='WO' or @flag='A' or @flag='ED')
	BEGIN
		set @MaxExceedHours=53
		Declare @StartDay varchar(20)		
		Declare @StartNo int
		if(@Fromdate is null)
		BEGIN
			set @Fromdate=CONVERT(varchar(11),getdate())
		END
		set @Todate=CONVERT(varchar(11),getdate())
		select @StartNo= CumulativeWeekStartDay from TA_Tbl_ShiftSettings 
		--set @StartNo=4
		select @StartDay=case when @StartNo=2 then 'Monday'
					when @StartNo=3 then 'Tuesday'
					when @StartNo=4 then 'Wednesday'
					when @StartNo=5 then 'thursday'
					when @StartNo=6 then 'friday'
					when @StartNo=7 then 'saturday'
					when @StartNo=1 then 'sunday'
		end
		Declare @i int
		set @i=7
		Declare @j int
		set @j=0
		while (@i>0)
		begin
			if(datename(dw,dateadd(d,-@j,@fromdate))=@StartDay)
			begin		
				set @Fromdate=dateadd(d,-@j,@fromdate)	
				break;
			end
			else
			begin
				set @i=@i-1
				set @j=@j+1
			end
		end
		if(@Todate<@FromDate)
		begin
			select 'Todate should be greater than From date. so please check the condition'
			return;
		end
		
		--select Fromdate=@FromDate,Todate=@Todate,FromDate_Day=DATENAME(dw,@FromDate),
		--Todate_day=DATENAME(dw,@Todate),Difference=DATEDIFF(d,@FromDate-1,@Todate)	
		
		create table #TempProcessedData(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),WorkHours_min bigint)
		insert into #TempProcessedData
		select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName, pd.WorkHoursInMins from TA_Tbl_ProcessedData pd
		Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
		where (Date>=@FromDate and Date<=@Todate) and E.Isdeleted=0 and E.Hostel=1
		--Blocking is required means, value will be one.
		and ProcessFlag=1
		
		
		select EmployeeID,EmployeeName,[Total Work Hours]= dbo.ConvertMinsToHours(SUM(WorkHours_min)) from #TempProcessedData
		group by EmployeeID,EmployeeName
		having(SUM(WorkHours_min)>=(@MaxExceedHours*60))
		
		Insert into #TempEmployeeDetails
		select EmployeeID,EmployeeName,[Total Work Hours]= dbo.ConvertMinsToHours(SUM(WorkHours_min)),(1) from #TempProcessedData
		group by EmployeeID,EmployeeName
		having(SUM(WorkHours_min)>=(@MaxExceedHours*60))
		
	END
	if(@flag='QO' or @flag='A' or @flag='ED')
	BEGIN		
		Declare @FinancialYear_FromDate datetime
		Declare @FinancialYear_Todate datetime
		Declare @multiply_Factor float
		
		
		select @MaxExceedHours=71, @FinancialYear_FromDate=FromDate,@FinancialYear_Todate=@FinancialYear_Todate from TA_Tbl_YearSetting where IsActive=1
		if(@Given_Fromdate is null)
		begin
			set @GivenDate=DATEADD(M,-0,getdate())		
		end
		else
		begin
			set @GivenDate=DATEADD(M,0,@Given_Fromdate)
		end
		select @multiply_Factor= 
			case	when DATEPART(month,@GivenDate) in(1,2,3,4) then 1 
					when DATEPART(month,@GivenDate) in(5,6,7,8) then 2
					when DATEPART(month,@GivenDate) in(9,10,11,12) then 3
			end
			
			select 
			@FromDate=
			case	when @multiply_Factor=1 then DATEADD(m,0,@FinancialYear_FromDate)
					when @multiply_Factor=2 then DATEADD(m,4,@FinancialYear_FromDate)
					when @multiply_Factor=3 then DATEADD(m,8,@FinancialYear_FromDate)
			end,@Todate=@GivenDate
		
		--select Quarter=@multiply_Factor,Fromdate=@FromDate,Todate=@Todate
		if(@Todate<@FromDate)
		begin
			select 'Todate should be greater than from date. so please check the condition'
			return;
		end		
		create table #TempProcessedDataOT(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),ot_min bigint)
		insert into #TempProcessedDataOT
		select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName, pd.OtMins from TA_Tbl_ProcessedData pd
		Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
		where (Date>=@FromDate and Date<=@Todate) and E.Isdeleted=0 and E.Hostel=1
		--Blocking is required means, value will be one.
		and ProcessFlag=1 and E.OT_Eligible=1
		
		
		select EmployeeID,EmployeeName,[Total Overtime]=dbo.ConvertMinsToHours(SUM(ot_min)) from #TempProcessedDataOT
		group by EmployeeID,EmployeeName
		having(SUM(ot_min)>=(@MaxExceedHours*60))
		
		Insert into #TempEmployeeDetails
		select EmployeeID,EmployeeName,[Total Overtime]=dbo.ConvertMinsToHours(SUM(ot_min)),(2) from #TempProcessedDataOT
		group by EmployeeID,EmployeeName
		having(SUM(ot_min)>=(@MaxExceedHours*60))
	END
	Create Table #TempFinal(TotalEmployee Int,ReasonID int,Reason varchar(50))
	--select * from #TempEmployeeDetails 
	--return;
	IF NOT EXISTS(select ReasonID from #TempEmployeeDetails where ReasonID=1)
	BEGIN
	--testing purpose inserted dummy value, need to remove round function below
		Insert into #TempFinal values(ROUND(RAND()*100,0),1,'Weekly 60 Hrs Exceed')
	END
	IF NOT EXISTS(select ReasonID from #TempEmployeeDetails where ReasonID=2)
	BEGIN
		Insert into #TempFinal values(ROUND(RAND()*100,0),2,'Quarterly 75 Hrs OT Exceed')
	END
	
	Select TotalEmployee,ReasonID=case when ReasonID=1 then 'Weekly 60 Hrs' else 'Quarterly 75 Hrs OT' end,Reason from #TempFinal
	order by ReasonID,Reason
	
	Select TotalEmployee=sum(isnull(TotalEmployee,0)) from #TempFinal
	
	select* from #TempEmployeeDetails
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetDashboardInformation '', '2020/07/20', '2020/07/20',0,0,0,'SuperAdmin','0','0'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDashboardInformation]
      @EMPLOYEECODEID	NVARCHAR(MAX) = NULL,
      @FROMDATE			DATETIME,
      @TODATE			DATETIME,
      @Session			INT,
      @ShiftID			INT,
      @ParentID			INT,
      @UserGroupName	NVARCHAR(100),
      @GradeLevel		NVARCHAR(20),
      @empId			NVARCHAR(MAX)
AS
BEGIN 
	set nocount on;	
	Declare @FromdateString nvarchar(20)
	declare @todat			nvarchar(20);
	Declare @NoShiftID int
	select @NoShiftID=Shift_Id from TA_Tbl_Shift where Level_Id=0 and Shift_ShortName='NOS'
	select @NoShiftID=isnull(@NoShiftID,0)
	set @todat=GETDATE();
	if @FROMDATE=''
	begin
		  set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(nvarchar(20),DATEPART(month,getdate()))+'-'+
		  case when len(CONVERT(nvarchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,GETDATE()))
		  else CONVERT(nvarchar(20),DATEPART(D,GETDATE())) end
	end   
	else
	begin
		set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(nvarchar(20),DATEPART(month,@fromdate))+'-'+
		case when len(CONVERT(nvarchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,@fromdate))
		else CONVERT(nvarchar(20),DATEPART(D,@fromdate)) end
	end
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	Create table #FirstTableValue(TOPIC nvarchar(100),ValueCount int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #SecondDummyTableValue(TOPIC nvarchar(100),Count int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #ThirdDummyTableValue(Approval nvarchar(100),Approved int,Forwarded int,Pending nvarchar(100),ApprovedPercent nvarchar(30),ForwardedPercent nvarchar(30),PendingPercent nvarchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		select @groupid=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',''
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	Declare @sqlEmpLevel nvarchar(4000) 
	set @sqlEmpLevel=
	'insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and emp.Employee_Code_Id<>''18000000''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) and EL.LevelId is not null'    
	if(@isReportingto > 0)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) '  
		END   
	if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and ELevel.EmployeeId in ('+CAST(@empId as nvarchar(10))+')'
		END   
	execute(@sqlEmpLevel)
	--select * from #EmpLevel
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeecountQuery nvarchar(4000)
	Declare @EmployeePresentcountQuery nvarchar(4000)     
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode='Present' or ANAttendanceCode='Present') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  WHERE P.DATE=@FromdateString
			  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
	
	
	Declare @FirstBoard		nvarchar(MAX)
	Declare @FirstBoard1	nvarchar(MAX)
	Declare @SecondBoard	nvarchar(MAX)
	Declare @ThirdBoard		nvarchar(MAX)
	Declare @FourthBoard	nvarchar(MAX)
	Declare @FifthBoard		nvarchar(MAX)
	Declare @sixthBoard		nvarchar(MAX)
	Declare @Present_Filters nvarchar(MAX)
	Declare @Absetn_Filters	nvarchar(MAX)
	Declare @Leave_Filters	nvarchar(MAX)
	Declare @Union			nvarchar(MAX)
	set @Union=' Union All '
	IF ((ISNULL(@FROMDATE, '') <> ''))
	BEGIN
		--First Gridview Control
		Declare @CommonJoinQueries nvarchar(MAX)         
		Declare @CommonSelectQueries nvarchar(MAX) 
		set @FirstBoard=''      
		Declare @Firstboardexists int
		set @Firstboardexists=0
		set @CommonJoinQueries=''
		set @CommonJoinQueries=@CommonJoinQueries+' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
		INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
		INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
		Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
		set @CommonSelectQueries=''
		set @CommonSelectQueries=@CommonSelectQueries+'select 
			  TOPIC,
			  COUNT,
			  HYPER,
			  REPORTNAME, 
			  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
						  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeeCount)+' * 100)),0))+'' %'' 
			  End'
		Declare @Filters nvarchar(MAX)
		set @Filters=''
		if(@ShiftID!=0)
		begin
			  set @Filters =@Filters+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
		end
		if(@UserGroupName<>'SuperAdmin')
		BEGIN
			  SET @Filters = @Filters + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END
		-- Added below line by manikandan.r on 16-11-2016
		-- if you remove below line it will bring wrong value for absent column.bug id:0035540
		if(@isReportingto > 0)
		BEGIN  
			  SET @Filters = @Filters + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
		End
		--Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  set @FirstBoard =@CommonSelectQueries+' as PercentageValue from 
			  (
					SELECT DISTINCT ''Present'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''MonthlyAttendance'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'       
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND (FNAttendanceCode=''Present'' or ANAttendanceCode=''PRESENT''or (FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (intime<>''00:00'' or outtime<>''00:00''))
					or (FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' and (intime<>''00:00'' or outtime<>''00:00'')))
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Present'
			  set @Firstboardexists=1
		end
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard =@FirstBoard+@CommonSelectQueries+' as AbsenteesPercent from 
			  (
					SELECT DISTINCT ''Absent'' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''Absentees'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
					set @FirstBoard=@FirstBoard+@CommonJoinQueries        
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND 
					(ANAttendanceCode=''ABSENT'' AND FNAttendanceCode=''Absent'') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Absent'
			  set @Firstboardexists=1
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin
			  declare @LeaveCount nvarchar(MAX)
			  --Getting Leave Data          
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+' as LeavePercent from 
			  (
					SELECT DISTINCT ''Approved Leave'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''Leave_Angler'' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P'        
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND 
					(
						  FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') or
						  ANAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'')
					)
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Leave'
			  set @Firstboardexists=1
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as OnDutyPercent from (
			  SELECT DISTINCT ''Approved OnDuty'' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''OnDuty'' AS REPORTNAME 
			  FROM Ta_Tbl_ManualTimeEntry M
			  inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
			  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and 
			  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
			  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) '
			  SET @FirstBoard = @FirstBoard + ' WHERE (M.ManualTimeEntry_InDate >= '''+convert(nvarchar(MAX),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(nvarchar(MAX),@FromdateString)+''') 
			  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''Approved'' And OD.Onduty_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as OnDuty'
			  set @Firstboardexists=1
		end
		--Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as PunctualityPercent from (
			  SELECT DISTINCT ''Punctuality'' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''Punctuality'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)=0 AND 
			  (ANAttendanceCode<>''Weekly Off'' or FNAttendanceCode<>''Weekly Off'') AND (p.LateIn=''00:00'' and p.InTime <> ''00:00'')
			  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Punctuality'
			  set @Firstboardexists=1
		end
		--Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '  as RawDataPercent from (
			  Select ''Attendance Summary'' As TOPIC,COUNT(P.DATE) [COUNT],
			  6 as HYPER,''AttendanceSummary'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''           
			  set @FirstBoard=@FirstBoard+@Filters+ ') as Attendance'
		end
		if(ISNULL(@FirstBoard,'')!='')
		begin
			  set @FirstBoard='insert into #FirstTableValue ' + @FirstBoard
			  Execute(@FirstBoard)
		end
		select * from #FirstTableValue
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		--Second Table
		--Getting Late Entry Data
		Declare @WhereFilter nvarchar(MAX)
		set @ThirdBoard=''
		Declare @ThirdBoardvalue int
		set @ThirdBoardvalue =0
		set @WhereFilter =' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
		((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) 
		and E.Employee_Code_Id<>''18000000'''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
		begin
			  set @ThirdBoard='  
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' 
					End as Percentage from (
			  SELECT DISTINCT ''Late Entry'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''LateEntry'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Early Exit Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+' 
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Early Exit'' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''EarlyExit'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + 'WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(EarlyOutMins,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Less Hours worked Data
		--Getting Shift Not allocated Employee Record
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select	TOPIC,
						COUNT,
						HYPER,
						REPORTNAME,
						Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
						Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End as 
						Percentage from 
						(                   
							SELECT  DISTINCT ''Shift Not Allocated'' AS TOPIC, 
									isnull(sum(case when (isnull(P.Shift_id,''0'')=0 or isnull(P.Shift_id,''0'')=''' + CONVERT(varchar(20),@NoShiftID) +''') then 1 else 0 end),0) [COUNT],
									3 AS HYPER, 
									''Shift Not Allocated'' AS REPORTNAME 
									FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''')'
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Approved Overtime Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Approved Over Time'' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''OverTime'' AS REPORTNAME 
			  FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '  WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''Approved'' And E.CompOff_Eligible=0 And E.OT_Eligible=1 '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1 
		end         
		--Getting Discrepancy Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME,  
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(DistinctCOUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage from 
			  ( 
					SELECT      DISTINCT ''Discrepancy'' AS TOPIC, 
								COUNT(C.Clk_EmpId) [COUNT],
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''Discrepancy'' AS REPORTNAME 
					FROM ta_tbl_clockdetails C
					Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
			  SET @ThirdBoard = @ThirdBoard + '  WHERE (C.Clk_Date ='''+convert(nvarchar(MAX),@FromdateString)+''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+') as A'
			  set @ThirdBoardvalue=1 
		end
		--Getting Non processed data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME, 
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage 
			  from(
						  Select      ''Non Processed Record'' As TOPIC,
									  COUNT(*)[COUNT],
									  COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
									  6 as HYPER,
									  ''Non Process'' AS REPORTNAME 
						  FROM TA_Tbl_Clk_RawData C           
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  '
			  SET @ThirdBoard = @ThirdBoard + ' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE ='''+convert(nvarchar(MAX),@FromdateString)+''''
			  set @ThirdBoard=@ThirdBoard+') as A'
		end
		--Execute(@ThirdBoard)
		if(ISNULL(@ThirdBoard,'')!='')
		begin
			--print (@ThirdBoard)
			Execute(@ThirdBoard)
		end
		else
		begin
			select * from #SecondDummyTableValue
		end
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		Declare @SecondBoardValue int
		set @SecondBoardValue=0
		set @FifthBoard=' '
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
		begin
			set @FifthBoard=@FifthBoard+'
			select 
				  ''Leave'' as Approval,
				  Approved,
				  Forwarded,
				  Pending,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ApprovedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ForwardedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as PendingPercent from
			(
					select      
								count(case  when L.Status=''Approved'' then 1  end)Approved,
								count(case  when L.Status=''Forwarded'' then 1 end)Forwarded,
								count(case  when L.Status=''Pending''  then 1  end)Pending
					from TA_Tbl_LeaveApplication L 
					Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
					Left outer join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=e.SwipeCardNo and P.Date=''' + CONVERT(nvarchar(MAX),@FromdateString) +''')'
                       SET @FifthBoard = @FifthBoard + '  where 
					(
						(''' + CONVERT(nvarchar(MAX),@FromdateString) +''' between L.Leave_FromDate and L.Leave_ToDate)
						
					) 
					and L.IsDeleted=0'
					if(@ShiftID!=0)
						  begin
								set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
						  end               
					if(@UserGroupName<>'SuperAdmin')
						  BEGIN
								SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
						  END
					if(@isReportingto > 0)
					BEGIN  
						  SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
					End         
					set @FifthBoard=@FifthBoard+') as a'
					set @SecondBoardValue=1                         
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+ ' select 
					''Onduty'' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),(Approved*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ApprovedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ForwardedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as PendingPercent from
					(
								select                              
								count(case  when (M.ManualTimeEntry_Status =''Approved'' and OD.Onduty_Status =''Approved'') then 1 else null end) Approved,
								count(case  when (M.ManualTimeEntry_Status=''Forwarded'' and OD.Onduty_Status=''Forwarded'') then 1 else null end) Forwarded,
								count(case  when (M.ManualTimeEntry_Status=''Pending'' and OD.Onduty_Status=''Pending'')  then 1 else null end)  Pending
								from Ta_Tbl_ManualTimeEntry M 
								inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
								Inner join TA_Tbl_Employee E 
								on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
								Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
								INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
								INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
								Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
								----Newly added below left outer instead of innner join 13-Feb-2020
								Left Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
								(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
								(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  '
			  SET @FifthBoard = @FifthBoard + ' where M.IsOnDuty=1 and M.isDeleted=0 and
			  M.ManualTimeEntry_InDate<='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and 
			  M.ManualTimeEntry_OutDate>='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and M.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End               
			  set @FifthBoard=@FifthBoard+') as B '
			  set @SecondBoardValue=1 
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+' select ''Permission'' as Approval,
						  Approved,
					Forwarded,
					Pending,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ApprovedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ForwardedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as PendingPercent from
			  (
						  select 
									  count(case  when P.Permission_Status=''Approved'' then 1 else null end) Approved,
									  count(case  when P.Permission_Status=''Forwarded'' then  1 else null end)Forwarded,
									  count(case  when P.Permission_Status=''Pending''  then 1 else null end) Pending
						  from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
						  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
			  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  '
			  SET @FifthBoard = @FifthBoard + ' where P.Permission_Date='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and P.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and PD.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End   
			  set @FifthBoard=@FifthBoard+')as A'
		end
		if(ISNULL(@FifthBoard,'')!='')
		begin
			  Execute(@FifthBoard)
		end
		else
		begin
			  select * from #ThirdDummyTableValue
		end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
	drop table #EmpDesignation      
	drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetDashboardInformation '', '2020/07/20', '2020/07/20',0,0,0,'SuperAdmin','0','0'
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]
      @EMPLOYEECODEID	NVARCHAR(MAX) = NULL,
      @FROMDATE			DATETIME,
      @TODATE			DATETIME,
      @Session			INT,
      @ShiftID			INT,
      @ParentID			INT,
      @UserGroupName	NVARCHAR(100),
      @GradeLevel		NVARCHAR(20),
      @empId			NVARCHAR(MAX)
AS
BEGIN 
	set nocount on;	
	Declare @FromdateString nvarchar(20)
	declare @todat			nvarchar(20);
	Declare @NoShiftID int
	select @NoShiftID=Shift_Id from TA_Tbl_Shift where Level_Id=0 and Shift_ShortName='NOS'
	set @todat=GETDATE();
	if @FROMDATE=''
	begin
		  set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(nvarchar(20),DATEPART(month,getdate()))+'-'+
		  case when len(CONVERT(nvarchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,GETDATE()))
		  else CONVERT(nvarchar(20),DATEPART(D,GETDATE())) end
	end   
	else
	begin
		set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(nvarchar(20),DATEPART(month,@fromdate))+'-'+
		case when len(CONVERT(nvarchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,@fromdate))
		else CONVERT(nvarchar(20),DATEPART(D,@fromdate)) end
	end
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	Create table #FirstTableValue(TOPIC nvarchar(100),ValueCount int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #SecondDummyTableValue(TOPIC nvarchar(100),Count int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #ThirdDummyTableValue(Approval nvarchar(100),Approved int,Forwarded int,Pending nvarchar(100),ApprovedPercent nvarchar(30),ForwardedPercent nvarchar(30),PendingPercent nvarchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		select @groupid=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',''
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	Declare @sqlEmpLevel nvarchar(4000) 
	set @sqlEmpLevel=
	'insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and emp.Employee_Code_Id<>''18000000''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) and EL.LevelId is not null'    
	if(@isReportingto > 0)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) '  
		END   
	if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and ELevel.EmployeeId in ('+CAST(@empId as nvarchar(10))+')'
		END   
	execute(@sqlEmpLevel)
	--select * from #EmpLevel
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeecountQuery nvarchar(4000)
	Declare @EmployeePresentcountQuery nvarchar(4000)     
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode='Present' or ANAttendanceCode='Present') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  WHERE P.DATE=@FromdateString
			  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
	
	
	Declare @FirstBoard		nvarchar(MAX)
	Declare @FirstBoard1	nvarchar(MAX)
	Declare @SecondBoard	nvarchar(MAX)
	Declare @ThirdBoard		nvarchar(MAX)
	Declare @FourthBoard	nvarchar(MAX)
	Declare @FifthBoard		nvarchar(MAX)
	Declare @sixthBoard		nvarchar(MAX)
	Declare @Present_Filters nvarchar(MAX)
	Declare @Absetn_Filters	nvarchar(MAX)
	Declare @Leave_Filters	nvarchar(MAX)
	Declare @Union			nvarchar(MAX)
	set @Union=' Union All '
	IF ((ISNULL(@FROMDATE, '') <> ''))
	BEGIN
		--First Gridview Control
		Declare @CommonJoinQueries nvarchar(MAX)         
		Declare @CommonSelectQueries nvarchar(MAX) 
		set @FirstBoard=''      
		Declare @Firstboardexists int
		set @Firstboardexists=0
		set @CommonJoinQueries=''
		set @CommonJoinQueries=@CommonJoinQueries+' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
		INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
		INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
		Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
		set @CommonSelectQueries=''
		set @CommonSelectQueries=@CommonSelectQueries+'select 
			  TOPIC,
			  COUNT,
			  HYPER,
			  REPORTNAME, 
			  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
						  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeeCount)+' * 100)),0))+'' %'' 
			  End'
		Declare @Filters nvarchar(MAX)
		set @Filters=''
		if(@ShiftID!=0)
		begin
			  set @Filters =@Filters+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
		end
		if(@UserGroupName<>'SuperAdmin')
		BEGIN
			  SET @Filters = @Filters + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END
		-- Added below line by manikandan.r on 16-11-2016
		-- if you remove below line it will bring wrong value for absent column.bug id:0035540
		if(@isReportingto > 0)
		BEGIN  
			  SET @Filters = @Filters + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
		End
		--Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  set @FirstBoard =@CommonSelectQueries+' as PercentageValue from 
			  (
					SELECT DISTINCT ''Present'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''MonthlyAttendance'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'       
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND (FNAttendanceCode=''Present'' or ANAttendanceCode=''PRESENT''or (FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (intime<>''00:00'' or outtime<>''00:00''))
					or (FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' and (intime<>''00:00'' or outtime<>''00:00'')))
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Present'
			  set @Firstboardexists=1
		end
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard =@FirstBoard+@CommonSelectQueries+' as AbsenteesPercent from 
			  (
					SELECT DISTINCT ''Absent'' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''Absentees'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
					set @FirstBoard=@FirstBoard+@CommonJoinQueries        
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND 
					(ANAttendanceCode=''ABSENT'' AND FNAttendanceCode=''Absent'') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Absent'
			  set @Firstboardexists=1
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin
			  declare @LeaveCount nvarchar(MAX)
			  --Getting Leave Data          
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+' as LeavePercent from 
			  (
					SELECT DISTINCT ''Approved Leave'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''Leave_Angler'' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P'        
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND 
					(
						  FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') or
						  ANAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'')
					)
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Leave'
			  set @Firstboardexists=1
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as OnDutyPercent from (
			  SELECT DISTINCT ''Approved OnDuty'' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''OnDuty'' AS REPORTNAME 
			  FROM Ta_Tbl_ManualTimeEntry M
			  inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
			  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and 
			  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
			  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) '
			  SET @FirstBoard = @FirstBoard + ' WHERE (M.ManualTimeEntry_InDate >= '''+convert(nvarchar(MAX),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(nvarchar(MAX),@FromdateString)+''') 
			  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''Approved'' And OD.Onduty_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as OnDuty'
			  set @Firstboardexists=1
		end
		--Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as PunctualityPercent from (
			  SELECT DISTINCT ''Punctuality'' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''Punctuality'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)=0 AND 
			  (ANAttendanceCode<>''Weekly Off'' or FNAttendanceCode<>''Weekly Off'') AND (p.LateIn=''00:00'' and p.InTime <> ''00:00'')
			  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Punctuality'
			  set @Firstboardexists=1
		end
		--Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '  as RawDataPercent from (
			  Select ''Attendance Summary'' As TOPIC,COUNT(P.DATE) [COUNT],
			  6 as HYPER,''AttendanceSummary'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''           
			  set @FirstBoard=@FirstBoard+@Filters+ ') as Attendance'
		end
		if(ISNULL(@FirstBoard,'')!='')
		begin
			  set @FirstBoard='insert into #FirstTableValue ' + @FirstBoard
			  Execute(@FirstBoard)
		end
		select * from #FirstTableValue
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		--Second Table
		--Getting Late Entry Data
		Declare @WhereFilter nvarchar(MAX)
		set @ThirdBoard=''
		Declare @ThirdBoardvalue int
		set @ThirdBoardvalue =0
		set @WhereFilter =' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
		((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) 
		and E.Employee_Code_Id<>''18000000'''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
		begin
			  set @ThirdBoard='  
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' 
					End as Percentage from (
			  SELECT DISTINCT ''Late Entry'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''LateEntry'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Early Exit Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+' 
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Early Exit'' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''EarlyExit'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + 'WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(EarlyOutMins,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Less Hours worked Data
		--Getting Shift Not allocated Employee Record
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select	TOPIC,
						COUNT,
						HYPER,
						REPORTNAME,
						Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
						Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End as 
						Percentage from 
						(                   
							SELECT  DISTINCT ''Shift Not Allocated'' AS TOPIC, 
									isnull(sum(case when (isnull(P.Shift_id,''0'')=0 or isnull(P.Shift_id,''0'')=''' + CONVERT(varchar(20),@NoShiftID) +''') then 1 else 0 end),0) [COUNT],
									3 AS HYPER, 
									''Shift Not Allocated'' AS REPORTNAME 
									FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''')'
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Approved Overtime Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Approved Over Time'' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''OverTime'' AS REPORTNAME 
			  FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '  WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''Approved'' And E.CompOff_Eligible=0 And E.OT_Eligible=1 '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1 
		end         
		--Getting Discrepancy Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME,  
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(DistinctCOUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage from 
			  ( 
					SELECT      DISTINCT ''Discrepancy'' AS TOPIC, 
								COUNT(C.Clk_EmpId) [COUNT],
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''Discrepancy'' AS REPORTNAME 
					FROM ta_tbl_clockdetails C
					Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
			  SET @ThirdBoard = @ThirdBoard + '  WHERE (C.Clk_Date ='''+convert(nvarchar(MAX),@FromdateString)+''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+') as A'
			  set @ThirdBoardvalue=1 
		end
		--Getting Non processed data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME, 
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage 
			  from(
						  Select      ''Non Processed Record'' As TOPIC,
									  COUNT(*)[COUNT],
									  COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
									  6 as HYPER,
									  ''Non Process'' AS REPORTNAME 
						  FROM TA_Tbl_Clk_RawData C           
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  '
			  SET @ThirdBoard = @ThirdBoard + ' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE ='''+convert(nvarchar(MAX),@FromdateString)+''''
			  set @ThirdBoard=@ThirdBoard+') as A'
		end
		--Execute(@ThirdBoard)
		if(ISNULL(@ThirdBoard,'')!='')
		begin
			--print (@ThirdBoard)
			Execute(@ThirdBoard)
		end
		else
		begin
			select * from #SecondDummyTableValue
		end
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		Declare @SecondBoardValue int
		set @SecondBoardValue=0
		set @FifthBoard=' '
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
		begin
			set @FifthBoard=@FifthBoard+'
			select 
				  ''Leave'' as Approval,
				  Approved,
				  Forwarded,
				  Pending,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ApprovedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ForwardedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as PendingPercent from
			(
					select      
								count(case  when L.Status=''Approved'' then 1  end)Approved,
								count(case  when L.Status=''Forwarded'' then 1 end)Forwarded,
								count(case  when L.Status=''Pending''  then 1  end)Pending
					from TA_Tbl_LeaveApplication L 
					Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
					Left outer join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=e.SwipeCardNo and P.Date=''' + CONVERT(nvarchar(MAX),@FromdateString) +''')'
                       SET @FifthBoard = @FifthBoard + '  where 
					(
						(''' + CONVERT(nvarchar(MAX),@FromdateString) +''' between L.Leave_FromDate and L.Leave_ToDate)
						
					) 
					and L.IsDeleted=0'
					if(@ShiftID!=0)
						  begin
								set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
						  end               
					if(@UserGroupName<>'SuperAdmin')
						  BEGIN
								SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
						  END
					if(@isReportingto > 0)
					BEGIN  
						  SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
					End         
					set @FifthBoard=@FifthBoard+') as a'
					set @SecondBoardValue=1                         
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+ ' select 
					''Onduty'' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),(Approved*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ApprovedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ForwardedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as PendingPercent from
					(
								select                              
								count(case  when (M.ManualTimeEntry_Status =''Approved'' and OD.Onduty_Status =''Approved'') then 1 else null end) Approved,
								count(case  when (M.ManualTimeEntry_Status=''Forwarded'' and OD.Onduty_Status=''Forwarded'') then 1 else null end) Forwarded,
								count(case  when (M.ManualTimeEntry_Status=''Pending'' and OD.Onduty_Status=''Pending'')  then 1 else null end)  Pending
								from Ta_Tbl_ManualTimeEntry M 
								inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
								Inner join TA_Tbl_Employee E 
								on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
								Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
								INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
								INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
								Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
								----Newly added below left outer instead of innner join 13-Feb-2020
								Left Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
								(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
								(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  '
			  SET @FifthBoard = @FifthBoard + ' where M.IsOnDuty=1 and M.isDeleted=0 and
			  M.ManualTimeEntry_InDate<='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and 
			  M.ManualTimeEntry_OutDate>='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and M.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End               
			  set @FifthBoard=@FifthBoard+') as B '
			  set @SecondBoardValue=1 
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+' select ''Permission'' as Approval,
						  Approved,
					Forwarded,
					Pending,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ApprovedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ForwardedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as PendingPercent from
			  (
						  select 
									  count(case  when P.Permission_Status=''Approved'' then 1 else null end) Approved,
									  count(case  when P.Permission_Status=''Forwarded'' then  1 else null end)Forwarded,
									  count(case  when P.Permission_Status=''Pending''  then 1 else null end) Pending
						  from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
						  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
			  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  '
			  SET @FifthBoard = @FifthBoard + ' where P.Permission_Date='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and P.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and PD.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End   
			  set @FifthBoard=@FifthBoard+')as A'
		end
		if(ISNULL(@FifthBoard,'')!='')
		begin
			  Execute(@FifthBoard)
		end
		else
		begin
			  select * from #ThirdDummyTableValue
		end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
	drop table #EmpDesignation      
	drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation_Product]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetDashboardInformation '', '2020/07/20', '2020/07/20',0,0,0,'SuperAdmin','0','0'
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetDashboardInformation_Product]
      @EMPLOYEECODEID	NVARCHAR(MAX) = NULL,
      @FROMDATE			DATETIME,
      @TODATE			DATETIME,
      @Session			INT,
      @ShiftID			INT,
      @ParentID			INT,
      @UserGroupName	NVARCHAR(100),
      @GradeLevel		NVARCHAR(20),
      @empId			NVARCHAR(MAX)
AS
BEGIN 
	set nocount on;	
	Declare @FromdateString nvarchar(20)
	declare @todat			nvarchar(20);
	Declare @NoShiftID int
	select @NoShiftID=Shift_Id from TA_Tbl_Shift where Level_Id=0 and Shift_ShortName='NOS'
	select @NoShiftID=isnull(@NoShiftID,0)
	set @todat=GETDATE();
	if @FROMDATE=''
	begin
		  set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(nvarchar(20),DATEPART(month,getdate()))+'-'+
		  case when len(CONVERT(nvarchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,GETDATE()))
		  else CONVERT(nvarchar(20),DATEPART(D,GETDATE())) end
	end   
	else
	begin
		set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(nvarchar(20),DATEPART(month,@fromdate))+'-'+
		case when len(CONVERT(nvarchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(nvarchar(20),DATEPART(D,@fromdate))
		else CONVERT(nvarchar(20),DATEPART(D,@fromdate)) end
	end
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	Create table #FirstTableValue(TOPIC nvarchar(100),ValueCount int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #SecondDummyTableValue(TOPIC nvarchar(100),Count int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #ThirdDummyTableValue(Approval nvarchar(100),Approved int,Forwarded int,Pending nvarchar(100),ApprovedPercent nvarchar(30),ForwardedPercent nvarchar(30),PendingPercent nvarchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		select @groupid=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',''
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	Declare @sqlEmpLevel nvarchar(4000) 
	set @sqlEmpLevel=
	'insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and emp.Employee_Code_Id<>''18000000''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) and EL.LevelId is not null'    
	if(@isReportingto > 0)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) '  
		END   
	if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + ' and ELevel.EmployeeId in ('+CAST(@empId as nvarchar(10))+')'
		END   
	execute(@sqlEmpLevel)
	--select * from #EmpLevel
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeecountQuery nvarchar(4000)
	Declare @EmployeePresentcountQuery nvarchar(4000)     
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode='Present' or ANAttendanceCode='Present') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  WHERE P.DATE=@FromdateString
			  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
	
	
	Declare @FirstBoard		nvarchar(MAX)
	Declare @FirstBoard1	nvarchar(MAX)
	Declare @SecondBoard	nvarchar(MAX)
	Declare @ThirdBoard		nvarchar(MAX)
	Declare @FourthBoard	nvarchar(MAX)
	Declare @FifthBoard		nvarchar(MAX)
	Declare @sixthBoard		nvarchar(MAX)
	Declare @Present_Filters nvarchar(MAX)
	Declare @Absetn_Filters	nvarchar(MAX)
	Declare @Leave_Filters	nvarchar(MAX)
	Declare @Union			nvarchar(MAX)
	set @Union=' Union All '
	IF ((ISNULL(@FROMDATE, '') <> ''))
	BEGIN
		--First Gridview Control
		Declare @CommonJoinQueries nvarchar(MAX)         
		Declare @CommonSelectQueries nvarchar(MAX) 
		set @FirstBoard=''      
		Declare @Firstboardexists int
		set @Firstboardexists=0
		set @CommonJoinQueries=''
		set @CommonJoinQueries=@CommonJoinQueries+' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
		INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
		INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
		Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
		set @CommonSelectQueries=''
		set @CommonSelectQueries=@CommonSelectQueries+'select 
			  TOPIC,
			  COUNT,
			  HYPER,
			  REPORTNAME, 
			  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
						  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeeCount)+' * 100)),0))+'' %'' 
			  End'
		Declare @Filters nvarchar(MAX)
		set @Filters=''
		if(@ShiftID!=0)
		begin
			  set @Filters =@Filters+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
		end
		if(@UserGroupName<>'SuperAdmin')
		BEGIN
			  SET @Filters = @Filters + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END
		-- Added below line by manikandan.r on 16-11-2016
		-- if you remove below line it will bring wrong value for absent column.bug id:0035540
		if(@isReportingto > 0)
		BEGIN  
			  SET @Filters = @Filters + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
		End
		--Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  set @FirstBoard =@CommonSelectQueries+' as PercentageValue from 
			  (
					SELECT DISTINCT ''Present'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''MonthlyAttendance'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'       
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND (FNAttendanceCode=''Present'' or ANAttendanceCode=''PRESENT''or (FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (intime<>''00:00'' or outtime<>''00:00''))
					or (FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' and (intime<>''00:00'' or outtime<>''00:00'')))
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Present'
			  set @Firstboardexists=1
		end
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard =@FirstBoard+@CommonSelectQueries+' as AbsenteesPercent from 
			  (
					SELECT DISTINCT ''Absent'' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''Absentees'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
					set @FirstBoard=@FirstBoard+@CommonJoinQueries        
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND 
					(ANAttendanceCode=''ABSENT'' AND FNAttendanceCode=''Absent'') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Absent'
			  set @Firstboardexists=1
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin
			  declare @LeaveCount nvarchar(MAX)
			  --Getting Leave Data          
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+' as LeavePercent from 
			  (
					SELECT DISTINCT ''Approved Leave'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''Leave_Angler'' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P'        
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') 
					AND 
					(
						  FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') or
						  ANAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'')
					)
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
					and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as Leave'
			  set @Firstboardexists=1
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as OnDutyPercent from (
			  SELECT DISTINCT ''Approved OnDuty'' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''OnDuty'' AS REPORTNAME 
			  FROM Ta_Tbl_ManualTimeEntry M
			  inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
			  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and 
			  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
			  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) '
			  SET @FirstBoard = @FirstBoard + ' WHERE (M.ManualTimeEntry_InDate >= '''+convert(nvarchar(MAX),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  <= '''+convert(nvarchar(MAX),@FromdateString)+''') 
			  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''Approved'' And OD.Onduty_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''                       
			  set @FirstBoard=@FirstBoard+@Filters+') as OnDuty'
			  set @Firstboardexists=1
		end
		--Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as PunctualityPercent from (
			  SELECT DISTINCT ''Punctuality'' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''Punctuality'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)=0 AND 
			  (ANAttendanceCode<>''Weekly Off'' or FNAttendanceCode<>''Weekly Off'') AND (p.LateIn=''00:00'' and p.InTime <> ''00:00'')
			  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and E.Employee_Code_Id<>''18000000'''
			  set @FirstBoard=@FirstBoard+@Filters+') as Punctuality'
			  set @Firstboardexists=1
		end
		--Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '  as RawDataPercent from (
			  Select ''Attendance Summary'' As TOPIC,COUNT(P.DATE) [COUNT],
			  6 as HYPER,''AttendanceSummary'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
			  and E.Employee_Code_Id<>''18000000'''           
			  set @FirstBoard=@FirstBoard+@Filters+ ') as Attendance'
		end
		if(ISNULL(@FirstBoard,'')!='')
		begin
			  set @FirstBoard='insert into #FirstTableValue ' + @FirstBoard
			  Execute(@FirstBoard)
		end
		select * from #FirstTableValue
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		--Second Table
		--Getting Late Entry Data
		Declare @WhereFilter nvarchar(MAX)
		set @ThirdBoard=''
		Declare @ThirdBoardvalue int
		set @ThirdBoardvalue =0
		set @WhereFilter =' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
		((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) 
		and E.Employee_Code_Id<>''18000000'''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
		begin
			  set @ThirdBoard='  
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' 
					End as Percentage from (
			  SELECT DISTINCT ''Late Entry'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''LateEntry'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE ='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(LATEINMINS,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Early Exit Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+' 
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Early Exit'' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''EarlyExit'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + 'WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(EarlyOutMins,0)<>0 '
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Less Hours worked Data
		--Getting Shift Not allocated Employee Record
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select	TOPIC,
						COUNT,
						HYPER,
						REPORTNAME,
						Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
						Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End as 
						Percentage from 
						(                   
							SELECT  DISTINCT ''Shift Not Allocated'' AS TOPIC, 
									isnull(sum(case when (isnull(P.Shift_id,''0'')=0 or isnull(P.Shift_id,''0'')=''' + CONVERT(varchar(20),@NoShiftID) +''') then 1 else 0 end),0) [COUNT],
									3 AS HYPER, 
									''Shift Not Allocated'' AS REPORTNAME 
									FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''')'
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1
		end
		--Getting Approved Overtime Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
					as Percentage from (                
			  SELECT DISTINCT ''Approved Over Time'' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''OverTime'' AS REPORTNAME 
			  FROM TA_TBL_PROCESSEDDATA P '
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '  WHERE (P.DATE='''+convert(nvarchar(MAX),@FromdateString)+''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''Approved'' And E.CompOff_Eligible=0 And E.OT_Eligible=1 '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
			  set @ThirdBoardvalue=1 
		end         
		--Getting Discrepancy Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME,  
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(DistinctCOUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage from 
			  ( 
					SELECT      DISTINCT ''Discrepancy'' AS TOPIC, 
								COUNT(C.Clk_EmpId) [COUNT],
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''Discrepancy'' AS REPORTNAME 
					FROM ta_tbl_clockdetails C
					Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
			  SET @ThirdBoard = @ThirdBoard + '  WHERE (C.Clk_Date ='''+convert(nvarchar(MAX),@FromdateString)+''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) '
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+') as A'
			  set @ThirdBoardvalue=1 
		end
		--Getting Non processed data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME, 
						  Case  when '+convert(nvarchar(10),@EmployeePresentcount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/'+convert(nvarchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
									  as Percentage 
			  from(
						  Select      ''Non Processed Record'' As TOPIC,
									  COUNT(*)[COUNT],
									  COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
									  6 as HYPER,
									  ''Non Process'' AS REPORTNAME 
						  FROM TA_Tbl_Clk_RawData C           
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  '
			  SET @ThirdBoard = @ThirdBoard + ' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE ='''+convert(nvarchar(MAX),@FromdateString)+''''
			  set @ThirdBoard=@ThirdBoard+') as A'
		end
		--Execute(@ThirdBoard)
		if(ISNULL(@ThirdBoard,'')!='')
		begin
			--print (@ThirdBoard)
			Execute(@ThirdBoard)
		end
		else
		begin
			select * from #SecondDummyTableValue
		end
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		Declare @SecondBoardValue int
		set @SecondBoardValue=0
		set @FifthBoard=' '
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
		begin
			set @FifthBoard=@FifthBoard+'
			select 
				  ''Leave'' as Approval,
				  Approved,
				  Forwarded,
				  Pending,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ApprovedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as ForwardedPercent,
				  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
				  End as PendingPercent from
			(
					select      
								count(case  when L.Status=''Approved'' then 1  end)Approved,
								count(case  when L.Status=''Forwarded'' then 1 end)Forwarded,
								count(case  when L.Status=''Pending''  then 1  end)Pending
					from TA_Tbl_LeaveApplication L 
					Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
					Left outer join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=e.SwipeCardNo and P.Date=''' + CONVERT(nvarchar(MAX),@FromdateString) +''')'
                       SET @FifthBoard = @FifthBoard + '  where 
					(
						(''' + CONVERT(nvarchar(MAX),@FromdateString) +''' between L.Leave_FromDate and L.Leave_ToDate)
						
					) 
					and L.IsDeleted=0'
					if(@ShiftID!=0)
						  begin
								set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
						  end               
					if(@UserGroupName<>'SuperAdmin')
						  BEGIN
								SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
						  END
					if(@isReportingto > 0)
					BEGIN  
						  SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
					End         
					set @FifthBoard=@FifthBoard+') as a'
					set @SecondBoardValue=1                         
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+ ' select 
					''Onduty'' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),(Approved*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ApprovedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as ForwardedPercent,
					Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
					End as PendingPercent from
					(
								select                              
								count(case  when (M.ManualTimeEntry_Status =''Approved'' and OD.Onduty_Status =''Approved'') then 1 else null end) Approved,
								count(case  when (M.ManualTimeEntry_Status=''Forwarded'' and OD.Onduty_Status=''Forwarded'') then 1 else null end) Forwarded,
								count(case  when (M.ManualTimeEntry_Status=''Pending'' and OD.Onduty_Status=''Pending'')  then 1 else null end)  Pending
								from Ta_Tbl_ManualTimeEntry M 
								inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
								Inner join TA_Tbl_Employee E 
								on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
								Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
								INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
								INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
								Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
								----Newly added below left outer instead of innner join 13-Feb-2020
								Left Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
								(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
								(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  '
			  SET @FifthBoard = @FifthBoard + ' where M.IsOnDuty=1 and M.isDeleted=0 and
			  M.ManualTimeEntry_InDate<='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and 
			  M.ManualTimeEntry_OutDate>='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and M.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End               
			  set @FifthBoard=@FifthBoard+') as B '
			  set @SecondBoardValue=1 
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+' select ''Permission'' as Approval,
						  Approved,
					Forwarded,
					Pending,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ApprovedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as ForwardedPercent,
						  Case  when '+convert(nvarchar(10),@EmployeeCount)+'=0 then ''0 %''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/'+convert(nvarchar(10),@EmployeeCount)+')*100),0))+'' %'' 
						  End as PendingPercent from
			  (
						  select 
									  count(case  when P.Permission_Status=''Approved'' then 1 else null end) Approved,
									  count(case  when P.Permission_Status=''Forwarded'' then  1 else null end)Forwarded,
									  count(case  when P.Permission_Status=''Pending''  then 1 else null end) Pending
						  from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
						  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
			  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  '
			  SET @FifthBoard = @FifthBoard + ' where P.Permission_Date='''+ CONVERT(nvarchar(MAX),@FromdateString) +''' and P.IsDeleted=0'
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+' and PD.Shift_Id='+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>'SuperAdmin')
					BEGIN
						  SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
			  End   
			  set @FifthBoard=@FifthBoard+')as A'
		end
		if(ISNULL(@FifthBoard,'')!='')
		begin
			  Execute(@FifthBoard)
		end
		else
		begin
			  select * from #ThirdDummyTableValue
		end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
	drop table #EmpDesignation      
	drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDateOfJoining]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Proc_TA_GetDateOfJoining 
--	Modified By		:	Manjula.P
--	Modified On		:	26-Apr-2014
--	Descriptions	:	Modified this procedure from PRODUCT for ANGER migration
CREATE PROCEDURE [dbo].[Proc_TA_GetDateOfJoining]
(
   @Employee_Code_Id NVARCHAR(10),
   @xml xml,
   @ManualEntryDate varchar(20),
   @Parameter varchar(1)
)
AS
BEGIN 
  if(@Parameter = 'S')
	BEGIN
	  SELECT DateOfJoining FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id AND IsDeleted = 0
	END
  else if(@Parameter = 'G')
	BEGIN
	  Declare @Index int
	  Set @Index = 0;
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  select E.Employee_Id as EmployeeAutoId
		  from OpenXML(@Index, '/NewDataSet/Table')
		  With (EmployeeId VARCHAR(250) 'EmployeeId') as xm 
		  inner join TA_Tbl_Employee E on E.Employee_Code_Id = xm.EmployeeId
		  where E.DateOfJoining > @ManualEntryDate
	  Exec sp_xml_removedocument @Index
	END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDatesWithFormat]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetDatesWithFormat '2015-04-01','2015-04-01'
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetDatesWithFormat]
	-- Add the parameters for the stored procedure here
	@From varchar(20),
	@To varchar(20)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
    -- Insert statements for procedure here
	SELECT case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR,CONVERT(datetime,@From),@dateFormat),' ','-') 
	else CONVERT(VARCHAR,CONVERT(datetime,@From), @dateFormat) end AS
	Date,case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR,CONVERT(datetime,@To),@dateFormat),' ','-') 
	else CONVERT(VARCHAR,CONVERT(datetime,@To), @dateFormat) end AS
	Date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDepartmentMailIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_GetDepartmentMailIds 5
CREATE PROCEDURE [dbo].[Proc_TA_GetDepartmentMailIds]
@LevelId int
AS
BEGIN
if(@LevelId<>0)
	BEGIN
	select Id,LevelId,name,ToMailIds,CCMailIds from TA_Tbl_LevelDetails Where ID=@LevelId and IsDeleted=0
	END
else
	BEGIN
	select Id,LevelId,name,ToMailIds,CCMailIds from TA_Tbl_LevelDetails Where LevelId=(Select max(LevelId) from TA_Tbl_LevelDetails where IsDeleted=0)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Proc_TA_GetDesignation
Modified By		:	Manjula.P
Modified On		:	15-Jan-2014
Descriptions	:	adding +'-'+ISNULL(LD.name,'') as TitleName for getting level with designation name in reports filters
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetDesignation]        
AS        
BEGIN      
		--Adding left joins for getting organization name with designation name by MAnjula.P on 15-Jan-2014       
        SELECT TitleId,replace(TitleName,'&amp;','&')+'-'+ISNULL(LD.name,'') as TitleName		
		FROM TA_Tbl_Title  T
		left join Ta_Tbl_levelDetails LD on LD.id=T.LevelID	
		WHERE  T.isdeleted=0 order by TitleName
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignationByLevelId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetDesignationByLevelId]        
@Leveld INT
AS        
BEGIN        
        SELECT TitleId,replace(TitleName,'&amp;','&') as TitleName FROM TA_Tbl_Title 
		WHERE LevelId = @Leveld and isdeleted=0 order by TitleName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDeviceLogTableDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <01-Jan-2020 15:43 PM>
-- Description:	<Get the Device Log Table Details with LastLog ID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDeviceLogTableDetails]
	@DeviceLog_TableName nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT tblAutoID,DeviceLog_TableName,LastLogID from Ta_Tbl_DeviceLogTableDetails where DeviceLog_TableName=rtrim(ltrim(@DeviceLog_TableName))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDevices]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <24_Aug_2019>
-- Description:	<This Procedure takes device ids from rawdata table for rawdata report for Filter dropdown>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDevices] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Select distinct CLK_DEVICEID as DeviceId from TA_Tbl_Clk_RawData order by CLK_DEVICEID asc

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_GetDiscrepanyForPayRollProcess '01/01/2012','12/19/2012','1','superadmin',0
CREATE   PROCEDURE [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]
(
    @FromDate Varchar(20),
    @EndDate Varchar(20),
    @Org_LevelID nVarchar(4000),
    @UserGroupName varchar(250),
	@ParentId int
)
AS
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	set @sqlQuery='select *,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, clk_date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, clk_date, '+cast(@dateFormat as varchar(100))+') end	as clk_Date1, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, clk_indate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, clk_indate, '+cast(@dateFormat as varchar(100))+') end as clk_InDate1, 
	right(clk_Intime,8) as clk_intime1,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, clk_outdate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, clk_outdate, '+cast(@dateFormat as varchar(100))+') end as clk_outDate1, 
	right(clk_outtime,8) as clk_outtime1 
	from TA_Tbl_ClockDetails inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_ClockDetails.Clk_CompId  where IsVoid=0 and (Clk_InDate is null or Clk_InTime is null or Clk_OutDate is null or Clk_OutTime is null) and Clk_Date between ''' + @FromDate + ''' and ''' + @EndDate + ''''
	exec(@sqlQuery)
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetDuplicatePunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_Ta_GetDuplicatePunches]
(
   @PunchInterval AS INT,
   @Type AS TINYINT
)
AS
BEGIN
IF (@Type = 0) -- IN
BEGIN
	SELECT DISTINCT a.Clk_id, a.Clk_empid, a.clk_date,(a.clk_InDate + a.clk_Intime) as InDateTime,(a.clk_OutDate+a.clk_OutTime) AS OutDateTime
	FROM ta_tbl_clockdetails a
	INNER JOIN ta_tbl_clockdetails b ON b.Clk_EmpId = a.Clk_EmpId AND b.Clk_Date = a.Clk_Date
	INNER JOIN Ta_Tbl_CollectRawDataCompanyLevelTemp crdTemp ON crdTemp.LevelId = a.Clk_CompId
	WHERE  
	((DATEDIFF(s,(a.Clk_InDate+a.Clk_InTime), (b.Clk_InDate+b.Clk_InTime)) <= @PunchInterval AND DATEDIFF(s,(a.Clk_InDate+a.Clk_InTime), (b.Clk_InDate+b.Clk_InTime)) > 0) OR
	(DATEDIFF(s,(b.Clk_InDate+b.Clk_InTime),(a.Clk_InDate+a.Clk_InTime) ) <= @PunchInterval AND DATEDIFF(s,(b.Clk_InDate+b.Clk_InTime),(a.Clk_InDate+a.Clk_InTime)) > 0) ) 
	AND a.IsVoid = 0 AND b.IsVoid = 0 AND a.clk_date between DateAdd(Month,-1,getdate()) and getdate()
	ORDER BY (a.clk_InDate + a.clk_Intime)
END
ELSE 
BEGIN 
	SELECT DISTINCT a.Clk_id, a.Clk_empid, a.clk_date,(a.clk_OutDate+a.clk_OutTime) AS OutDateTime, (a.clk_InDate + a.clk_Intime) as InDateTime
	FROM ta_tbl_clockdetails a
	INNER JOIN ta_tbl_clockdetails b ON b.Clk_EmpId = a.Clk_EmpId AND b.Clk_Date = a.Clk_Date
	INNER JOIN Ta_Tbl_CollectRawDataCompanyLevelTemp crdTemp ON crdTemp.LevelId = a.Clk_CompId
	WHERE 
	((DATEDIFF(s,(a.Clk_OutDate+a.Clk_OutTime), (b.Clk_OutDate+b.Clk_OutTime)) <= @PunchInterval AND DATEDIFF(s,(a.Clk_OutDate+a.Clk_OutTime), (b.Clk_OutDate+b.Clk_OutTime)) > 0) OR
	(DATEDIFF(s,(b.Clk_OutDate+b.Clk_OutTime),(a.Clk_OutDate+a.Clk_OutTime) ) <= @PunchInterval AND DATEDIFF(s,(b.Clk_OutDate+b.Clk_OutTime),(a.Clk_OutDate+a.Clk_OutTime)) > 0) ) 
	AND a.IsVoid = 0 AND b.IsVoid = 0 AND a.clk_date between DateAdd(Month,-1,getdate()) and getdate()
	ORDER BY (a.clk_OutDate + a.clk_Outtime)
	DELETE FROM Ta_Tbl_CollectRawDataCompanyLevelTemp
END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_GetEmailIds 's'
CREATE  PROCEDURE [dbo].[Proc_TA_GetEmailIds] 
@PrefixText as varchar(20)
 AS
SELECT Emp.EmailId,Emp.Employee_FirstName,LD.name FROM TA_Tbl_Employee Emp
INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EmployeeID=Emp.Employee_ID
INNER JOIN Ta_Tbl_levelDetails LD on EL.LevelId=LD.id 
WHERE Emp.Employee_Status = 1 AND Emp.IsDeleted = 0
AND Emp.Employee_Firstname <> 'Administrator' and Emp.EmailId like @PrefixText + '%'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIdsByUserGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the email ids based on the user group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailIdsByUserGroup] 
(
@LevelId int,
@DesignationId int,
@Parameter varchar(5)
)
AS
BEGIN
	SET NOCOUNT ON;
if(@Parameter='P')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_Planned CCP on CCP.CC_Planned=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCP.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END
if(@Parameter='U')
	BEGIN
	    select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_UnPlanned CCU on CCU.CC_UnPlanned=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCU.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END
if(@Parameter='O')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_Others CCO on CCO.CC_Others=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCO.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END  
-- Add by GOpinath for adding CCMail group users for OD Approval table 
if(@Parameter='OD')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_ODApproval CCOD on CCOD.CC_ODApproval=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCOD.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailReportNotSendedDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-02-2013
-- Description:	Get the Rescheduling Email Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailReportNotSendedDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ReScheduleid,id,FromMailId ,ToEmailIds ,CCEmailIds,EmailSubject ,Content ,Attachment from Ta_tbl_EmailReportNotSendedDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--select * from TA_tbl_EmailScheduleStatus
--Proc_TA_GetEmailSchedule 'Weekly'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailSchedule]
(
 @Frequency varchar(20) = 'Daily'
)
AS
BEGIN
			Select TA_Tbl_EmailScheduled_Employees.ScheduleId,dbo.GetUTCTimeZoneDateTime(TA_Tbl_EmailScheduled_Employees.Employee_id) as DateTimeUTC 
			into #UTCDateTimeTable
			from TA_Tbl_EmailScheduled_Employees 


	create table #TempEmailSchedule(ScheduleId int)
	if(@Frequency = 'Daily')
	BEGIN
			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Daily' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETUTCDATE(),101) as datetime) 

			select TA_Tbl_EmailSchedule.ScheduleId,#UTCDateTimeTable.DateTimeUTC from TA_Tbl_EmailSchedule
			inner join #UTCDateTimeTable on #UTCDateTimeTable.ScheduleId =TA_Tbl_EmailSchedule.ScheduleId
			where Frequency = 'Daily'
			and   #UTCDateTimeTable.DateTimeUTC >= cast((CONVERT(varchar(10),GETUTCDATE(),101) + ' '  + TimeToSend) as datetime)
			and TA_Tbl_EmailSchedule.ScheduleId not in (select scheduleId from #TempEmailSchedule)
			and IsDeleted = 0 and Enabled = 1

	END	
	else if(@Frequency = 'Weekly')
	BEGIN
			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Weekly' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETUTCDATE(),101) as datetime) 
			declare @WeekDay varchar(10)
			set @WeekDay = (select DATEname(DW,GETUTCDATE()))

			select TA_Tbl_EmailSchedule.ScheduleId,#UTCDateTimeTable.DateTimeUTC from TA_Tbl_EmailSchedule
			inner join #UTCDateTimeTable on #UTCDateTimeTable.ScheduleId =TA_Tbl_EmailSchedule.ScheduleId
			where Frequency = 'Weekly'
			and DayToSend = @WeekDay
			and   #UTCDateTimeTable.DateTimeUTC >= cast((CONVERT(varchar(10),GETUTCDATE(),101) + ' '  + TimeToSend) as datetime)
			and TA_Tbl_EmailSchedule.ScheduleId not in (select scheduleId from #TempEmailSchedule)
			and IsDeleted = 0 and Enabled = 1
	END
	else if(@Frequency = 'Monthly')
	BEGIN
			insert into #TempEmailSchedule 
			select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Monthly' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETUTCDATE(),101) as datetime) 
			declare @CurrentDate int
			set @CurrentDate = (select DATEPART(D,GETUTCDATE()))
			declare @LastDateOfCurrentMonth int
			set @LastDateOfCurrentMonth = (SELECT DATEPART ( D , DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETUTCDATE()))),
            DATEADD(MONTH, 1, GETUTCDATE()))))
			if(@CurrentDate = @LastDateOfCurrentMonth)
			BEGIN
				select TA_Tbl_EmailSchedule.ScheduleId,#UTCDateTimeTable.DateTimeUTC from TA_Tbl_EmailSchedule
				inner join #UTCDateTimeTable on #UTCDateTimeTable.ScheduleId =TA_Tbl_EmailSchedule.ScheduleId
				where Frequency = 'Monthly'
				and DateToSend >= @CurrentDate
				and   #UTCDateTimeTable.DateTimeUTC >= cast((CONVERT(varchar(10),GETUTCDATE(),101) + ' '  + TimeToSend) as datetime)
				and TA_Tbl_EmailSchedule.ScheduleId not in (select scheduleId from #TempEmailSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
			ELSE
			BEGIN
			--Print @CurrentDate
				select TA_Tbl_EmailSchedule.ScheduleId,#UTCDateTimeTable.DateTimeUTC from TA_Tbl_EmailSchedule
				inner join #UTCDateTimeTable on #UTCDateTimeTable.ScheduleId =TA_Tbl_EmailSchedule.ScheduleId
				where Frequency = 'Monthly'
				and DateToSend = @CurrentDate
					and   #UTCDateTimeTable.DateTimeUTC >= cast((CONVERT(varchar(10),GETUTCDATE(),101) + ' '  + TimeToSend) as datetime)
				and TA_Tbl_EmailSchedule.ScheduleId not in (select scheduleId from #TempEmailSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
	END
	drop table #TempEmailSchedule
END




--ALTER PROCEDURE [dbo].[Proc_TA_GetEmailSchedule]
--(
-- @Frequency varchar(20) = 'Monthly'
--)
--AS
--BEGIN
--	create table #TempEmailSchedule(ScheduleId int)
--	if(@Frequency = 'Daily')
--	BEGIN
--			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
--			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
--			where ES.Frequency = 'Daily' and Status=1
--			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			
--			select ScheduleId from TA_Tbl_EmailSchedule
--			where Frequency = 'Daily'
--			and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
--			and ScheduleId not in (select scheduleId from #TempEmailSchedule)
--			and IsDeleted = 0 and Enabled = 1
--	END	
--	else if(@Frequency = 'Weekly')
--	BEGIN
--			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
--			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
--			where ES.Frequency = 'Weekly' and Status=1
--			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
--			declare @WeekDay varchar(10)
--			set @WeekDay = (select DATEname(DW,GETDATE()))
--			select ScheduleId from TA_Tbl_EmailSchedule
--			where Frequency = 'Weekly'
--			and DayToSend = @WeekDay
--			and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
--			and ScheduleId not in (select scheduleId from #TempEmailSchedule)
--			and IsDeleted = 0 and Enabled = 1
--	END
--	else if(@Frequency = 'Monthly')
--	BEGIN
--			insert into #TempEmailSchedule 
--			select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
--			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
--			where ES.Frequency = 'Monthly' and Status=1
--			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
--			declare @CurrentDate int
--			set @CurrentDate = (select DATEPART(D,GETDATE()))
--			declare @LastDateOfCurrentMonth int
--			set @LastDateOfCurrentMonth = (SELECT DATEPART ( D , DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),
--            DATEADD(MONTH, 1, GETDATE()))))
--			if(@CurrentDate = @LastDateOfCurrentMonth)
--			BEGIN
--				select ScheduleId from TA_Tbl_EmailSchedule
--				where Frequency = 'Monthly'
--				and DateToSend >= @CurrentDate
--				and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
--				and ScheduleId not in (select scheduleId from #TempEmailSchedule)
--				and IsDeleted = 0 and Enabled = 1
--			END
--			ELSE
--			BEGIN
--			--Print @CurrentDate
--				select ScheduleId from TA_Tbl_EmailSchedule
--				where Frequency = 'Monthly'
--				and DateToSend = @CurrentDate
--				and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
--				and ScheduleId not in (select scheduleId from #TempEmailSchedule)
--				and IsDeleted = 0 and Enabled = 1
--			END
--	END
--	drop table #TempEmailSchedule
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetEmailScheduler_FilterDetails 14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails] 
	-- Add the parameters for the stored procedure here
	@scheduleId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	Declare @Filters varchar(max)
	Declare @Count int
	Declare @start int
	Declare @TempTable varchar(max)
	Declare @TempTableInsert varchar(max)
	Declare @TempFiltersvalue varchar(max)
	Declare @TempFiltersvalues varchar(max)
	set @TempTable='Create Table TempFinalFilters('
	set @TempTableInsert='Insert into TempFinalFilters values('
	set @start=1
	select @Filters=Filters  from TA_Tbl_EmailScheduleFilters where ScheduleId=@scheduleId
	select @Count=COUNT(*) from dbo.Split(@Filters,',')
	Create table #TempFilters(id int identity(1,1),Filters varchar(max))
	insert into #TempFilters select Value from dbo.Split(@Filters,',')
	--select * from #TempFilters
	while @start<=@Count 
	begin
		select @TempFiltersvalue=replace(substring(Filters,0,charindex('=',Filters)),'@',''),
		@TempFiltersvalues=replace(substring(Filters,charindex('=',Filters)+1,LEN(Filters)),'~',',')
		from #TempFilters where id=@start 
		if(@start!=@Count)
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max),'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''','
		end
	else
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max)'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''''
		end			
		set @start=@start+1
	end
	set @TempTable=@TempTable+')'
	set @TempTableInsert=@TempTableInsert+')'	
	Execute(@TempTable)
	Execute(@TempTableInsert)
	select * from TempFinalFilters
	Select ReportType From TA_Tbl_EmailScheduleFilters Where ScheduleId=@scheduleId
	drop table TempFinalFilters
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailScripts]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_GetEmailScripts  
Description		: Get ScriptText Based on the ScriptType  
Tables Included : TA_TBL_EmailScripts  
Created By		: Prabakaran  
Created On		: 20-Sep-07  
Modified By		:  
Modified On		:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailScripts]  
@ScriptType nvarchar(100)  
as  
BEGIN
	Select * from TA_TBL_EmailScripts where ScriptType=@ScriptType  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmpforShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  procedure [dbo].[Proc_TA_GetEmpforShift]    
(    
@EmpID INT    
)    
AS    
Begin
	SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + '' + Employee_LastName AS 'Employee Name' FROM TA_Tbl_Employee WHERE Employee_Id=@EmpID and 
	Isdeleted=0 and Employee_Firstname<>'Administrator' 
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAllocatedFencingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetEmployeeAllocatedFencingDetails @EmployeeId=33,@shiftDate='2023-07-20',@tag='EF'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeAllocatedFencingDetails] 
	-- Add the parameters for the stored procedure here
	@EmployeeId int,
	@shiftDate varchar(20),
	@tag char(3)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	
	Declare @CurrentYear int
	Declare @CurrentMonth int
	Declare @currentDate varchar(20)

	Declare @LandmarkValue varchar(20)
	Declare @TempLandmark as Table (LandmarkId int,Lat varchar(100),Long varchar(100))

	if(@tag='EF')
	begin
		print @tag

		Select @LandmarkValue=F.LandmarkId From TA_tbl_GeoFencingAllocation FA inner Join TA_tbl_Fencing F on F.FencingId=FA.FencingId where FA.EmployeeId=@EmployeeId and (@shiftDate between FA.FromDate and FA.Todate) 

		Declare @LandmarkID as Table (L_Id int)

		insert into @LandmarkID
		Select * From [dbo].[CSVToTable] (@LandmarkValue)
		
		Select id,LocationName,latitude,longitude From Ta_tbl_LandMarks l1 inner Join @LandmarkID l2 on l2.L_Id=l1.id 
	End
	Else IF(@tag='MS')
	Begin

		Select @LandmarkValue=F.LandmarkId From TA_tbl_GeoFencingAllocation FA inner Join TA_tbl_Fencing F on F.FencingId=FA.FencingId where FA.EmployeeId=@EmployeeId and (@shiftDate between FA.FromDate and FA.Todate)
		Declare @Landmark as Table (L_Id int)

		insert into @LandmarkID
		Select * From [dbo].[CSVToTable] (@LandmarkValue)
		
		Select id,LocationName,latitude,longitude From Ta_tbl_LandMarks l1 inner Join @Landmark l2 on l2.L_Id=l1.id 
	End


END

--Select * From TA_tbl_Fencing

--Select * From TA_tbl_GeoFencingAllocation FA inner Join TA_tbl_Fencing F on F.FencingId=FA.FencingId where ('2023-07-02' between FromDate and Todate)  and EmployeeId=33
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoId]
@Employee_Code_Id as nvarchar(30)
AS
BEGIN
	select Employee_Id,Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where Employee_Code_Id=@Employee_Code_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoIdForImport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoIdForImport]
@Employee_Code_Id as nvarchar(30)
AS
BEGIN
	select Employee_Id,Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where isdeleted=0 and employee_status=1 and Employee_Code_Id=@Employee_Code_Id 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeCodeID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeCodeID]
@Employee_ID as int
AS
BEGIN
	select Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where Employee_ID=@Employee_ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeCompanyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeCompanyID]

@loginEmployeeId int =45

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LevelId int 
   
   Select @LevelId=LevelId from TA_Tbl_Employeelevel where EmployeeId =@loginEmployeeId
   --Select Fun_TA_GetBranchName(@LevelId)
   Select  [dbo].[Func_TA_GetParentIds](@LevelId) as CompanyID

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 31-07-2014
-- Description:	To get the employee id from temporary shift allocation table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT EmployeeId FROM TA_Tbl_TempShiftAllocation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails]       
-- Proc_GetEmployeeDetails 'EIT02',1.2,1.2      
 -- Add the parameters for the stored procedure here      
 @CardNo VARCHAR(50)=NULL,
 @EmployeeName VARCHAR(100)=NULL,
 @EmployeeId VARCHAR(50)=NULL,
 @EmpCategory VARCHAR(100)=NULL,
 @EmployeeType VARCHAR(100)=NULL,
 @Designation VARCHAR(100)=NULL,
 @Gender VARCHAR(50)=NULL,
 @Month varchar(100)=NULL,
 @Year varchar(50)=NULL,
 @UserGroupName VARCHAR(250)=NULL,
 @GradeLevel VARCHAR(100)=NULL,
 @parentLevelId INT =NULL,
 @EmpId VARCHAR(50)=NULL,
 @PresentDays NUMERIC(18,1)=NULL,
 @Difference_Days NUMERIC(18,1)=NULL,
 @Status varchar(50)
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
    -- Insert statements for procedure here      
 IF @Status='Update'     
  BEGIN      
    UPDATE TA_Tbl_AttendenceData SET PresentDays=@PresentDays,Difference_Days=@Difference_Days      
    WHERE EmpId=@EmpId 
    SELECT 0     
   END      
  ELSE IF @Status='Select'  
  BEGIN     
 SELECT EmpId,PresentDays,OD,EL,CL,SL,LOP_Absent,Difference_Days FROM TA_Tbl_AttendenceData      
 END  
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_Blocking_Unblocking]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_GetEmployeeDetails_Blocking_Unblocking] 63,'B','0'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_Blocking_Unblocking]
	@ShiftId bigInt,
	@flag char(3),
	@isNightShift int
AS
BEGIN
	SET NOCOUNT ON;
	if(@flag='B')
	BEGIN
		if(@isNightShift=0)
		begin
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=0 and WeekWise=0 and QuarterWise=0 and ContinuousDayWise=0 )
		end
		else if(@isNightShift=1)
		BEGIN
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=DATEADD(d,-1, CONVERT(datetime, CONVERT(varchar(11), GETDATE())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=0 and WeekWise=0 and QuarterWise=0  and ContinuousDayWise=0)
		END
	END
	else if(@flag='UB')
	BEGIN
		if(@isNightShift=0)
		begin
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1 and WeekWise=0 and DayWise=0 and QuarterWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<CONVERT(datetime,CONVERT(varchar(11),getdate())))
			
		end
		else if(@isNightShift=1)
		BEGIN
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1 and WeekWise=0 and DayWise=0 and QuarterWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))=CONVERT(datetime,CONVERT(varchar(11),getdate())))
			
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_Blocking_Unblocking_25Feb2022]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_GetEmployeeDetails_Blocking_Unblocking] 63,'B','0'
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_Blocking_Unblocking_25Feb2022]
	@ShiftId bigInt,
	@flag char(3),
	@isNightShift int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @EmployeeIDs varchar(max)
	set @EmployeeIDs=''
	if(@flag='B')
	BEGIN
		--insert into testingBlocking values(@ShiftId,@flag,@isNightShift)
		if(@isNightShift=0)
		begin
			if(@ShiftId!=0)
			begin
				set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0 and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
				and pd.Employee_Code_Id!='' and isnull(pd.Employee_Code_Id,'')!=''
				order by isnull(outtime,'')
				if(@EmployeeIDs!='')
				begin
					select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
				end
				else
				begin
					select 'Empty' as employeeids,updateQuery=''
				end
				select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,ShiftDate=pd.Date,OutTime from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
				order by isnull(outtime,'')
			end
			--change the value from 188880 to 0 for no shift concepts..
			--commentted on 23feb2022 10 pm by manikandan.rr
			else if(@shiftid=188880)
			BEGIN
				set @ShiftId=188880
				Declare @AllowedMaxMin_AfterShiftEnd int
				set @AllowedMaxMin_AfterShiftEnd=0
				select @AllowedMaxMin_AfterShiftEnd=Daily_Hrs from Ta_tbl_PolicyConfiguration 
				Create table #TempPreviousDate(Employee_code_id varchar(20))
				Insert into #TempPreviousDate
				select E.Employee_Code_Id from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				inner join ta_tbl_shift s on pd.shift_id=s.Shift_Id
				where pd.ProcessFlag=1 and E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and Date=dateadd(d,-1,CONVERT(datetime, CONVERT(varchar(11), GETDATE())))
				and 'yes'=(
				case when RIGHT(s.Shift_StartTime,2)='PM' and RIGHT(s.Shift_EndTime,2)='AM' then 'Yes' 
				when RIGHT(s.Shift_StartTime,2)='PM' and
				Right(convert(varchar(20),convert(datetime,(case when DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,s.Shift_EndTime)='1900-01-02 00:00:00.000'
				then dateadd(d,-1,DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,s.Shift_EndTime))
				else DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,s.Shift_EndTime) end ))),2)='AM' then 'Yes'
				else 'No' end)
				set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where 
				--pd.ProcessFlag=1 and 
				E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=0 and WeekWise=0 and QuarterWise=0 and ContinuousDayWise=0 and daily=0)
				and pd.Employee_Code_Id not in(select Employee_code_id from #TempPreviousDate)
				and pd.Employee_Code_Id!='' and isnull(pd.Employee_Code_Id,'')!=''
				and(isnull(intime,'00:00')!='00:00' or isnull(OutTime,'00:00')!='00:00')
				order by isnull(outtime,'')
				if(@EmployeeIDs!='')
				begin
					select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
				end
				else
				begin
					select 'Empty' as employeeids,updateQuery=''
				end
				select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,ShiftDate=pd.Date from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where pd.ProcessFlag=1 and E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees 
				where DayWise=0 and WeekWise=0 and QuarterWise=0 and ContinuousDayWise=0 and daily=0)
				and pd.Employee_Code_Id not in(select Employee_code_id from #TempPreviousDate)
				and(isnull(intime,'00:00')!='00:00' or isnull(OutTime,'00:00')!='00:00')
				drop table #TempPreviousDate
			END
		end
		else if(@isNightShift=1)
		BEGIN
			Declare @AllowedMinMin_BeforeShiftStart int
			Declare @Shift_Starttime varchar(20)
			set @AllowedMinMin_BeforeShiftStart=120
			select  @Shift_Starttime=DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,shift_starttime) from ta_tbl_shift where shift_id=@ShiftId
			if(dateadd(d,0,@Shift_Starttime)>dateadd(d,0,substring(convert(varchar(20),getdate()),12,20)))
			begin
				set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0 and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=DATEADD(d,-1, CONVERT(datetime, CONVERT(varchar(11), GETDATE())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
				if(@EmployeeIDs!='')
				begin
					select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
				end
				else
				begin
					select 'Empty' as employeeids,updateQuery=''
				end
				select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,ShiftDate=pd.Date from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0 and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=DATEADD(d,-1, CONVERT(datetime, CONVERT(varchar(11), GETDATE())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			end
			else
			begin
				set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+''''  from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where pd.Employee_Code_Id='12345678459#' and(isnull(intime,'00:00')!='00:00' or isnull(OutTime,'00:00')!='00:00')
				order by isnull(outtime,'')
				if(@EmployeeIDs!='')
				begin
					select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
				end
				else
				begin
					select 'Empty' as employeeids,updateQuery=''
				end
			end
		END
	END
	--BNP means, blocking No punches employee records. Implemented on second enhancement by us
	ELSE IF(@flag='BNP')
	BEGIN
		if(@isNightShift=0)
		begin
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and (isnull(InTime,'00:00')='00:00' and ISNULL(OutTime,'00:00')='00:00')
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where daily=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
		end
		else if(@isNightShift=1)
		BEGIN
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where pd.ProcessFlag=1 and E.Isdeleted=0
			and (isnull(InTime,'00:00')='00:00' and ISNULL(OutTime,'00:00')='00:00')
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=DATEADD(d,-1, CONVERT(datetime, CONVERT(varchar(11), GETDATE())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where daily=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
		END
	END
	else if(@flag='UB')
	BEGIN
		if(@isNightShift=0)
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+Employee_Code_Id+''''  from
			(			
				--Daily hrs blocking Employees
				select Employee_Code_Id=pd.Employee_Code_Id from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1  and QuarterWise=0
				and WeekWise=0 and DayWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<=CONVERT(datetime,CONVERT(varchar(11),getdate())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
				union all  --Quarterly Overtime Employees
				select pd.Employee_Code_Id from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=0  and QuarterWise=1
				and WeekWise=0 and DayWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<CONVERT(datetime,CONVERT(varchar(11),getdate())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			)as final
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''N'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
			--List of employees to unblocking both daily and quarterly wise employees
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,shiftdate=pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Isdeleted=0 and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1  and QuarterWise=0
			and WeekWise=0 and DayWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<=CONVERT(datetime,CONVERT(varchar(11),getdate())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			union all
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,shiftdate=pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Isdeleted=0 and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=0  and QuarterWise=1
			and WeekWise=0 and DayWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<CONVERT(datetime,CONVERT(varchar(11),getdate())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1 
			and WeekWise=0 and DayWise=0 and QuarterWise=0 and CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))
			<=CONVERT(datetime,CONVERT(varchar(11),getdate()))
		end
		else if(@isNightShift=1)
		BEGIN
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+Employee_Code_Id+'''' 
			from
			(
				select Employee_Code_Id=pd.Employee_Code_Id
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1  and QuarterWise=0 and WeekWise=0 and DayWise=0 and 
				--i Changed this condition on 21-06-2022 01:13 pm. if employee camee previous day morning and next day night shift means, its not considered fro unblocking
				--CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))=CONVERT(datetime,CONVERT(varchar(11),getdate())))
				CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<=CONVERT(datetime,CONVERT(varchar(11),getdate())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
				union all
				select pd.Employee_Code_Id
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where E.Isdeleted=0
				and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
				and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
				and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=0  and QuarterWise=1 and WeekWise=0 and DayWise=0 and 
				--i Changed this condition on 21-06-2022 01:13 pm. if employee camee previous day morning and next day night shift means, its not considered fro unblocking
				--CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))=CONVERT(datetime,CONVERT(varchar(11),getdate())))
				CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))<=CONVERT(datetime,CONVERT(varchar(11),getdate())))
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1)
				and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			)as final
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''N'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,shiftdate=pd.Date from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=1  and QuarterWise=0 and WeekWise=0 and DayWise=0 and 
			CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))=CONVERT(datetime,CONVERT(varchar(11),getdate())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where QuarterWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
			union all
			select EmployeeCode=E.Employee_Code_Id,E.Employee_FirstName,shiftdate=pd.Date from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Isdeleted=0
			and isnull(E.InActive_Status,0)=0 and isnull(E.Hostel,0)=1
			and pd.Shift_Id=@ShiftId and Date=CONVERT(datetime, CONVERT(varchar(11), GETDATE()))
			and pd.Employee_Code_Id in(select b.EmployeeCard from Ta_tbl_BlockedEmployees b where Daily=0  and QuarterWise=1 and WeekWise=0 and DayWise=0 and 
			CONVERT(datetime,CONVERT(varchar(11),WhenBlocked_Daily))=CONVERT(datetime,CONVERT(varchar(11),getdate())))
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where DayWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1)
			and pd.Employee_Code_Id not in(select EmployeeCard from Ta_tbl_BlockedEmployees where ContinuousDayWise=1)
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.MANIKANDAN>
-- Create date: <01-APRIL-2019 04:39 PM>
-- Description:	<GET THE EMPLOYEE DETAILS FOR EMAIL TRIGGERING BASED ON THE SELECTION AND ACTIVE STATUS>
-- Proc_TA_GetEmployeeDetails_EmailTriggering_13Apr2022 23,5,'08:00','Y'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 2,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 3,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 4,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 5,'01:00'
--  exec Proc_TA_GetEmployeeDetails_EmailTriggering @Scheduleid=8,@Option=N'5',@Time=N'16:12'
--exec Proc_TA_GetEmployeeDetails_EmailTriggering @Scheduleid=8,@Option=N'5',@Time=N'16:14'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]
	@Scheduleid INT,
	@Option int,
	@Time varchar(5),
	@isReminder char(2)=null
AS
BEGIN
	SET NOCOUNT ON;
	Create table #TempEmployeeDetails(Autoid int identity(1,1),Employee_Code_Id varchar(50),EmailId varchar(200),ReportingTo varchar(10),Employee_ID bigint)
	Declare @ScheculeName varchar(max)
	Declare @reportID varchar(max)
	
	select @ScheculeName =ScheduleName,@reportID=ReportId from TA_Tbl_EmailSchedule where ScheduleId=@Scheduleid

	if(@ScheculeName='Warning Letter Late Entry' or @ScheculeName='Warning Letter Early Exit')
	BEGIN
		Declare @monthStartDate datetime
		Declare @monthEndDate datetime
		select @monthStartDate=DATEADD(month,DATEDIFF(month,0,getdate()),0),@monthEndDate=dateadd(d,-1,DATEADD(month,DATEDIFF(month,0,getdate())+1,0))
		Insert into #TempEmployeeDetails
		SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
		INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
		where ScheduleId=@Scheduleid
		and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')
		and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
		and (CONVERT(datetime,convert(varchar(11),SentDate)) between @monthStartDate and @monthEndDate) and Status=1)
	END
	ELSE
	BEGIN
		IF(@isReminder='N')
		BEGIN
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')
			and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
			and CONVERT(datetime,convert(varchar(11),SentDate))=CONVERT(datetime,convert(varchar(11),getdate())) and Status=1)
		END
		ELSE
		BEGIN
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')	
			
		END
	END	
	DECLARE @START INT
	SET @START=1
	DECLARE @TOTAL INT
	SELECT @TOTAL=COUNT(EMPLOYEE_CODE_ID) FROM #TEMPEMPLOYEEDETAILS

	IF(@reportID!=248 and @reportID!=249 and @isReminder='N')
	BEGIN
		

		WHILE @START<=@TOTAL
		BEGIN
			Declare @Employee_Code_id varchar(50)
			Declare @Shift_Id int

			SELECT @Shift_Id=Shift_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@Employee_Code_id
			and Date=CONVERT(datetime,CONVERT(varchar(11),GETDATE())) and ProcessFlag=1


			IF (@Shift_Id is not null and @Shift_Id<>'' and @Shift_Id<>0)
			BEGIN
				DECLARE @Shift_StartTime DATETIME
				DECLARE @Shift_EndTime DATETIME
				DECLARE @addAndSubtractvalue INT
				DECLARE @finalTimings DATETIME
				SELECT @Shift_StartTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_StartTime,@Shift_EndTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@Shift_Id AND Isdeleted=0
				set @addAndSubtractvalue=CONVERT(int,SUBSTRING(@Time,0,charindex(':',@time)))*60+CONVERT(int,SUBSTRING(@Time,charindex(':',@time)+1,LEN(@time)))


				--AFTER SHIFT START TIME
				IF (@Option=1 OR @Option=2)
				BEGIN
					IF(@Option=2)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END			
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_StartTime)
				END		
				--AFTER SHIFT END TIME
				ELSE IF (@Option=3 OR @Option=4)
				BEGIN
					IF(@Option=4)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END	
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_EndTime)			
				END
				--CUSTOM TIMINGS
				ELSE IF @Option=5
				BEGIN		
					--SELECT DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))

					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
				END
				--SELECT @Shift_StartTime
				if(@finalTimings<=GETDATE())
				BEGIN
					set @START=@START+1
					continue;
				END
				ELSE
				BEGIN
					Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
				END
			END
			ELSE
			BEGIN
				Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			END		
			set @START=@START+1
		END
	end
	ELSE
	BEGIN
		--select * from #TEMPEMPLOYEEDETAILS
		Delete from #TempEmployeeDetails where Employee_Code_Id not in(
		select TE.Employee_Code_Id from #TempEmployeeDetails TE
		left outer join TA_Tbl_Employee E on TE.Employee_ID=E.Reporting_To
		where isnull(E.Reporting_To,0)!=0)
	END

	--UTC Time Zone for Employee Wise Country Datetime Select -- // Hariharan.J >> 02-02-2024 //
			
--select * from #TEMPEMPLOYEEDETAILS

		Select Autoid,#TEMPEMPLOYEEDETAILS.Employee_Code_Id,#TEMPEMPLOYEEDETAILS.EmailId,#TEMPEMPLOYEEDETAILS.ReportingTo ,
		#TEMPEMPLOYEEDETAILS.Employee_Id,LEFT(CONVERT(VARCHAR, [dbo].[GetUTCTimeZoneDateTime](TA_Tbl_Employee.Employee_Id), 108), 5) as EmployeeLiveCountryTime 
		,Right (CONVERT(Varchar, [dbo].[GetUTCTimeZoneDateTime](TA_Tbl_Employee.Employee_Id),111),10) AS EmployeeCountryDate 
		into #TimeZoneCheck
		from TA_Tbl_Employee  
		inner join #TEMPEMPLOYEEDETAILS on #TEMPEMPLOYEEDETAILS.Employee_ID = TA_Tbl_Employee.Employee_Id
		
		Select * from #TimeZoneCheck where EmployeeCountryDate = CONVERT(DATE,GETUTCDATE()) and EmployeeLiveCountryTime >= @Time

		--Select CONVERT(DATE,GETUTCDATE())

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering_13Apr2022]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.MANIKANDAN>
-- Create date: <01-APRIL-2019 04:39 PM>
-- Description:	<GET THE EMPLOYEE DETAILS FOR EMAIL TRIGGERING BASED ON THE SELECTION AND ACTIVE STATUS>
-- Proc_TA_GetEmployeeDetails_EmailTriggering_13Apr2022 23,5,'08:00','Y'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 2,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 3,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 4,'01:00'
-- Proc_TA_GetEmployeeDetails_EmailTriggering 5,'01:00'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering_13Apr2022]
	@Scheduleid INT,
	@Option int,
	@Time varchar(5),
	@isReminder char(2)
AS
BEGIN
	SET NOCOUNT ON;
	Create table #TempEmployeeDetails(Autoid int identity(1,1),Employee_Code_Id varchar(50),EmailId varchar(200),ReportingTo varchar(10),Employee_ID bigint)
	Declare @ScheculeName varchar(max)
	Declare @reportID varchar(max)
	
	select @ScheculeName =ScheduleName,@reportID=ReportId from TA_Tbl_EmailSchedule where ScheduleId=@Scheduleid
	if(@ScheculeName='Warning Letter Late Entry' or @ScheculeName='Warning Letter Early Exit')
	BEGIN
		Declare @monthStartDate datetime
		Declare @monthEndDate datetime
		select @monthStartDate=DATEADD(month,DATEDIFF(month,0,getdate()),0),@monthEndDate=dateadd(d,-1,DATEADD(month,DATEDIFF(month,0,getdate())+1,0))
		Insert into #TempEmployeeDetails
		SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
		INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
		where ScheduleId=@Scheduleid
		and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')
		and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
		and (CONVERT(datetime,convert(varchar(11),SentDate)) between @monthStartDate and @monthEndDate) and Status=1)
	END
	ELSE
	BEGIN
		IF(@isReminder='N')
		BEGIN
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')
			and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
			and CONVERT(datetime,convert(varchar(11),SentDate))=CONVERT(datetime,convert(varchar(11),getdate())) and Status=1)
		END
		ELSE
		BEGIN
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,EmailId,e.Reporting_To,E.Employee_Id FROM TA_Tbl_EmailScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'')			
		END
	END	
	DECLARE @START INT
	SET @START=1
	DECLARE @TOTAL INT
	SELECT @TOTAL=COUNT(EMPLOYEE_CODE_ID) FROM #TEMPEMPLOYEEDETAILS
	IF(@reportID!=248 and @reportID!=249 and @isReminder='N')
	BEGIN
		WHILE @START<=@TOTAL
		BEGIN
			Declare @Employee_Code_id varchar(50)
			Declare @Shift_Id int
			select @Employee_Code_id=Employee_Code_Id from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			SELECT @Shift_Id=Shift_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@Employee_Code_id
			and Date=CONVERT(datetime,CONVERT(varchar(11),GETDATE())) and ProcessFlag=1
			IF (@Shift_Id is not null and @Shift_Id<>'' and @Shift_Id<>0)
			BEGIN
				DECLARE @Shift_StartTime DATETIME
				DECLARE @Shift_EndTime DATETIME
				DECLARE @addAndSubtractvalue INT
				DECLARE @finalTimings DATETIME
				SELECT @Shift_StartTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_StartTime,@Shift_EndTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@Shift_Id AND Isdeleted=0
				set @addAndSubtractvalue=CONVERT(int,SUBSTRING(@Time,0,charindex(':',@time)))*60+CONVERT(int,SUBSTRING(@Time,charindex(':',@time)+1,LEN(@time)))
				--AFTER SHIFT START TIME
				IF (@Option=1 OR @Option=2)
				BEGIN
					IF(@Option=2)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END			
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_StartTime)
				END		
				--AFTER SHIFT END TIME
				ELSE IF (@Option=3 OR @Option=4)
				BEGIN
					IF(@Option=4)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END	
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_EndTime)			
				END
				--CUSTOM TIMINGS
				ELSE IF @Option=5
				BEGIN		
					--SELECT DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
				END
				--SELECT @Shift_StartTime
				if(@finalTimings<=GETDATE())
				BEGIN
					set @START=@START+1
					continue;
				END
				ELSE
				BEGIN
					Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
				END
			END
			ELSE
			BEGIN
				Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			END		
			set @START=@START+1
		END
	end
	ELSE
	BEGIN
		--select * from #TEMPEMPLOYEEDETAILS
		Delete from #TempEmployeeDetails where Employee_Code_Id not in(
		select TE.Employee_Code_Id from #TempEmployeeDetails TE
		left outer join TA_Tbl_Employee E on TE.Employee_ID=E.Reporting_To
		where isnull(E.Reporting_To,0)!=0)
	END
	select * from #TEMPEMPLOYEEDETAILS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_WhatsAppTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- exec Proc_TA_GetEmployeeDetails_WhatsAppTriggering @Scheduleid=4,@Option=N'5',@Time=N'09:12'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_WhatsAppTriggering] 
	-- Add the parameters for the stored procedure here
	@Scheduleid INT,
	@Option int,
	@Time varchar(5),
	@isReminder char(2)=null
AS
BEGIN
	SET NOCOUNT ON;
	Create table #TempEmployeeDetails(Autoid int identity(1,1),Employee_Code_Id varchar(50),Mobile_Number varchar(200),ReportingTo varchar(10),Employee_ID bigint)
	Declare @ScheculeName varchar(max)
	Declare @reportID varchar(max)
	
	select @ScheculeName =ScheduleName,@reportID=ReportId from TA_Tbl_WhatsAppSchedule where ScheduleId=@Scheduleid
	if(@ScheculeName='Warning Letter Late Entry' or @ScheculeName='Warning Letter Early Exit')
	BEGIN
		Declare @monthStartDate datetime
		Declare @monthEndDate datetime
		select @monthStartDate=DATEADD(month,DATEDIFF(month,0,getdate()),0),@monthEndDate=dateadd(d,-1,DATEADD(month,DATEDIFF(month,0,getdate())+1,0))
		Insert into #TempEmployeeDetails
		SELECT E.Employee_Code_Id,Mobile_Number,e.Reporting_To,E.Employee_Id FROM TA_Tbl_WhatsAppScheduled_Employees ESE
		INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
		where ScheduleId=@Scheduleid
		and E.Employee_Status=1 and E.Isdeleted=0 and (Mobile_Number is not null and Mobile_Number<>'')
		and E.Employee_Code_Id not in(select MobileNumber from TA_Tbl_WhatsAppScheduleStatus where ScheduleId=@Scheduleid
		and (CONVERT(datetime,convert(varchar(11),SentDate)) between @monthStartDate and @monthEndDate) and Status=1)
	END
	ELSE
	BEGIN
		IF(@isReminder='N')
		BEGIN
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,Mobile_Number,e.Reporting_To,E.Employee_Id FROM TA_Tbl_WhatsAppScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (Mobile_Number is not null and Mobile_Number<>'')
			and E.Employee_Code_Id not in(select MobileNumber from TA_Tbl_WhatsAppScheduleStatus where ScheduleId=@Scheduleid
			and CONVERT(datetime,convert(varchar(11),SentDate))=CONVERT(datetime,convert(varchar(11),getdate())) and Status=1)
		END
		ELSE
		BEGIN
 
			Insert into #TempEmployeeDetails
			SELECT E.Employee_Code_Id,Mobile_Number,e.Reporting_To,E.Employee_Id FROM TA_Tbl_WhatsAppScheduled_Employees ESE
			INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
			where ScheduleId=@Scheduleid
			and E.Employee_Status=1 and E.Isdeleted=0 and (Mobile_Number is not null and Mobile_Number<>'')		
			

		END
	END	
	DECLARE @START INT
	SET @START=1
	DECLARE @TOTAL INT
	SELECT @TOTAL=COUNT(EMPLOYEE_CODE_ID) FROM #TEMPEMPLOYEEDETAILS
	IF(@reportID!=248 and @reportID!=249 and @isReminder='N')
	BEGIN
		
		WHILE @START<=@TOTAL
		BEGIN
			Declare @Employee_Code_id varchar(50)
			Declare @Shift_Id int
			select @Employee_Code_id=Employee_Code_Id from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			SELECT @Shift_Id=Shift_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@Employee_Code_id
			and Date=CONVERT(datetime,CONVERT(varchar(11),GETDATE())) and ProcessFlag=1
			IF (@Shift_Id is not null and @Shift_Id<>'' and @Shift_Id<>0)
			BEGIN
				DECLARE @Shift_StartTime DATETIME
				DECLARE @Shift_EndTime DATETIME
				DECLARE @addAndSubtractvalue INT
				DECLARE @finalTimings DATETIME
				SELECT @Shift_StartTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_StartTime,@Shift_EndTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@Shift_Id AND Isdeleted=0
				set @addAndSubtractvalue=CONVERT(int,SUBSTRING(@Time,0,charindex(':',@time)))*60+CONVERT(int,SUBSTRING(@Time,charindex(':',@time)+1,LEN(@time)))
				--AFTER SHIFT START TIME
				IF (@Option=1 OR @Option=2)
				BEGIN
					IF(@Option=2)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END			
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_StartTime)
				END		
				--AFTER SHIFT END TIME
				ELSE IF (@Option=3 OR @Option=4)
				BEGIN
					IF(@Option=4)
					BEGIN
						SET @addAndSubtractvalue=-1*@addAndSubtractvalue
					END	
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_EndTime)			
				END
				--CUSTOM TIMINGS
				ELSE IF @Option=5
				BEGIN		
					--SELECT DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
					set @finalTimings=DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
				END
				--SELECT @Shift_StartTime
				if(@finalTimings<=GETDATE())
				BEGIN
					set @START=@START+1
					continue;
				END
				ELSE
				BEGIN
					Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
				END
			END
			ELSE
			BEGIN
				Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			END		
			set @START=@START+1
		END
	end
	--ELSE
	--BEGIN
		--select * from #TEMPEMPLOYEEDETAILS

		--Delete from #TempEmployeeDetails where Employee_Code_Id not in(
		--select TE.Employee_Code_Id from #TempEmployeeDetails TE
		--left outer join TA_Tbl_Employee E on TE.Employee_ID=E.Reporting_To
		--where isnull(E.Reporting_To,0)!=0)
	--END
	select * from #TEMPEMPLOYEEDETAILS
END

--Select * From TA_Tbl_WhatsAppScheduled_Employees

--Select * From TA_Tbl_WhatsAppScheduleStatus


--Select Mobile_Number From TA_Tbl_Employee
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailsForBlocking]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetEmployeeDetailsForBlocking @PolicyType='7A',@ShiftID=2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailsForBlocking]
	@PolicyType char(5),
	@ShiftID int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Fromdate datetime
	Declare @Todate datetime
	set @Fromdate=GETDATE()	
	if(@PolicyType='7P')
	BEGIN
			
		Declare @7DayPresent int
		select @7DayPresent=Day_Value from Ta_tbl_PolicyConfiguration
		set @Todate=DATEADD(d,-@7DayPresent,@Fromdate)
		select E.Employee_Code_Id,COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
		inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
		where e.Hostel=1 and (pd.Date>=@Todate and pd.Date<=@Fromdate)
		and pd.FNAttendanceCode='Present' and pd.ANAttendanceCode='Present'
		group by e.Employee_Code_Id having(COUNT(date))>=@7DayPresent
	END
	ELSE IF(@PolicyType='7A')
	BEGIN
		Declare @7DayAbsent int
		select @7DayAbsent=Cont_Value from Ta_tbl_PolicyConfiguration
		set @Todate=DATEADD(d,-@7DayAbsent,@Fromdate)
		--select E.Employee_Code_Id,COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
		--inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
		--where e.Hostel=1 and (pd.Date>=@Todate and pd.Date<=@Fromdate)
		--and pd.FNAttendanceCode in('Absent','Weekly Off','Holiday') and pd.ANAttendanceCode in('Absent','Weekly off','Holiday')
		--group by e.Employee_Code_Id having(COUNT(date))>=@7DayAbsent

		declare @EmpCode nvarchar(MAX)=''

		select @EmpCode= @EmpCode + E.Employee_Code_Id + ','  from TA_Tbl_ProcessedData pd
		inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
		where e.Hostel=1 and (pd.Date>=@Todate and pd.Date<=@Fromdate)
		and pd.FNAttendanceCode in('Absent','Weekly Off','Holiday') and pd.ANAttendanceCode in('Absent','Weekly off','Holiday') and pd.Employee_Code_Id not in (select EmployeeCodeID from ta_tbl_BlockingUnblockingEmployee where BlockingTypeID=5 and isStatus=1)
		group by e.Employee_Code_Id having(COUNT(date))>=@7DayAbsent
		if(@EmpCode !='')
			begin
				select substring(@EmpCode, 1, (len(@EmpCode) - 1)) EmployeeCode
			end
		else
			begin
				select '' EmployeeCode
			end

	END
	ELSE IF(@PolicyType='DHEX')
	BEGIN
		select E.Employee_Code_Id from TA_Tbl_ProcessedData pd
		inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
		where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=@Fromdate)
		and Shift_Id=@ShiftID
	END
	ELSE IF(@PolicyType='QOT')
	BEGIN
		SELECT 1
	END
	ELSE IF(@PolicyType='WWH')
	BEGIN
		SELECT 1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailsForBlockingNew]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.RR>
-- Create date: <15-Nov-2021 05:00 PM>
-- Description:	<Getting Blocking and Unblocking employee details>

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='7A',@ShiftID=2,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='7P',@ShiftID=2,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='DHEXB',@ShiftID=63,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='WWHB',@ShiftID=2,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='qotb',@ShiftID=3,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='WWHUB',@ShiftID=2,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='DHEXUB',@ShiftID=-1,@isNightShift=0

-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='UB7P',@ShiftID=-1,@isNightShift=0

-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailsForBlockingNew]
	@PolicyType varchar(6),
	@ShiftID int,
	@isNightShift int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Fromdate datetime
	Declare @Todate datetime
	--set @Fromdate=convert(datetime, CONVERT(varchar(11),dateadd(d,-19,GETDATE()	)))
	--set @Todate=@Fromdate
	Declare @EmployeeCodeID varchar(20)
	--set @EmployeeCodeID='07613298'
	
	set @Fromdate=convert(datetime, CONVERT(varchar(11),dateadd(d,-0,GETDATE()	)))
	set @Todate=convert(datetime, CONVERT(varchar(11),dateadd(d,0,dateadd(d,-0,GETDATE()))))
	--select @Todate
	Declare @MaxExceedHours  int
	Declare @Fromdate_Day varchar(10)
	Declare @Todate_Day varchar(10)
	
	Declare @Daily_Rrd bit
	Declare @Day_Rqrd bit
	Declare @Weekly_Rqrd bit
	Declare @Quarterly_Rqrd bit
	Declare @Cont_Absent bit
	Declare @Daymaxhous int
	select @Daily_Rrd= Daily_Rrd,@Daymaxhous=Daily_Hrs, @Day_Rqrd= Day_Rqrd,@Weekly_Rqrd= Weekly_Rqrd,@Quarterly_Rqrd= Quarterly_Rqrd,@Cont_Absent= Cont_Absent from Ta_tbl_PolicyConfiguration 
	
	if(@PolicyType='7P')
	BEGIN
		if(@Day_Rqrd=1)
		begin
			Declare @7DayPresent int
			select @7DayPresent=isnull(Day_Value,0) from Ta_tbl_PolicyConfiguration
			set @Fromdate=DATEADD(d,-@7DayPresent+1,@Fromdate)
			
			create table #TempNightShiftEmp(EmployeeCodeid varchar(20),PreviousDateShiftEndTime datetime)
			insert into #TempNightShiftEmp
			select Employee_Code_Id,dateadd(minute,@Daymaxhous,Date +' '+S.Shift_EndTime) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Shift S on pd.Shift_Id=S.Shift_Id
			where 
			Date=dateadd(d,-1,@Todate)and 
			right(S.Shift_StartTime,2)='PM' and right(S.Shift_EndTime,2)='AM'
			
			
			select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
			and 
			pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
			and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
			and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
			and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
			and pd.Employee_Code_Id not in (select EmployeeCodeid from #TempNightShiftEmp)
			group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
			union all
			select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			inner join #TempNightShiftEmp TNS on TNS.EmployeeCodeid=pd.Employee_Code_Id
			where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
			and 
			pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
			and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
			and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
			and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
			and PreviousDateShiftEndTime<=GETDATE()
			group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
			
			
		end
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select employeecard from Ta_tbl_BlockedEmployees where Daily=1000)group by e.Employee_Code_Id
		end
	END
	ELSE IF(@PolicyType='7A')
	BEGIN
		if(@Cont_Absent=1)
		begin
			Declare @7DayAbsent int
			select @7DayAbsent=Cont_Value from Ta_tbl_PolicyConfiguration
			set @Fromdate=DATEADD(d,-@7DayAbsent+1,@Fromdate)
			declare @EmpCode nvarchar(MAX)=''
			--select @Fromdate,@Todate
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=DATEADD(d,-1,@Todate))
			and pd.FNAttendanceCode in('Absent','Weekly Off','Holiday') and pd.ANAttendanceCode in('Absent','Weekly off','Holiday') 
			and pd.Employee_Code_Id not in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B)
			and (InTime is null or InTime='00:00') and (OutTime is null or OutTime='00:00')
			and pd.Employee_Code_Id not in (select employeecard  from Ta_tbl_BlockedEmployees)
			and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
			group by e.Employee_Code_Id having(COUNT(date))>=@7DayAbsent-1
		end
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			group by e.Employee_Code_Id
		end
	END
	ELSE IF(@PolicyType='DHEXB')
	BEGIN
		if(@Daily_Rrd=1)
		begin
			execute Proc_TA_GetEmployeeDetails_Blocking_Unblocking @ShiftID,'B',@isNightShift
		end
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			group by e.Employee_Code_Id
		end
	END
	ELSE IF(@PolicyType='DHEXUB')
	BEGIN
		if(@Daily_Rrd=1)
		begin
			execute Proc_TA_GetEmployeeDetails_Blocking_Unblocking @ShiftID,'UB',@isNightShift
		end
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			group by e.Employee_Code_Id
		end
	END
	ELSE IF(@PolicyType='QOTB')
	BEGIN		
		Declare @Quarterly_Hrs int
		
		Declare @AllowedMaxHours_Day1 int
		set @AllowedMaxHours_Day1=270 --i.e 4 hrs 30 minutes perday		
		select @AllowedMaxHours_Day1=Daily_Hrs ,@Quarterly_Rqrd= Quarterly_Rqrd,@Quarterly_Hrs= Quarterly_Hrs from Ta_tbl_PolicyConfiguration 
		
		if(@Quarterly_Rqrd=1)
		begin
			Declare @FinancialYear_FromDate datetime
			Declare @FinancialYear_Todate datetime
			Declare @multiply_Factor float
			select @MaxExceedHours=71, @FinancialYear_FromDate=FromDate,@FinancialYear_Todate=@FinancialYear_Todate from TA_Tbl_YearSetting where IsActive=1
			
			
			select @multiply_Factor= 
			case	when DATEPART(month,@Fromdate) in(1,2,3,4) then 1 
					when DATEPART(month,@Fromdate) in(5,6,7,8) then 2
					when DATEPART(month,@Fromdate) in(9,10,11,12) then 3
			end
			
			select 
			@FromDate=
			case	when @multiply_Factor=1 then DATEADD(m,0,@FinancialYear_FromDate)
					when @multiply_Factor=2 then DATEADD(m,4,@FinancialYear_FromDate)
					when @multiply_Factor=3 then DATEADD(m,8,@FinancialYear_FromDate)
			end
			
			
			if(@Todate<@FromDate)
			begin
				select 'Todate should be greater than from date. so please check the condition'
				return;
			end		
			create table #TempProcessedDataOT(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),Shift_Date datetime,ot_min bigint)
			insert into #TempProcessedDataOT
			select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName,Shift_Date=date, pd.OtMins from TA_Tbl_ProcessedData pd
			Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where (Date>=@FromDate and Date<=@Todate) and E.Isdeleted=0 and E.Hostel=1
			--Blocking is required means, value will be one.
			and ProcessFlag=1 and isnull(OtMins,0)!=0
			and pd.Employee_Code_Id not in(select  EmployeeCard  from Ta_tbl_BlockedEmployees)
			
			create table #TempFinalResult1(Employeeid varchar(20),TotalWrkHrs varchar(20))
			Create Table #QuarterlyOverTime(Employeeid varchar(20),TotalOT bigint,DifferenceHrs bigint,ShiftTotalWorkHours bigint)
				
			
			Insert into #QuarterlyOverTime
			select EmployeeID,[Total Work Hours]= (SUM(ot_min)),
			DifferenceHrs=isnull(@Quarterly_Hrs,0)*60-(SUM(ot_min)),0 from #TempProcessedDataOT
			group by EmployeeID,EmployeeName
			
			--Block above 72 worked employees.
			--insert into #TempFinalResult1
			--select Employeeid,TotalOT from #QuarterlyOverTime where TotalOT>=(72*60)
			
			Declare @Considered_DefinedHours int
			
			select @Considered_DefinedHours =isnull(DefinedWorkhrs,0) from TA_Tbl_ShiftSettings
			if(@Considered_DefinedHours='')
			begin
				set @Considered_DefinedHours=0
			end
			--select * from #TempProcessedDataOT order by Shift_Date
			--select Employeeid,Quarter=@multiply_Factor,Fromdate=@FromDate,Todate=@Todate,configuredValue=@Quarterly_Hrs,[Total OT hours]=dbo.ConvertMinsToHours(TotalOT),[Balance OT Hours]=dbo.ConvertMinsToHours(DifferenceHrs)
			--from #QuarterlyOverTime
			/****************************compelted 53 hours and above  ***/
					
			insert into #TempFinalResult1
			select Employee_Code_Id ,0 from
			(
				select pd.Employee_Code_Id, Date,BlockigTime =
				dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime)  else  s.Shift_EndTime end))
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1				
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=dateadd(minute,@AllowedMaxHours_Day1,(Date+ ' ' + s.Shift_EndTime))
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
		
				union all
				select pd.Employee_Code_Id, Date,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
				and dateadd(minute,DifferenceHrs, date + ' '+InTime)<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
			)as result 
			
			select EmployeeCode=Employeeid,[Total OT hours]=dbo.ConvertMinsToHours(TotalWrkHrs) from #TempFinalResult1
			
			--To view the details uncommetn below lines.
			set @Considered_DefinedHours=0
			select Employeeid,Quarter=@multiply_Factor,Fromdate=@FromDate,Todate=@Todate,
			configuredValue=dbo.ConvertMinsToHours(@Quarterly_Hrs*60),
			[Total OT hours]=dbo.ConvertMinsToHours(TotalOT),
			[Balance OT Hours]=dbo.ConvertMinsToHours(DifferenceHrs),
			InTime,
			BlockigTime =
			dateadd(MINUTE,DifferenceHrs, date + (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end)),
			ShiftEndTime=date + (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end)
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1				
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
			
		END
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			group by e.Employee_Code_Id
		end
	END
	--Weekly work hours - Blocking
	ELSE IF(@PolicyType='WWHB')
	BEGIN
		Declare @Weekly_Hrs int
		
		Declare @AllowedMaxHours_Day int
		set @AllowedMaxHours_Day=270 --i.e 4 hrs 30 minutes perday		
		select @AllowedMaxHours_Day=Daily_Hrs ,@Weekly_Hrs=Weekly_Hrs,@Weekly_Rqrd=Weekly_Rqrd from Ta_tbl_PolicyConfiguration 
		
		if(@Weekly_Rqrd=1)
		BEGIN
			--if(DATENAME(DW,GETDATE()) in('Friday','Saturday','Sunday'))
			--begin				
				--set @Todate=@Fromdate
				Declare @StartDay varchar(20)		
				Declare @StartNo int
				
				select @StartNo= CumulativeWeekStartDay from TA_Tbl_ShiftSettings 
				
				select @StartDay=case when @StartNo=2 then 'Monday'
							when @StartNo=3 then 'Tuesday'
							when @StartNo=4 then 'Wednesday'
							when @StartNo=5 then 'thursday'
							when @StartNo=6 then 'friday'
							when @StartNo=7 then 'saturday'
							when @StartNo=1 then 'sunday'
				end
				Declare @i int
				set @i=7
				Declare @j int
				set @j=0
				while (@i>0)
				begin
					if(datename(dw,dateadd(d,-@j,@fromdate))=@StartDay)
					begin		
						set @Fromdate=dateadd(d,-@j,@fromdate)	
						break;
					end
					else
					begin
						set @i=@i-1
						set @j=@j+1
					end
				end
				--select @Fromdate,@Todate
				if(@Todate<@FromDate)
				begin
					select 'Todate should be greater than From date. so please check the condition'
					return;
				end		
				--select @Fromdate
				create table #TempFinalResult(Employeeid varchar(20),TotalWrkHrs varchar(20))
				
				--For removing 53 and above work hours upto previous date.
				Declare @minusValue int
				set @minusValue=0
				if(@Fromdate!=@Todate)
				begin
					set @minusValue=-1
				end
				--Removing time value from the date and time field
				set @Fromdate=CONVERT(datetime,convert(varchar(11),@fromdate))
				set @Todate=CONVERT(datetime,convert(varchar(11),@Todate))
				--select  @Fromdate,@Todate
				
				create table #TempProcessedData(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),WorkHours_min bigint,shiftDate datetime)
				insert into #TempProcessedData
				select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName, pd.HoursWorkInMins,Date from TA_Tbl_ProcessedData pd
				Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
				where (Date>=@FromDate and Date<=dateadd(d,@minusValue,@Todate)) and E.Isdeleted=0 and E.Hostel=1
				and ProcessFlag=1
				and pd.Employee_Code_Id not in(select EmployeeCard  from Ta_tbl_BlockedEmployees)
				
				--select * from #TempProcessedData where EmployeeID='07613298' order by shiftDate
				
				Create Table #WeeklyTotalWorkHours(Employeeid varchar(20),[Total Work Hours] bigint,DifferenceHrs bigint,ShiftTotalWorkHours bigint)
				
				Insert into #WeeklyTotalWorkHours
				select EmployeeID,[Total Work Hours]= (SUM(WorkHours_min)),
				DifferenceHrs=isnull(@Weekly_Hrs,0)*60-(SUM(WorkHours_min)),0 from #TempProcessedData
				group by EmployeeID,EmployeeName
				
				--Block above 53 worked employees.
				insert into #TempFinalResult
				select Employeeid ,[Total Work Hours] from #WeeklyTotalWorkHours 
				where [Total Work Hours]>=(53*60)
				
				--select Employeeid,FromDate=@Fromdate,Todate=@Todate,TotalWorkhours=dbo.ConvertMinsToHours([Total Work Hours]),RemainingHours=dbo.ConvertMinsToHours(DifferenceHrs) from #WeeklyTotalWorkHours
				
				
				/****************************compelted 53 hours and above  ***/
				insert into #TempFinalResult
				select Employee_Code_Id ,0 from
				(
					select pd.Employee_Code_Id, Date,
					FiexedDayTime=dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))),
					AlloedTime=dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 
					inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
					left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
					where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1
					and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))<=
					DATEADD(minute,-(datepart(minute,dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + s.Shift_EndTime)))/60-40),dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))))
					and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)) <=GETDATE()
					and InTime is not null and InTime<>'00:00'
					and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
					and [Total Work Hours]<(53*60)
					union all
					select pd.Employee_Code_Id, Date,(Date+ ' ' + isnull(null,'00:00')),
					dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 					
					left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
					where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
					and dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)<=GETDATE()
					and InTime is not null and InTime<>'00:00'
					and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
					and [Total Work Hours]<(53*60)
				)as result 
				
				select EmployeeCode=Employeeid,TotalWorkHours= dbo.ConvertMinsToHours(TotalWrkHrs) from #TempFinalResult
				
				
				--To view the emloyee details for checking uncomment the codings
				select pd.Employee_Code_Id,FromDate=@Fromdate,Todate=@Todate,intime,AllowedMaxHours_Day=@AllowedMaxHours_Day,s.Shift_EndTime,TotalWorkhours=dbo.ConvertMinsToHours([Total Work Hours]),
				RemainingHours=dbo.ConvertMinsToHours(DifferenceHrs),
				DayEndTime=DATEADD(minute,-(datepart(minute,dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + s.Shift_EndTime)))%60-40),dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + s.Shift_EndTime))),
				BlockingTime=dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,isnull(DifferenceHrs,0), date + ' '+InTime))/60-40),dateadd(MINUTE,isnull(DifferenceHrs,0), date + ' '+InTime)) 
				from TA_Tbl_ProcessedData pd 
				left outer join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),@Todate))
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
				
			--end			
		END
		else
		begin
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			group by e.Employee_Code_Id
		end	
	END
	Else if(@PolicyType='WWHUB')
	begin
		if(@Weekly_Rqrd=1)
		begin
			Declare @StartDay1 varchar(20)		
			Declare @StartNo1 int
			
			select @StartNo1= CumulativeWeekStartDay from TA_Tbl_ShiftSettings 
			--set @StartNo=4
			select @StartDay1=case when @StartNo1=2 then 'Monday'
						when @StartNo1=3 then 'Tuesday'
						when @StartNo1=4 then 'Wednesday'
						when @StartNo1=5 then 'thursday'
						when @StartNo1=6 then 'friday'
						when @StartNo1=7 then 'saturday'
						when @StartNo1=1 then 'sunday'
			end
			--select DATENAME(dw,@Fromdate),@StartDay1
			if(DATENAME(dw,@Fromdate)=@StartDay1)
			begin
				select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where Daily=3 and WhenBlocked_Daily<@Fromdate
			end
			else
			begin
				select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1000 and WhenBlocked_Daily<@Fromdate
			end
		end
		else
		begin
			select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1000 and WhenBlocked_Daily<@Fromdate
		end
	end
	Else if(@PolicyType='UB7P')
	begin
		if(@Day_Rqrd=1)
		begin
			select EmployeeCode=EmployeeCard  from Ta_tbl_BlockedEmployees where Daily=2 and WhenBlocked_Daily<@Fromdate
		end
		else
		begin
			select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where Daily=1000 and WhenBlocked_Daily<@Fromdate
		end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailsForBlockingNew_25Feb2022]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.RR>
-- Create date: <15-Nov-2021 05:00 PM>
-- Description:	<Getting Blocking and Unblocking employee details>
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='7A',@ShiftID=2,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='7P',@ShiftID=2,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='DHEXB',@ShiftID=63,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='WWHB',@ShiftID=2,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='qotb',@ShiftID=3,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='WWHUB',@ShiftID=2,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='DHEXUB',@ShiftID=-1,@isNightShift=0
-- Proc_Ta_GetEmployeeDetailsForBlockingNew @PolicyType='UB7P',@ShiftID=-1,@isNightShift=0
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailsForBlockingNew_25Feb2022]
	@PolicyType varchar(6),
	@ShiftID int,
	@isNightShift int
AS
BEGIN
	SET NOCOUNT ON;
		--To remove duplicate records
	delete from TA_Tbl_ProcessedData where Process_Rec_ID in(
	select Process_Rec_ID from (
	select row=row_number()over(partition by employee_code_id,date order by employee_code_id,date),Employee_Code_Id,Date,Process_Rec_ID from 
	TA_Tbl_ProcessedData)as a)

	Declare @Fromdate datetime
	Declare @Todate datetime
	--set @Fromdate=convert(datetime, CONVERT(varchar(11),dateadd(d,-19,GETDATE()	)))
	--set @Todate=@Fromdate
	Declare @EmployeeCodeID varchar(20)
	--set @EmployeeCodeID='07613298'
	--set @Fromdate=convert(datetime, CONVERT(varchar(11),dateadd(d,-0,GETDATE()	)))
	--set @Todate=convert(datetime, CONVERT(varchar(11),dateadd(d,0,dateadd(d,-0,GETDATE()))))
	--select @Todate
	Declare @MaxExceedHours  int
	Declare @Fromdate_Day varchar(10)
	Declare @Todate_Day varchar(10)
	Declare @Daily_Rrd bit
	Declare @Day_Rqrd bit
	Declare @Weekly_Rqrd bit
	Declare @Quarterly_Rqrd bit
	Declare @Cont_Absent bit
	Declare @Daymaxhous int
	select @Daily_Rrd= Daily_Rrd,@Daymaxhous=Daily_Hrs, @Day_Rqrd= Day_Rqrd,@Weekly_Rqrd= Weekly_Rqrd,@Quarterly_Rqrd= Quarterly_Rqrd,@Cont_Absent= Cont_Absent from Ta_tbl_PolicyConfiguration 
	Declare @EmployeeIDs varchar(max)
	set @EmployeeIDs=''
	if(@PolicyType='7P')
	BEGIN
		if(@Day_Rqrd=1)
		begin
			Declare @7DayPresent int
			select @7DayPresent=isnull(Day_Value,0) from Ta_tbl_PolicyConfiguration
			set @Fromdate=DATEADD(d,-@7DayPresent+1,@Fromdate)
			create table #TempNightShiftEmp(EmployeeCodeid varchar(20),PreviousDateShiftEndTime datetime)
			insert into #TempNightShiftEmp
			select Employee_Code_Id,dateadd(minute,@Daymaxhous,dateadd(d,1,Date) +' '+S.Shift_EndTime) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Shift S on pd.Shift_Id=S.Shift_Id
			where 
			Date=dateadd(d,-1,@Todate)and 
			(right(S.Shift_StartTime,2)='PM' and right(S.Shift_EndTime,2)='AM'
			or
			right(S.Shift_StartTime,2)='PM' and right(S.Shift_EndTime,2)='PM')
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCode+'''' from
			(
				select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
				where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
				and 
				pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
				and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
				and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
				and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
				and pd.Employee_Code_Id not in (select EmployeeCodeid from #TempNightShiftEmp)
				group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
				union all
				select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
				inner join #TempNightShiftEmp TNS on TNS.EmployeeCodeid=pd.Employee_Code_Id
				where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
				and 
				pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
				and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
				and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
				and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
				and PreviousDateShiftEndTime<=GETDATE()
				group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
			)as main
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
			select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
				where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
				and 
				pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
				and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
				and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
				and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
				and pd.Employee_Code_Id not in (select EmployeeCodeid from #TempNightShiftEmp)
				group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
				union all
				select EmployeeCode=E.Employee_Code_Id,totalDaysPresent=COUNT(e.Employee_Code_Id) from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
				inner join #TempNightShiftEmp TNS on TNS.EmployeeCodeid=pd.Employee_Code_Id
				where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=dateadd(d,-1,@Todate))
				and 
				pd.FNAttendanceCode in('Present','Weekly off','Holiday') and pd.ANAttendanceCode in('Present','Weekly off','holiday')
				and ((intime is not null and InTime<>'00:00') or (OutTime is not null and OutTime<>'00:00'))
				and pd.Employee_Code_Id not in (select employeecard from Ta_tbl_BlockedEmployees)
				and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
				and PreviousDateShiftEndTime<=GETDATE()
				group by e.Employee_Code_Id having(COUNT(date))>=(@7DayPresent-1)
		end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select employeecard from Ta_tbl_BlockedEmployees where Daily=1000)
			--group by e.Employee_Code_Id
			order by isnull(outtime,'')
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end
	END
	ELSE IF(@PolicyType='7A')
	BEGIN
		if(@Cont_Absent=1)
		begin
			Declare @7DayAbsent int
			select @7DayAbsent=Cont_Value from Ta_tbl_PolicyConfiguration
			set @Fromdate=DATEADD(d,-@7DayAbsent+1,@Fromdate)
			declare @EmpCode nvarchar(MAX)=''
			--select @Fromdate,@Todate
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCode+''''
			from(
				select EmployeeCode=E.Employee_Code_Id,Totalcount=count(Date) from TA_Tbl_ProcessedData pd
				inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
				where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=DATEADD(d,-1,@Todate))
				and pd.FNAttendanceCode in('Absent','Weekly Off','Holiday') and pd.ANAttendanceCode in('Absent','Weekly off','Holiday')
				and pd.Employee_Code_Id not in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where DayWise=1)
				and (InTime is null or InTime='00:00') and (OutTime is null or OutTime='00:00')
				--and pd.Employee_Code_Id not in (select employeecard  from Ta_tbl_BlockedEmployees)
				and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
				group by e.Employee_Code_Id having(COUNT(date))>=@7DayAbsent-1
			)as main
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
			select EmployeeCode=E.Employee_Code_Id,count(Date) from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where e.Hostel=1 and (pd.Date>=@Fromdate and pd.Date<=DATEADD(d,-1,@Todate))
			and pd.FNAttendanceCode in('Absent','Weekly Off','Holiday') and pd.ANAttendanceCode in('Absent','Weekly off','Holiday') 
			and pd.Employee_Code_Id not in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B  where DayWise=1)
			and (InTime is null or InTime='00:00') and (OutTime is null or OutTime='00:00')
			--and pd.Employee_Code_Id not in (select employeecard  from Ta_tbl_BlockedEmployees)
			and (@EmployeeCodeID is null or pd.Employee_Code_Id=@EmployeeCodeID)
			group by e.Employee_Code_Id having(COUNT(date))>=@7DayAbsent-1
		end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			--group by e.Employee_Code_Id
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end
	END
	ELSE IF(@PolicyType='DHEXB')
	BEGIN
		if(@Daily_Rrd=1)
		begin
			--insert into testingBlocking values(@ShiftId,'B',@isNightShift)
			execute [Proc_TA_GetEmployeeDetails_Blocking_Unblocking_25Feb2022] @ShiftID,'B',@isNightShift
			end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			--group by e.Employee_Code_Id
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end
	END
	ELSE IF(@PolicyType='DHEXUB' or @PolicyType='UB')
	BEGIN
		if(@Daily_Rrd=1)
		begin
			--insert into testingPolicy values(@PolicyType,@ShiftID,@isNightShift)
			execute [Proc_TA_GetEmployeeDetails_Blocking_Unblocking_25Feb2022] @ShiftID,'UB',@isNightShift
		end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			--group by e.Employee_Code_Id
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''N'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end
	END
	ELSE IF(@PolicyType='QOTB')
	BEGIN		
		Declare @Quarterly_Hrs int
		Declare @AllowedMaxHours_Day1 int
		set @AllowedMaxHours_Day1=270 --i.e 4 hrs 30 minutes perday		
		select @AllowedMaxHours_Day1=Daily_Hrs ,@Quarterly_Rqrd= Quarterly_Rqrd,@Quarterly_Hrs= Quarterly_Hrs from Ta_tbl_PolicyConfiguration 
		--set @Quarterly_Rqrd=1
		--set @Quarterly_Hrs=60
		if(@Quarterly_Rqrd=1)
		begin
			Declare @FinancialYear_FromDate datetime
			Declare @FinancialYear_Todate datetime
			Declare @multiply_Factor float
			select @MaxExceedHours=71, @FinancialYear_FromDate=FromDate,@FinancialYear_Todate=@FinancialYear_Todate from TA_Tbl_YearSetting where IsActive=1
			select @multiply_Factor= 
			case	when DATEPART(month,@Fromdate) in(1,2,3) then 1 
					when DATEPART(month,@Fromdate) in(4,5,6) then 2
					when DATEPART(month,@Fromdate) in(7,8,9) then 3
					when DATEPART(month,@Fromdate) in(11,12,10) then 4
			end
			select 
			@FromDate=
			case	when @multiply_Factor=1 then DATEADD(m,0,@FinancialYear_FromDate)
					when @multiply_Factor=2 then DATEADD(m,3,@FinancialYear_FromDate)
					when @multiply_Factor=3 then DATEADD(m,6,@FinancialYear_FromDate)
					when @multiply_Factor=3 then DATEADD(m,9,@FinancialYear_FromDate)
			end
			if(@Todate<@FromDate)
			begin
				select 'Todate should be greater than from date. so please check the condition'
				return;
			end		
			create table #TempProcessedDataOT(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),Shift_Date datetime,ot_min bigint)
			insert into #TempProcessedDataOT
			select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName,Shift_Date=date, pd.OtMins from TA_Tbl_ProcessedData pd
			Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where (Date>=@FromDate and Date<=@Todate) and E.Isdeleted=0 and E.Hostel=1
			--Blocking is required means, value will be one.
			and ProcessFlag=1 and isnull(OtMins,0)!=0
			and pd.Employee_Code_Id not in(select  EmployeeCard  from Ta_tbl_BlockedEmployees)
			--and pd.Employee_Code_Id='10515219'
			create table #TempFinalResult1(Employeeid varchar(20),TotalWrkHrs varchar(20))
			Create Table #QuarterlyOverTime(Employeeid varchar(20),TotalOT bigint,DifferenceHrs bigint,ShiftTotalWorkHours bigint)
			Insert into #QuarterlyOverTime
			select EmployeeID,[Total Work Hours]= (SUM(ot_min)),
			DifferenceHrs=isnull(@Quarterly_Hrs,0)*60-(SUM(ot_min)),0 from #TempProcessedDataOT
			group by EmployeeID,EmployeeName
			--Block above 72 worked employees.
			--insert into #TempFinalResult1
			--select Employeeid,TotalOT from #QuarterlyOverTime where TotalOT>=(72*60)
			Declare @Considered_DefinedHours int
			select @Considered_DefinedHours =isnull(DefinedWorkhrs,0) from TA_Tbl_ShiftSettings
			if(@Considered_DefinedHours='')
			begin
				set @Considered_DefinedHours=0
			end
			--select * from #TempProcessedDataOT order by Shift_Date
			--select Employeeid,Quarter=@multiply_Factor,Fromdate=@FromDate,Todate=@Todate,configuredValue=@Quarterly_Hrs,[Total OT hours]=dbo.ConvertMinsToHours(TotalOT),[Balance OT Hours]=dbo.ConvertMinsToHours(DifferenceHrs)
			--from #QuarterlyOverTime
			/****************************compelted 53 hours and above  ***/
			insert into #TempFinalResult1
			select Employee_Code_Id ,0 from
			(
				select pd.Employee_Code_Id, Date,BlockigTime =
				dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime)  else  s.Shift_EndTime end))
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=dateadd(minute,@AllowedMaxHours_Day1,(Date+ ' ' + s.Shift_EndTime))
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
				union all
				select pd.Employee_Code_Id, Date,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
				and dateadd(minute,DifferenceHrs, date + ' '+InTime)<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
			)as result 
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+Employeeid+''''
			from #TempFinalResult1
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
			--select EmployeeCode=Employeeid,[Total OT hours]=dbo.ConvertMinsToHours(TotalWrkHrs) 
			--from #TempFinalResult1
			select EmployeeCode= pd.Employee_Code_Id, Date,BlockigTime =
				dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime)  else  s.Shift_EndTime end))
				from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1				
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=dateadd(minute,@AllowedMaxHours_Day1,(Date+ ' ' + s.Shift_EndTime))
				and dateadd(MINUTE,DifferenceHrs, date + ' '+ (case when @Considered_DefinedHours=1 then DATEADD(MINUTE,dbo.ConvertHoursToMinites(s.Shift_TotalWorkingHours), intime) else  s.Shift_EndTime end))<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				--and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
				union all
				select EmployeeCode= pd.Employee_Code_Id, Date,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 
				inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
				inner join #QuarterlyOverTime wt on wt.Employeeid=pd.Employee_Code_Id
				where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
				and dateadd(minute,DifferenceHrs, date + ' '+InTime)<=GETDATE()
				and InTime is not null and InTime<>'00:00'
				--and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult1 f)
		END
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			--group by e.Employee_Code_Id
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end
	END
	--Weekly work hours - Blocking
	ELSE IF(@PolicyType='WWHB')
	BEGIN
		Declare @Weekly_Hrs int
		Declare @AllowedMaxHours_Day int
		set @AllowedMaxHours_Day=270 --i.e 4 hrs 30 minutes perday		
		select @AllowedMaxHours_Day=Daily_Hrs ,@Weekly_Hrs=Weekly_Hrs,@Weekly_Rqrd=Weekly_Rqrd from Ta_tbl_PolicyConfiguration 
		if(@Weekly_Rqrd=1)
		BEGIN
			--if(DATENAME(DW,GETDATE()) in('Friday','Saturday','Sunday'))
			--begin				
				--set @Todate=@Fromdate
				Declare @StartDay varchar(20)	
				Declare @EndDay varchar(20)		
				Declare @EndNo int
				Declare @StartNo int
				select @StartNo= CumulativeWeekStartDay,@EndNo=CumulativeWeekEndDay from TA_Tbl_ShiftSettings 
				select @StartDay=case when @StartNo=2 then 'Monday'
				when @StartNo=3 then 'Tuesday'
							when @StartNo=4 then 'Wednesday'
							when @StartNo=5 then 'Thursday'
							when @StartNo=6 then 'Friday'
							when @StartNo=7 then 'Saturday'
							when @StartNo=1 then 'Sunday' end,
						@EndDay=case when @EndNo=2 then 'Monday'
							when @EndNo=3 then 'Tuesday'
							when @EndNo=4 then 'Wednesday'
							when @EndNo=5 then 'Thursday'
							when @EndNo=6 then 'Friday'
							when @EndNo=7 then 'Saturday'
							when @EndNo=1 then 'Sunday'
				end
				--select datename(dw,@todate),@EndDay
				--if(datename(dw,@todate)=@EndDay)
				if(1=1)
				begin
					Declare @i int
					set @i=7
					Declare @j int
					set @j=0
					while (@i>0)
					begin
						if(datename(dw,dateadd(d,-@j,@fromdate))=@StartDay)
						begin		
							set @Fromdate=dateadd(d,-@j,@fromdate)	
							break;
						end
						else
						begin
							set @i=@i-1
							set @j=@j+1
						end
					end
					--select @Fromdate,@Todate,@StartDay
					if(@Todate<@FromDate)
					begin
						select 'Todate should be greater than From date. so please check the condition'
						return;
					end		
					--select @Fromdate
					create table #TempFinalResult(Employeeid varchar(20),TotalWrkHrs varchar(20))
					--For removing 53 and above work hours upto previous date.
					Declare @minusValue int
					set @minusValue=0
					if(@Fromdate!=@Todate)
					begin
						set @minusValue=-1
					end
					--Removing time value from the date and time field
					set @Fromdate=CONVERT(datetime,convert(varchar(11),@fromdate))
					set @Todate=CONVERT(datetime,convert(varchar(11),@Todate))
					--select  @Fromdate,@Todate
					create table #TempProcessedData(AutoID bigint,EmployeeID varchar(20),EmployeeName varchar(500),WorkHours_min bigint,shiftDate datetime)
					insert into #TempProcessedData
					select AutoID=E.Employee_Id,E.Employee_Code_Id, E.Employee_FirstName + ' ' +E.Employee_LastName, pd.HoursWorkInMins,Date from TA_Tbl_ProcessedData pd
					Inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
					where (Date>=@FromDate and Date<=dateadd(d,@minusValue,@Todate)) and E.Isdeleted=0 and E.Hostel=1
					and ProcessFlag=1
					and pd.Employee_Code_Id not in(select EmployeeCard  from Ta_tbl_BlockedEmployees)
					--select * from #TempProcessedData 
					Create Table #WeeklyTotalWorkHours(Employeeid varchar(20),[Total Work Hours] bigint,DifferenceHrs bigint,ShiftTotalWorkHours bigint)
					Insert into #WeeklyTotalWorkHours
					select EmployeeID,[Total Work Hours]= (SUM(WorkHours_min)),
					DifferenceHrs=isnull(@Weekly_Hrs,0)*60-(SUM(WorkHours_min)),0 from #TempProcessedData
					group by EmployeeID,EmployeeName
					--Block above 53 worked employees.
					insert into #TempFinalResult
					select Employeeid ,[Total Work Hours] from #WeeklyTotalWorkHours 
					where [Total Work Hours]>=(53*60)
					--select Employeeid,FromDate=@Fromdate,Todate=@Todate,TotalWorkhours=dbo.ConvertMinsToHours([Total Work Hours]),RemainingHours=dbo.ConvertMinsToHours(DifferenceHrs) 
					--from #WeeklyTotalWorkHours
					/****************************compelted 53 hours and above  ***/
					insert into #TempFinalResult
					select Employee_Code_Id ,0 from
					(
						select pd.Employee_Code_Id, Date,
						FiexedDayTime=dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))),
						AllowedTime=dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd
						inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
						left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
						where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1
						and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))<=
						DATEADD(minute,-(datepart(minute,dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + s.Shift_EndTime)))/60-40),dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))))
						and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)) <=GETDATE()
						and InTime is not null and InTime<>'00:00'
						and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
						and [Total Work Hours]<(53*60)
						union all
						select pd.Employee_Code_Id, Date,(Date+ ' ' + isnull(null,'00:00')),
						dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 					
						left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
						where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
						and dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)<=GETDATE()
						and InTime is not null and InTime<>'00:00'
						and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
						and [Total Work Hours]<(53*60)
					)as result 
					set @EmployeeIDs=''
					select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+Employeeid+'''' from #TempFinalResult
					if(@EmployeeIDs!='')
					begin
						select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
					end
					else
					begin
						select 'Empty' as employeeids,updateQuery=''
					end
					--select EmployeeCode=Employeeid,TotalWorkHours= dbo.ConvertMinsToHours(TotalWrkHrs) from #TempFinalResult
					select EmployeeCode=pd.Employee_Code_Id, Date,
					FiexedDayTime=dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))),
						AlloedTime=dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 
						inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
						left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
						where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id!=-1
						and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))<=
						DATEADD(minute,-(datepart(minute,dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + s.Shift_EndTime)))/60-40),dateadd(minute,@AllowedMaxHours_Day,(Date+ ' ' + isnull(s.Shift_EndTime,'00:00'))))
						and dateadd(minute,-(datepart(MINUTE,dateadd(MINUTE,DifferenceHrs, date + ' '+InTime))/60-40),dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)) <=GETDATE()
						and InTime is not null and InTime<>'00:00'
						and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
						and [Total Work Hours]<(53*60)
						union all
						select pd.Employee_Code_Id, Date,(Date+ ' ' + isnull(null,'00:00')),
						dateadd(MINUTE,DifferenceHrs, date + ' '+InTime) from TA_Tbl_ProcessedData pd 					
						left outer join #WeeklyTotalWorkHours wt on wt.Employeeid=pd.Employee_Code_Id
						where Date=CONVERT(datetime, CONVERT(varchar(11),GETDATE())) and pd.Shift_Id=-1
						and dateadd(MINUTE,DifferenceHrs, date + ' '+InTime)<=GETDATE()
						and InTime is not null and InTime<>'00:00'
						and pd.Employee_Code_Id not in(select f.Employeeid from #TempFinalResult f)
						and [Total Work Hours]<(53*60)		
						union all
						select f.Employeeid,'','','' from #TempFinalResult f
				end
				else
				begin
					set @EmployeeIDs=''
					select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
					inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
					where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
					--group by e.Employee_Code_Id
					if(@EmployeeIDs!='')
					begin
						select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
					end
					else
					begin
						select 'Empty' as employeeids,updateQuery=''
					end
					select datename(dw,@todate),@EndDay
				end				
			--end			
		END
		else
		begin
			set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+pd.Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee e on pd.Employee_Code_Id=e.SwipeCardNo
			where pd.Employee_Code_Id  in (select B.EmployeeCard from Ta_tbl_BlockedEmployees B where ContinuousDayWise=1000)
			--group by e.Employee_Code_Id
			if(@EmployeeIDs!='')
			begin
				select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''Y'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			end
			else
			begin
				select 'Empty' as employeeids,updateQuery=''
			end
		end	
	END
	Else if(@PolicyType='WWHUB')
	begin
		if(@Weekly_Rqrd=1)
		begin
			Declare @StartDay1 varchar(20)		
			Declare @StartNo1 int
			select @StartNo1= CumulativeWeekStartDay from TA_Tbl_ShiftSettings 
			--set @StartNo=4
			select @StartDay1=case when @StartNo1=2 then 'Monday'
						when @StartNo1=3 then 'Tuesday'
						when @StartNo1=4 then 'Wednesday'
						when @StartNo1=5 then 'Thursday'
						when @StartNo1=6 then 'Friday'
						when @StartNo1=7 then 'Saturday'
						when @StartNo1=1 then 'Sunday'
			end
			--select DATENAME(dw,@Fromdate),@StartDay1
			if(DATENAME(dw,@Fromdate)=@StartDay1)
			begin
				set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCard+'''' from Ta_tbl_BlockedEmployees where WeekWise=1 and WhenBlocked_WeekWise<@Fromdate
				--select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1 and WhenBlocked_WeekWise<@Fromdate
			end
			else
			begin
				set @EmployeeIDs=''
				select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCard+'''' from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
				--select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1 and WhenBlocked_WeekWise<@Fromdate
				--select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
			end
		end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCard+'''' from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
			--select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
		end
		if(@EmployeeIDs!='')
		begin
			select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''N'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
			select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1 and WhenBlocked_WeekWise<@Fromdate
		end
		else
		begin
			select 'Empty' as employeeids,updateQuery=''
		end
	end
	Else if(@PolicyType='UB7P')
	begin
		Create table #tempFinalDaywise (EmployeeCard varchar(20))
		if(@Day_Rqrd=1)
		begin
			set @EmployeeIDs=''
			--select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCard+''''  from Ta_tbl_BlockedEmployees be
			----inner join TA_Tbl_ProcessedData pd on pd.Employee_Code_Id=be.EmployeeCard
			--where WeekWise=0 and DayWise=1 
			----and (date+Shift_StartTime)<=GETDATE()
			--and WhenBlocked_DayWise<@Fromdate
			--select EmployeeCode=EmployeeCard  from Ta_tbl_BlockedEmployees where WeekWise=0 and DayWise=1 and WhenBlocked_DayWise<@Fromdate
			--insert into testingunblocking values(@PolicyType,@shiftid,@isNightShift)
			Declare @AllowedMinMin_BeforeShiftStart int
			set @AllowedMinMin_BeforeShiftStart=120
			insert into #tempFinalDaywise 
			select EmployeeCard from Ta_tbl_BlockedEmployees be
			where WeekWise=0 and DayWise=1 and WhenBlocked_DayWise<@Fromdate
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+Employee_Code_Id+'''' from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
			where Employee_Code_Id in(select EmployeeCard from #tempFinalDaywise)
			and (CONVERT(varchar(11),getdate())+ DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,s.Shift_StartTime)<=GETDATE()) and date=convert(varchar(11),getdate())		
		end
		else
		begin
			set @EmployeeIDs=''
			select @EmployeeIDs=coalesce(@EmployeeIDs+',','')+''''+EmployeeCard+''''from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
			--select EmployeeCode=EmployeeCard from Ta_tbl_BlockedEmployees where WeekWise=1000 and WhenBlocked_WeekWise<@Fromdate
		end
		if(@EmployeeIDs!='')
		begin
			select employeeids=substring(@EmployeeIDs,2,len(@EmployeeIDs)),updateQuery='update T_USR set DSBDUSR=''N'' where USRID in('+substring(@EmployeeIDs,2,len(@EmployeeIDs))+')'
		end
		else
		begin
			select 'Empty' as employeeids,updateQuery=''
		end
			select EmployeeCode=Employee_Code_Id from TA_Tbl_ProcessedData pd 
			inner join TA_Tbl_Shift s on pd.Shift_Id=s.Shift_Id
			where Employee_Code_Id in(select EmployeeCard from #tempFinalDaywise)
			and (CONVERT(varchar(11),getdate())+ DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,s.Shift_StartTime)<=GETDATE()) and date=convert(varchar(11),getdate())
			drop table #tempFinalDaywise
	end
	--For synchornization
	--if((convert(varchar(11),getdate())+' 00:15')>=getdate() and (convert(varchar(11),getdate())+' 00:30')<=getdate())
	if not exists(select * from ta_tbl_EmployeeAPILog where convert(varchar(11),Log_Timestamp)=convert(varchar(11),getdate()))
	begin
		delete from ta_tbl_EmployeeAPILog 
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailsForProfile]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetEmployeeDetailsForProfile 3
-- exec Proc_Ta_GetEmployeeDetailsForProfile @EmpAutoID=35
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailsForProfile]
	@EmpAutoID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF NOT EXISTS(SELECT myprofileID FROM Ta_Tbl_MyProfileDetails where Employee_Id=@EmpAutoID and isnull(Status,'')='Pending' )
	
	BEGIN
		--select 3
		SELECT	E.Employee_Id,
				E.Employee_FirstName,
				E.Employee_MiddleName,
				isnull(E.Employee_LastName,'') as Employee_LastName, 
				E.Father_name,
				E.Mother_name,
				CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,
				CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
				E.Blood_Group,
				E.EmailId,
				E.Contact_Address,
				E.Permanent_Address,
				E.Phone_Number,
				E.Mobile_Number,
				E.Marital_status,  
				E.Nationality,
				R.Name as Religion,
				R.ID as ReligionId,
				E.Personal_mailid,
				E.Native_Place,Look.Title As CityName,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,
				MP.Remarks,  
				0 myprofileID
		FROM TA_Tbl_Employee E 
		LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
		LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
		LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
		LEFT OUTER JOIN Ta_Tbl_MyProfileDetails MP ON MP.Employee_Id = E.Employee_Id
		LEFT OUTER JOIN TA_Tbl_Religion R on e.Religion=R.ID
		where E.Employee_Id=@EmpAutoID and e.isdeleted=0
	END
	ELSE
	BEGIN
	print 'else'
		SELECT TOP 1 MP.Employee_Id,
				MP.Employee_FirstName,
				MP.Employee_MiddleName,
				isnull(MP.Employee_MiddleName,''), 
				E.Father_name,
				E.Mother_name,
				E.Blood_Group,
				CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,
				CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
				E.EmailId,
				E.Personal_mailid,
				MP.Contact_Address ,
				MP.Permanent_Address ,				
				E.Native_Place,Look.Title As CityName ,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,  
				MP.Phone_Number ,
				MP.Mobile_Number,
				MP.Marital_status,  
				E.Nationality,
				R.Name as Religion,
				R.ID as ReligionId,
				MP.Remarks,
				mp.myprofileID  myprofileID
		FROM TA_Tbl_Employee E 
		LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
		LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
		LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
		LEFT OUTER JOIN Ta_Tbl_MyProfileDetails MP ON MP.Employee_Id = E.Employee_Id
		LEFT OUTER JOIN TA_Tbl_Religion R on e.Religion=R.ID
		where Mp.Employee_Id=@EmpAutoID and isnull(Status,'')='Pending' or isnull(Status,'')='Rejected'
		and e.isdeleted=0
	END
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeEmailIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified by : Thilakraj.C   On : 22-Feb-2013
For : " Com " shown as "Co" - 
SELECT substring(@List,0,LEN(@List)) as Email--- OLD Line No : 40
SELECT substring(@List,1,LEN(@List)) as Email --- New
*/
--Proc_TA_GetEmployeeEmailIds '1,2,3,4,5,6,7,8'
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeEmailIds]
(
 @EmployeeIds varchar(4000)
)
AS
BEGIN
declare @sql varchar(4000)
set @sql =''
create table #TempEmail (Email varchar(250))
set @sql = @sql + 'select emailId from TA_Tbl_Employee where Employee_Id in (' + @EmployeeIds + ')'
insert into #TempEmail exec (@sql)
DECLARE @List VARCHAR(8000)
SELECT @List = COALESCE(@List + ';', '') + CAST(Email AS VARCHAR)
FROM   #TempEmail
SELECT substring(@List,1,LEN(@List)) as Email
drop table #TempEmail 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		< Velumani P>
-- Create date: < 25-Jan-2020 >
-- Description:	<Get Employee Data and save into its table>
/*
Proc_TA_GetEmployeeFromCMITechDevice
'<DocumentElement>
  <MyDt>
    <EmployeeName>Anandaprasad</EmployeeName>
    <EmployeeId>2</EmployeeId>
  </MyDt>
  <MyDt>
    <EmployeeName>RENJUKUMAR</EmployeeName>
    <EmployeeId>3</EmployeeId>
  </MyDt>
</DocumentElement>'
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]
	-- Add the parameters for the stored procedure here
	@Xml XML

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Index INT 
	set @Index= 0
	declare @Error nvarchar(Max)
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	create table #ImportMaster 
	(
		id bigint identity(1,1),
		Emp_FirstName nvarchar(max),
		Emp_id nvarchar(max)
	)
	insert into  #ImportMaster
	select 
		rtrim(ltrim(EmployeeName)),
		rtrim(ltrim(EmployeeId))
		from OPENXML(@Index, '/DocumentElement/MyDt',2)
	WITH(
			EmployeeName  nvarchar(max),
			EmployeeId   nvarchar(max)			
		  ) AS OT 
		  
	delete from TA_Tbl_CMITechSyncEmployeeInfo
	
	INSERT INTO TA_Tbl_CMITechSyncEmployeeInfo
	select Emp_FirstName, Emp_id from #ImportMaster

	drop table #ImportMaster	
		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeLeavepolicyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetEmployeeLeavepolicyID @tag='PA',@EmployeeID=33,@shiftDate='2023-06-13'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeLeavepolicyID] 
	-- Add the parameters for the stored procedure here
	@tag char(3)='PA',
	@EmployeeID NVARCHAR(50) = 'TCT002',
	@ShiftDate datetime = '2023-06-08'
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    if(@tag='LP')
	Begin

		Declare @curentDate Date 
		Set @curentDate= Convert(date,GETDATE())
		Declare @ParentId int

		if(Convert(date,@ShiftDate)!='')
		begin

		 Select LeavePolicy_Id,EmployeeId,YearSettingId,hasSpecialRights  From TA_Tbl_Emp_LeavePolicy inner Join TA_Tbl_Employee on Employee_Id=EmployeeId inner Join TA_Tbl_Usergroup on groupId=UserGroup_Id  where EmployeeId=@EmployeeID and (@ShiftDate between FromDate and ToDate)

		End
		else
		Begin
			Select '0'
		End
	End
	Else IF (@tag='LA')
	Begin
		
		Select Type,LT.LeaveType as leaveType_id,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Reason,LeaveApplication_Id From TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id where Employee_Id=@EmployeeID and Leave_FromDate=@ShiftDate and isCalanderflag=1

		-- Select * From TA_Tbl_LeaveApplication
	End

	Else IF (@tag='OD')
	Begin
	
       SELECT TA_Tbl_OndutyEntry.Onduty_ID,TA_Tbl_Employee.Employee_Id,TA_Tbl_OndutyEntry.Onduty_Status  FROM TA_Tbl_OndutyEntry 
               INNER JOIN  TA_Tbl_ManualTimeEntry on TA_Tbl_OndutyEntry.Onduty_ID  = TA_Tbl_ManualTimeEntry.OnDuty_ID
               INNER JOIN TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =  TA_Tbl_OndutyEntry.Onduty_EmployeeID
               WHERE Onduty_EmployeeID =@EmployeeID AND  Onduty_FromDate = @ShiftDate 
	End

	Else IF(@tag='LOD')
	Begin

		Select Onduty_FromTime as Fromdate,Onduty_ToTime as Todate,Onduty_Reason as Reason From TA_Tbl_OndutyEntry inner join TA_tbl_Employee on Employee_Code_Id=Onduty_EmployeeID  where Employee_Id=@EmployeeID and Onduty_FromDate=@ShiftDate

	End

	Else If (@tag='PA')
	Begin
		Select Permission_Id,Permission_Date,Permission_FromTime,Permission_ToTime,Permission_Status,Permission_Hours,Permission_Reason From TA_Tbl_Permission  where Employee_Id=@EmployeeID and Permission_Date=@ShiftDate 
	End

END

--Select * From TA_Tbl_Permission
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeLingual]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		S.Christopher
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeLingual]
	@EmployeeId int
AS
BEGIN
	SET NOCOUNT ON;
	 if exists(SELECT LanguageId FROM TA_Tbl_EmployeeLingual WHERE EmployeeId = @EmployeeId)
	 begin
		SELECT Resource_File_Name,ML.Language_Id FROM TA_Tbl_MultiLingual ML
		inner join TA_Tbl_EmployeeLingual EL on ML.Language_Id=EL.LanguageId
		WHERE EmployeeId=@EmployeeId
	 end
	 else
	 begin
		select Resource_File_Name,Language_Id from TA_Tbl_MultiLingual where Language_Id=1
	 end
END
---------------
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeName] 
	-- Add the parameters for the stored procedure here	
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Employee_FirstName + Space(1) + Employee_LastName as EmployeeName FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeOTEligible]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
Procedure Name	:	Proc_TA_GetEmployeeOTEligible
Description		:	Get whether the OT is Eligible for the particular Employee
Tables Included          	:	TA_Tbl_Employee
Created By		:	Kumuthini.L
Created On		:	19-Feb-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeOTEligible] 
(
   @Employee_Code_Id nVarchar(25)
)
AS
SELECT OT_Eligible FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeRequiredPeriod]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
Procedure Name : Proc_TA_GetEmployeeRequiredPeriod  202,53 
Description  : Get Eligible days for Employees Based on their Employee_Id and LeaveType_ID    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  : 
exec Proc_TA_GetEmployeeRequiredPeriod @Employee_Id=196,@leaveType_Id=18,@LeaveFromDate='2022-08-31 00:00:00',@LeaveToDate='2022-08-31 00:00:00' 
Select * From Ta_tbl_Employee where Employee_Id=196  
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_GetEmployeeRequiredPeriod]    
@Employee_Id bigint,    
@leaveType_Id int,
@LeaveFromDate datetime,
@LeaveToDate datetime    
AS    
declare @test as decimal    
declare @Result as varchar(10)    
if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
BEGIN  
	
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id 
	and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
ELSE
BEGIN
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id 
	--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101))     
if(@test=0)    
 begin    
 set @Result='N'    
  Select @test   
 end    
else    
 begin    
  declare @eligible as decimal    
  if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
  BEGIN    
	  set @eligible=(select distinct (Datediff(d,e.DateOfJoining,getdate()) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id
	  and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) 
	  order by TA_Tbl_Emp_LeavePolicy.ToDate desc))  
	   
  END 
  ELSE
  BEGIN
      set @eligible=(select distinct (Datediff(d,e.DateOfJoining,getdate()) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id
	  --and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) 
	  order by TA_Tbl_Emp_LeavePolicy.ToDate desc)) 
	 
  END
    if (@eligible>=0)    
      begin    
      set @Result='Y'    
      end       
    else    
     begin    
     set @Result='R'    
     end    
end    
select @Result as RemainingNoOfLeaves    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]
	@EmployeeIDs int
AS
BEGIN	
	SET NOCOUNT ON;	
	Select Employee_Status,Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmployeeIDs	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gopinath.k
-- Create date: 16-Dec-16
-- Description:	To fetch the employee worked details based on date for C/off Entry in THDC
-- Proc_Ta_GetEmployeeShiftDateDetails '2019/08/10','787'

--Proc_Ta_GetEmployeeShiftDateDetails '2019/08/15', 'VO357'a
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]
@date nvarchar(20),
@EmployeeCode nvarchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	DECLARE @dateFormat as int	
	declare @EmployeeID as int
	declare @LeaveStatus as nvarchar(100)
	select @DATEFORMAT=DateFormat,@TIMEFORMAT=TimeFormat from [dbo].[Func_TA_GetDateTimeFormat]()
	declare @GetLevelID as int
	select @GetLevelID=EL.LevelId,@EmployeeID=E.Employee_Id from TA_Tbl_EmployeeLevel EL inner join TA_Tbl_Employee E on E.Employee_Id=EL.EmployeeId where E.Employee_Code_Id=@EmployeeCode
    DECLARE @childID INT 
    ;WITH ParentLevel AS
    (
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
        UNION ALL
        SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
        INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
     )
     SELECT TOP 1 @GetLevelID=id FROM ParentLevel r ORDER BY lvl DESC
     declare @CountRecord as int
     SELECT @CountRecord = count(Employee_Id) FROM TA_Tbl_Employee 
		WHERE Leave_Sanc_Authority = Reporting_To AND Employee_Id = @EmployeeID  
	declare @OTApproval as int
	select @OTApproval=OTApproval from TA_Tbl_ApprovalSettings where CompanyId=@GetLevelID
	DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT,@OtText VARCHAR(MAX)
			SELECT		@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,'00:00', ISNULL(OtMinHrs, '00:00')),
						@FullDayOTMins = DATEDIFF(MI,'00:00',ISNULL(FullDayOTMinHrs, '00:00'))
						FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
						WHERE ELP.EmployeeId = @EmployeeID AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
						INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
						WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeID ORDER BY ELP.ToDate DESC)


	IF(@CountRecord > 0)
	BEGIN
		SET @LeaveStatus = 'Forwarded'
	END
	ELSE IF(@CountRecord = 0)
	BEGIN
		SET @LeaveStatus = 'Pending'
	END	
	if(isnull(@OTApproval,0)=0)
	begin
		SET @LeaveStatus = 'Approved'
	end

	print @CountRecord
	print @LeaveStatus

	Select p.Employee_code_id,p.Date,p.Shift_id,
	case when OutTime is not null and OutTime<>'00:00' then
		CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN  CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,p.OutTime,0)), 114) 
				 ELSE substring(convert(varchar(25),convert(datetime,OutTime)),13,5)+' '+ substring(convert(varchar(25),convert(datetime,OutTime)),18,2)
		END 
	end OutTime,
	case when InTime is not null and InTime<>'00:00' then
		CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,p.InTime,0)), 114) 
				ELSE substring(convert(varchar(25),convert(datetime,InTime)),13,5)+' '+ substring(convert(varchar(25),convert(datetime,InTime)),18,2)
		END
	end
	InTime,
	p.NormOt,
	p.OffOt,p.HolOt,E.Employee_FirstName + case when E.Employee_MiddleName is not null then ' ' + cast(E.Employee_MiddleName as varchar(50)) else ' ' end + E.Employee_LastName AS 'Employee Name',case WHEN p.OtMins >= @HalfDayOTMins THEN 'Reached' else 'Not Reached' end as ComStatus,
	CASE when (p.NormOt!='00:00') then 'Week Day' ELSE
	CASE when (p.OffOt!='00:00') then 'Weekly Off' ELSE 
	CASE when (p.HolOt!='00:00') then 'Holiday' ELSE
	'NO OT Record Found' END END END  as  'WeekofftypeNormOt',@GetLevelID 'TopLevelID'
	,E.Employee_Id
	,LD.name as LevelName
	,p.ExtraMins
	,@LeaveStatus as 'OverTimeStatus',p.Process_Rec_ID,
	case when isnull(@HalfDayOTMins,0)=0 then 'LeavePolicyNotAssign' else 'Assign' end as LeavePolicyStatus
	from Ta_tbl_Processeddata p 
	inner join TA_Tbl_Employee E on p.Employee_Code_Id=E.SwipeCardNo
	inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
	inner join Ta_Tbl_levelDetails LD on LD.ID=EL.LevelId where  date = CONVERT(DATETIME,cast(@date as nvarchar(50)), 102) 
	and CompOff_Eligible=1 and OT_Eligible=1 and E.Employee_Code_Id = @EmployeeCode
	--and p.FNAttendanceCode in ('Weekly Off', 'Holiday') and p.ANAttendanceCode in ('Weekly Off', 'Holiday') --for vaighai client  
	--Select E.Employee_FirstName + case when E.Employee_MiddleName is not null then ' ' + cast(E.Employee_MiddleName as varchar(50)) else ' ' end + E.Employee_LastName AS 'Employee Name' from Ta_Tbl_employee Where Employee_code_id=@EmployeeCode
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeSpecificDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <17-07-2019>
-- Description:	<Getting Employee details for reporting to>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeSpecificDetails]
AS
BEGIN
	SET NOCOUNT ON;

    SELECT e.Employee_Id,(e.Employee_FirstName + ' - ' +(e.Employee_Code_Id)) as Employee_FirstName FROM TA_Tbl_Employee e 
	where e.Isdeleted=0 and e.Employee_Firstname<>'Administrator' and ISNULL(e.InActive_Status,0)=0   ORDER BY e.Employee_FirstName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeWhatsAppNumber]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeWhatsAppNumber]
	-- Add the parameters for the stored procedure here
	@tag varchar(20)='ReportingTo',
	@ScheduleId int=4,
	@Email_Id varchar(50)=null,
	@EmailType char(5)=null,
	@IsFlag bit=null,
	@EmployeeID nvarchar(20)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @tblDesignation as Table (des_RowId int,DesigId int, EmployeeID int)
    -- Insert statements for procedure here

	if(@tag='ReportingTo' and isNull(@ScheduleId,0)=0)
	Begin

		insert into @tblDesignation
		  SELECT ED.EmpDesignationID,Ed.DesignationID,ED.EmployeeID FROM TA_Tbl_EmployeeDesignation ED INNER JOIN TA_Tbl_Employee E ON ED.EmployeeID = E.Employee_Id WHERE   ED.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeeDesignation WHERE EmployeeID = ED.EmployeeID)
		 

		--Select * From @tblDesignation

		Select distinct e2.Employee_Id,e2.Employee_Code_Id,e2.Employee_FirstName,TitleName,e2.Mobile_Number,Case when e2.Employee_Status=1 then 'Active' Else 'InActive'End as Employee_Status,
		0 as WhatsAppScheduler_flag From TA_Tbl_Employee e1 
		Inner Join TA_Tbl_Employee e2 on (e1.Reporting_To=e2.Employee_Id or e1.Leave_Sanc_Authority=e2.Employee_Id)
		Inner Join @tblDesignation on EmployeeID=e2.Employee_Id inner Join TA_Tbl_Title on TitleId=DesigId
		where e2.Mobile_Number!=' ' and e2.InActive_Status=0

	End

	Else if(@tag='ToEmployee' and isNull(@ScheduleId,0)=0)
	Begin

		insert into @tblDesignation
		  SELECT ED.EmpDesignationID,Ed.DesignationID,ED.EmployeeID FROM TA_Tbl_EmployeeDesignation ED INNER JOIN TA_Tbl_Employee E ON ED.EmployeeID = E.Employee_Id WHERE   ED.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeeDesignation WHERE EmployeeID = ED.EmployeeID)

		--Select * From @tblDesignation

		Select  e1.Employee_Id,e1.Employee_Code_Id,e1.Employee_FirstName,TitleName,e1.Mobile_Number,Case when e1.Employee_Status=1 then 'Active' Else 'InActive'End as Employee_Status,
		0 as WhatsAppScheduler_flag From TA_Tbl_Employee e1 
		Inner Join @tblDesignation on EmployeeID=e1.Employee_Id inner Join TA_Tbl_Title on TitleId=DesigId
		where e1.Mobile_Number!=' ' and e1.InActive_Status=0

	End

	Else if(@tag='ReportingTo' and isNull(@ScheduleId,0)!=0)
	Begin
		
		print 'yes'

		insert into @tblDesignation
		  SELECT ED.EmpDesignationID,Ed.DesignationID,ED.EmployeeID FROM TA_Tbl_EmployeeDesignation ED INNER JOIN TA_Tbl_Employee E ON ED.EmployeeID = E.Employee_Id WHERE   ED.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeeDesignation WHERE EmployeeID = ED.EmployeeID)
		 
		--Select * From @tblDesignation

		Select distinct e2.Employee_Id,e2.Employee_Code_Id,e2.Employee_FirstName,TitleName,e2.Mobile_Number,Case when e2.Employee_Status=1 then 'Active' Else 'InActive'End as Employee_Status,case when isNull(SE.Employee_id,0)=0 then 0 Else 1 End As WhatsAppScheduler_flag From TA_Tbl_Employee e1
		Inner Join TA_Tbl_Employee e2 on (e1.Reporting_To=e2.Employee_Id or e1.Leave_Sanc_Authority=e2.Employee_Id)
		Inner Join @tblDesignation on EmployeeID=e2.Employee_Id inner Join TA_Tbl_Title on TitleId=DesigId
		Left Join TA_Tbl_WhatsAppScheduled_Employees SE on SE.Employee_id=e2.Employee_Id and SE.ScheduleId=@ScheduleId
		where e2.Mobile_Number!=' ' and e2.InActive_Status=0

	End

	Else If(@tag='ToEmployee' and isNull(@ScheduleId,0)!=0)
	begin
		insert into @tblDesignation
			  SELECT ED.EmpDesignationID,Ed.DesignationID,ED.EmployeeID FROM TA_Tbl_EmployeeDesignation ED INNER JOIN TA_Tbl_Employee E ON ED.EmployeeID = E.Employee_Id WHERE   ED.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeeDesignation WHERE EmployeeID = ED.EmployeeID)

			--Select * From @tblDesignation

			Select  e1.Employee_Id,e1.Employee_Code_Id,e1.Employee_FirstName,TitleName,e1.Mobile_Number,Case when e1.Employee_Status=1 then 'Active' Else 'InActive'End as Employee_Status, case when isNull(SE.Employee_id,0)=0 then 0 Else 1 End As WhatsAppScheduler_flag From TA_Tbl_Employee e1 
			Inner Join @tblDesignation on EmployeeID=e1.Employee_Id inner Join TA_Tbl_Title on TitleId=DesigId
			Left Join TA_Tbl_WhatsAppScheduled_Employees SE on SE.Employee_id=e1.Employee_Id and SE.ScheduleId=@ScheduleId
			where e1.Mobile_Number!=' ' and e1.InActive_Status=0 
	End


END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeWorkedDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- ALTER  date: <ALTER  Date,,>  
-- Description: <Description,,>  
-- =============================================  
--Proc_TA_GetEmployeeWorkedDays '40716',['CL'],'4/1/2008','04/30/2008'  
CREATE   PROCEDURE [dbo].[Proc_TA_GetEmployeeWorkedDays]  
 @EmployeeID as nvarchar(50),   
 @FilterBy as nvarchar(200),  
 @FromDate as nvarchar(15),  
 @ToDate as nvarchar(15)   
AS  
BEGIN  
 declare @SqlQuery as varchar(5000)  
 declare @SqlQuery1 as varchar(5000)  
 create table #Temp1(WorkDays1 varchar(20))    
 create table #Temp2(WorkDays2 varchar(20))   
declare @count1 as float
declare @count2 as float  
declare @count3 as float  
set @SqlQuery = 'Select count(FNAttendanceCode) from Ta_tbl_ProcessedData PD INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo=PD.Employee_Code_Id where ED.Employee_Id='''+ @EmployeeID + ''' '  
Set @SqlQuery = @SqlQuery + ' and  PD.FNAttendanceCode in (' + @FilterBy + ') and PD.date between CONVERT(DATETIME, ''' + cast(@FromDate as nvarchar(11)) + ''', 102) '  
Set @SqlQuery = @SqlQuery + ' and CONVERT(DATETIME, ''' + cast(@ToDate as nvarchar(11)) + ''', 102) '  
set @SqlQuery1 = 'Select count(ANAttendanceCode) from Ta_tbl_ProcessedData PD INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo=PD.Employee_Code_Id where ED.Employee_Id='''+ @EmployeeID + ''' '  
Set @SqlQuery1 = @SqlQuery1 + ' and  (PD.ANAttendanceCode in (' + @FilterBy + ')) and PD.date between CONVERT(DATETIME, ''' + cast(@FromDate as nvarchar(11)) + ''', 102) '  
Set @SqlQuery1 = @SqlQuery1 + ' and CONVERT(DATETIME, ''' + cast(@ToDate as nvarchar(11)) + ''', 102) '  
insert into #Temp1 exec (@SqlQuery)  
insert into #Temp2 exec (@SqlQuery1)  
set @count1=(select isnull(WorkDays1,0) from #Temp1)  
set @count2=(select isnull(WorkDays2,0) from #Temp2)  
if(@count1>0)
begin
set @count1=(@count1)/2
end
if(@count2>0)
begin
set @count2=(@count2)/2
end
drop table #Temp1   
drop table #Temp2  
set @count3=cast(@count1 as float)+ cast(@count2 as float)  
select @count3 as WorkedDays  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEntrance]
AS
BEGIN
	SET NOCOUNT ON;
Select E.Entrance_Name,T.Terminal_ReaderID from TA_Tbl_Entrance E
Inner Join TA_Tbl_Entrance_INOUTDetails ED On ED.Entrance_Id=E.Entrance_Id
Inner Join TA_Tbl_Terminal T On T.Terminal_Id=ED.Reader_Id
Where ED.Type='In'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetEntrance_Angler]
AS
BEGIN
	SET NOCOUNT ON;
Select E.Entrance_Name,T.Terminal_ReaderID from TA_Tbl_Entrance E
Inner Join TA_Tbl_Entrance_INOUTDetails ED On ED.Entrance_Id=E.Entrance_Id
Inner Join TA_Tbl_Terminal T On T.Terminal_Id=ED.Reader_Id
Where ED.Type='In'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEquivalentDeviceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11.29 AM>
-- Description:	<Get Equivalent Device Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEquivalentDeviceDetails]	
	@Type char(1)
AS
BEGIN	
	SET NOCOUNT ON;
	Declare @EntranceType char(3)
	if(@Type='I')
	begin
		set @EntranceType='Out'		
	end
	else if(@Type='O')
	begin
		set @EntranceType='In'
	end
	select stuff((select ',' + Terminal_ReaderId + '' from [TA_Tbl_Entrance_INOUTDetails] En
	inner join TA_Tbl_Terminal Ter on En.Reader_Id = Ter.Terminal_Id 
	where En.Type = @EntranceType AND Ter.IsDeleted = 0 for XML PATH('')),1,1,'') as Terminal_ReaderId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetErrorVersionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	24-Dec-2013
-- Description	:	Get The Error Version Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetErrorVersionDetails]
	@PageName VARCHAR(150),
	@TrackingPlatform VARCHAR(150),
	@ErrorMsg VARCHAR(MAX),
	@ErrorText VARCHAR(MAX)
AS
BEGIN
	DECLARE @ClientName VARCHAR(250), @Version VARCHAR(100), @ProductName VARCHAR(100), @ErrStatus VARCHAR(15)
	DECLARE @BugHistory VARCHAR(MAX), @BugId VARCHAR(1000)
	DECLARE @DateTime DATETIME
	SET @ClientName = (SELECT TOP 1 name FROM Ta_Tbl_levelDetails WHERE parentId = 0 AND isDeleted = 0)
	SET @ProductName = 'Timecheck'	
	SET @DateTime = GETDATE()
	SET @ErrStatus = 'New'
	SET @BugHistory = ''
	SELECT @PageName = displayName FROM TA_Tbl_Page WHERE [path] = @PageName
	SELECT @Version = ApplicationVersionName FROM TA_Tbl_Version
	IF EXISTS(SELECT ErrorMsg FROM TA_Tbl_PageError WHERE ErrorMsg LIKE '%' + @ErrorMsg + '%' AND PageName LIKE '%' + @PageName + '%' )
	BEGIN
		SET @ErrStatus = 'Repeatly'
		SELECT 
			@BugHistory = @BugHistory + (CASE WHEN LEN(ErrorId) = 1 THEN ('Bug No: 000' + CAST(ErrorId AS VARCHAR(1000))) WHEN LEN(ErrorId) = 2 THEN ('Bug No: 00' + CAST(ErrorId AS VARCHAR(1000))) WHEN LEN(ErrorId) = 3 THEN ('Bug No: 0' + CAST(ErrorId AS VARCHAR(1000))) ELSE ('Bug No: ' + CAST(ErrorId AS VARCHAR(1000))) END) + ' ' + ErrorMsg + CHAR(13)
		FROM TA_Tbl_PageError WHERE ErrorMsg LIKE '%' + @ErrorMsg + '%' AND PageName LIKE '%' + @PageName + '%' 
	END
	IF NOT EXISTS(SELECT ErrorMsg FROM TA_Tbl_PageError WHERE ErrorMsg LIKE '%' + @ErrorMsg + '%' AND PageName LIKE '%' + @PageName + '%' )
	BEGIN
		INSERT INTO TA_Tbl_PageError(ErrorMsg, ErrorDetails, PageName, ProductName, ProductVersion, ClientName, TrackingPlatForm, ErrorTime, BugStatus)
				VALUES(@ErrorMsg, @ErrorText, @PageName, @ProductName, @Version, @ClientName, @TrackingPlatform, @DateTime, @ErrStatus)
		SET @BugId = @@IDENTITY
	END
	ELSE
	BEGIN
		SELECT @BugId = MAX(ErrorId) FROM TA_Tbl_PageError WHERE ErrorMsg LIKE '%' + @ErrorMsg + '%' AND PageName LIKE '%' + @PageName + '%' 		
	END
	SET @BugId = (CASE WHEN LEN(@BugId) = 1 THEN ('Bug No: 000' + @BugId) WHEN LEN(@BugId) = 2 THEN ('Bug No: 00' + @BugId) WHEN LEN(@BugId) = 3 THEN ('Bug No: 0' + @BugId) ELSE ('Bug No: ' + @BugId) END)
	SET @BugHistory = (CASE WHEN @BugHistory = '' THEN (@BugId + ' ' + @ErrorMsg) ELSE @BugHistory END)
	SELECT @ErrStatus [BugStatus], REPLACE(CONVERT(VARCHAR(11), @DateTime, 106) , ' ', '-') + ' ' + CONVERT(VARCHAR(11), @DateTime, 108)  [DateTime], @ProductName [ProductName], ISNULL(@Version, '') [Version], ISNULL(@ClientName, '') ClientName, 'ANGLER' [AsignTo], @BugId BugId, @BugHistory BugHistory, @TrackingPlatform TrackingPlatform, ISNULL(@PageName, '') PageName, @ErrorMsg	ErrorMsg, @ErrorText ErrorText
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetExpInfo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetExpInfo]
AS
BEGIN
	select InstalledDate,DemoExpiryDate from TA_Tbl_Demo
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetFirstInDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetFirstInDetails]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50), 
	@inDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_InTime),13,21))) 
	AS FirstIn FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date =  @inDate AND Clk_InDate IS NOT NULL AND IsVoid = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	Getting First In punch details for processing
-- [Proc_Ta_GetFirstInDetailsForService] 2,'2020-04-01'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetFirstInDetailsForService]
	-- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
	@INSWIPECARDNO VARCHAR(50),
	@INDATE DATETIME
AS
BEGIN
	-- SET NOCOUNT ON ADDED TO PREVENT EXTRA RESULT SETS FROM
	-- INTERFERING WITH SELECT STATEMENTS.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
    --samsung client we used below logic.
	--SELECT dbo.Fn_RoundoffHours(@INSWIPECARDNO,@INDATE, MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),CLK_INDATE,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,CLK_INTIME),13,21))),'I') AS FIRSTIN 
	--FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @INSWIPECARDNO AND CLK_DATE = @INDATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0
	
	--This is for product
	SELECT MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),CLK_INDATE,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,CLK_INTIME),13,21))) AS FIRSTIN 
	FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @INSWIPECARDNO AND CLK_DATE = @INDATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInPunchTypeForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GetFirstInPunchTypeForService] '1002','2015-04-06'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetFirstInPunchTypeForService]
	-- Add the parameters for the stored procedure here
	@INSWIPECARDNO VARCHAR(50),
	@INDATE DATETIME
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
	SELECT Clk_InPunchType AS FirstIn 
	FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @INSWIPECARDNO AND CLK_DATE = @INDATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0
	order by Clk_InTime
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetFolderPath_Samsung]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Modified By: Manikandan.rr
-- Modifie On: 22-Oct-2021 06:42 PM
-- Description:	<This procedure get folder paths of Abraj project - windows service>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetFolderPath_Samsung]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--select *,'Detailed Attendance' as ReportType from Ta_Tbl_FolderPathConfiguration 
	select	FolderPathConfiguration_Id, 
			EmployeeFolderPath, 
			OndutyFolderPath, 
			LeaveFolderPath, 
			CreatedBy, 
			CreatedDate, 
			ModifiedBy, 
			ModifiedDate, 
			AttendanceData,
			'Monthly' as ReportType 
	from Ta_Tbl_FolderPathConfiguration 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]  
@FromDate datetime,  
@ToDate datetime  
as  
begin
	SET NOCOUNT ON;
	declare @count as int  
	declare @CheckValue as datetime  
	create table #Temp(FromDate datetime)  
	set @count=0  
	while(@FromDate<=@ToDate)  
	begin  
		set @CheckValue=  
		(select @FromDate as FromDate from ta_tbl_holiday h inner join  
		ta_tbl_yearsetting ys on h.YearSettings_Id=ys.YearSettings_Id   
		where (@FromDate between h.Holiday_FromDate and h.Holiday_ToDate) and h.Holiday_Type='G' and   
		h.IsDeleted=0 and ys.IsActive=1)  
		if(@CheckValue>0)  
		insert into #Temp values(@CheckValue)
		set @FromDate=DateAdd(day,1,@FromDate)  
	end  
	select * from #Temp 
	drop table #Temp  
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getGroupNameById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- Create date: 13-Aug-07
-- Description:	getting usergroup by id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getGroupNameById]
	(
		@groupId int		
	)
AS
BEGIN
	select * from ta_tbl_userGroup where groupId= @groupId
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetGroupNameForEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_GetGroupNameForEmployee]
(
   @EmployeeId int
)
AS
select ug.groupName from TA_Tbl_Employee emp,TA_Tbl_Usergroup ug where emp.UserGroup_Id = ug.groupId and ug.isDeleted = 0 and emp.Employee_Id = @EmployeeId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHelpContent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetHelpContent]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT Header,Paragraph from ta_tbl_HelpContent
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidayDetailsByHolidayID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetHolidayDetailsByHolidayID] 
	@HolidayID int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	select @dateFormat =DateFormat from dbo.Func_TA_GetDateTimeFormat()
	select	case when Holiday_Type='G' then 'Global Holiday'
				when Holiday_Type='Y' then 'Restricted Holiday' 
			end as Holiday_Type	
	,Holiday_Description,
	convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,
	convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate
	from TA_Tbl_Holiday where Holiday_Id=@HolidayID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidaySettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetHolidaySettings]  
AS  
BEGIN  
	SELECT hs.Global_Maxdays,hs.Yearly_Maxdays,hs.YearSettingId FROM TA_Tbl_HolidaySettings hs
	inner join TA_TBL_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId   
	where ys.IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInAndOutPunchDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 12.45PM>
-- Description:	<Get in and Out Punch Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetInAndOutPunchDetails]
	@inClk_Id bigint,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='O')
	begin
		SELECT Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_Id = @inClk_Id
	end
	else if(@Type='I')
	begin
		SELECT Clk_Date,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_Id = @inClk_Id
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInformToEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	14-May-2014
-- Description	:	Get The All Active Employee List For Leave Application Inform To Field Value
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetInformToEmployee]
AS
BEGIN
	SELECT Employee_FirstName + (CASE WHEN ISNULL(Employee_MiddleName, '') <> '' THEN ' ' + Employee_MiddleName ELSE '' END) + (CASE WHEN ISNULL(Employee_LastName, '') <> '' THEN ' ' + Employee_LastName ELSE '' END) [EmployeeName] FROM TA_Tbl_Employee
		WHERE IsDeleted = 0 AND Employee_Status = 1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLanguageDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
Procedure Name	:	Proc_TA_GetLanguageDetails
Description	:	Get All Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	17-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetLanguageDetails] 
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM TA_Tbl_MultiLingual order by Language_Name
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastLogin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetLastLogin]
(
	@UserName VARCHAR(15)
)
AS
begin
	SELECT LastLoginTime,LastLogoutTime FROM TA_Tbl_Login WHERE UserName=@UserName
end
SET QUOTED_IDENTIFIER OFF
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastOutDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLastOutDetails]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50), 
	@inDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	AS LastOut FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @inDate AND Clk_OutDate IS NOT NULL AND IsVoid = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetLastOutDetailsForService]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo VARCHAR(50),
	@inDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) AS LastOut 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @inDate AND Clk_OutDate IS NOT NULL AND IsVoid = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Last punch(Max Punch) details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLastOutForService]
	-- Add the parameters for the stored procedure here
	@Employeecode varchar(50),
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	AS LastOut FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @Date AND Clk_OutDate IS NOT NULL AND IsVoid = 0	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Last punch(Max Punch) details
-- [Proc_Ta_GetLastOutForServiceDataProcess] 2,'01/04/2020',1,2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]
	-- Add the parameters for the stored procedure here
	@Employeecode varchar(50),
	@ShiftDate datetime,
	@CompanyId int,
	@intShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @strLastOutDateTime datetime
	Declare @strLastInDateTime datetime
	Declare @strLastIn_DeviceID varchar(20)
	Declare @strFinalLastOut varchar(30)
	Declare @ShiftType bit
	Declare @EMPLOYEEAUTOID int
	Declare @InAndOut_Same int
	select @EMPLOYEEAUTOID=Employee_Id from TA_Tbl_Employee where SwipeCardNo=@Employeecode and Isdeleted=0
	SELECT @strLastOutDateTime=MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @ShiftDate AND Clk_OutDate IS NOT NULL AND IsVoid = 0	
	/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--if(@intShiftId=-1)
	--BEGIN
	--	CREATE TABLE #TEMPFreescan (SHIFTID INT)
	--	WHILE @intShiftId=-1
	--	BEGIN			
	--		set @DATE=DATEADD(d,-1,@DATE)
	--		DECLARE @QUERY VARCHAR(2000)   
	--		DECLARE @SHIFTID INT
	--		SET @SHIFTID=0
	--		DECLARE @ISDELETED INT				
	--		DECLARE @YEAR VARCHAR(5)
	--		DECLARE @MONTH VARCHAR(5)
	--		SET @YEAR=DATEPART(YEAR,@DATE)
	--		SET @MONTH=DATEPART(MONTH,@DATE)	
	--		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	--		SET @QUERY = '	SELECT (TSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
	--						WHERE TSA.[YEAR]= ' + @YEAR + '  AND  TSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = '''+ CONVERT(VARCHAR(10),@EMPLOYEEAUTOID) +''' '	
	--		INSERT INTO #TEMPFreescan EXEC(@QUERY)
	--		SET @SHIFTID = (SELECT SHIFTID FROM #TEMPFreescan)
	--		SET @SHIFTID = ISNULL(@SHIFTID,0) 
	--		DELETE FROM #TEMPFreescan
	--		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	--		IF(@SHIFTID = 0)
	--			BEGIN
	--				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
	--								WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' +  CONVERT(VARCHAR(10),@EMPLOYEEAUTOID) +''''
	--				INSERT INTO #TEMPFreescan EXEC(@QUERY)
	--				SET @SHIFTID = (SELECT SHIFTID FROM #TEMPFreescan)
	--				SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--				DELETE FROM #TEMPFreescan
	--			END
	--		IF(@SHIFTID != 0)
	--			BEGIN			
	--				IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
	--					BEGIN
	--						SET @SHIFTID = ISNULL(@SHIFTID,0)			
	--					END
	--			END		
	--		-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	--		IF(@SHIFTID = 0)
	--			BEGIN
	--				SET @SHIFTID = (SELECT @SHIFTID FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID)
	--				SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--				IF(@SHIFTID = 0)
	--					BEGIN					
	--						SET @SHIFTID = (SELECT SHIFT_ID FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0)
	--						SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--					END
	--			END
	--		IF(@SHIFTID > 0)
	--			BEGIN
	--				SELECT @intShiftId=ISNULL(@SHIFTID,0) FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
	--			END
	--		ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
	--			BEGIN
	--				SELECT @intShiftId=@SHIFTID
	--			END		
	--	end
	--	DROP TABLE #TEMPFreescan
	--end
	--Getting the shift Type for checking whether the type is freescan or function key
	/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--select @ShiftType=ShiftType from TA_Tbl_Shift where Shift_Id=@intShiftId and Isdeleted=0
	set @strFinalLastOut=''
	--select @ShiftType
    -- Insert statements for procedure here
    /**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--if(@ShiftType=1)
	--begin
		IF((SELECT ISNULL(FIRSTANDLAST,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID=@COMPANYID)=1)
		BEGIN
			--select 'entered'
			/**Below line is added by Manikandan.R on 28-May-2019 06:12 PM
			--First and last punch concept should be worked for function key logic too*/
			IF((SELECT COUNT(*) FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @EMPLOYEECODE AND CLK_DATE = @ShiftDate AND CLK_INDATE IS NOT NULL AND ISVOID = 0)>1)
			BEGIN
				SELECT @strLastInDateTime=MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + ' ' + SUBSTRING(CONVERT(VARCHAR,Clk_InTime),13,21)))
				FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @ShiftDate AND Clk_InDate IS NOT NULL AND IsVoid = 0			
			END
			/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
			--First and last punch concept should be worked for function key logic too*/
			--SELECT @strLastIn_DeviceID=Clk_InDeviceId
			--FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @ShiftDate AND Clk_InDate IS NOT NULL AND IsVoid = 0
			--and Clk_InDate+Clk_InTime=@strLastInDateTime
			--select @InAndOut_Same=count(TYPE) from ta_tbl_entrance_inoutdetails EIO 
			--inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
			--where T.Terminal_ReaderID=@strLastIn_DeviceID
			--if @InAndOut_Same=1
			--begin
			--	set @strLastInDateTime=null
			--end			
		END
	--end
	--select @strLastOutDateTime,@strLastInDateTime
	IF (@strLastOutDateTime is not null and @strLastInDateTime is not null and @strLastOutDateTime!='1900-01-01 00:00:00.000' and  @strLastInDateTime!='1900-01-01 00:00:00.000')
	BEGIN
		IF (CONVERT(DATETIME,@strLastOutDateTime) > Convert(datetime,@strLastInDateTime))
        BEGIN
			SET @strFinalLastOut = @strLastOutDateTime;
		END
        ELSE
        BEGIN
			SET @strFinalLastOut = @strLastInDateTime;
		END
	END
    ELSE IF (@strLastOutDateTime != '' and @strLastOutDateTime!='1900-01-01 00:00:00.000')
	BEGIN
		SET @strFinalLastOut = @strLastOutDateTime;
	END
	ELSE IF (@strLastInDateTime != '' and @strLastInDateTime!='1900-01-01 00:00:00.000')
	BEGIN
		SET @strFinalLastOut = @strLastInDateTime;
	END
	if(@strFinalLastOut!='')
	begin
		--Samsung Client
		--SELECT LastOut=dbo.Fn_RoundoffHours(@Employeecode,@ShiftDate,@strFinalLastOut,'O')
		--product
		SELECT LastOut=@strFinalLastOut
	end
	else
	begin
		SELECT LastOut=@strFinalLastOut
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveAndOndutyApprovalsForEmailTriggerring]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveAndOndutyApprovalsForEmailTriggerring]
	@ScheduleID bigint
AS
BEGIN
	
	SET NOCOUNT ON;
	
	select * from TA_Tbl_EmailScheduled_Employees 
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name		:	Proc_TA_GetLeaveApplicationByLeaveApplicationId 1094
Description		:	Get Leave Application Details of Employees Based on their LeaveApplication_Id
Tables Included		:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]
@LeaveApplication_Id int =null
as
declare @strLeaveType as nvarchar(50)
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as INT
	set @dateFormat =(Select DateFormat from dbo.Func_TA_GetDateTimeFormat())
	set @strLeaveType=(select Type from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and isdeleted=0)	
	DECLARE @FileNotFound as varchar(200) = 'File Not Found';
	DECLARE @FileFound as varchar(200) = 'Download';
	if(@strLeaveType='Leave' or @strLeaveType='LOP')
		begin
			select E.Employee_Code_Id as employeeid,
			la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end 
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			(lt.LeaveType + ' / '  + la.Type) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority
			,LA_FU.FileName as Download,
			case when LA_FU.FileName is null then cast(@FileNotFound as varchar(100)) else cast(@FileFound as varchar(100)) end as Result
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_LeaveType lt   
			on la.LeaveType_Id = lt.LeaveType_Id
			inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id 
			left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on LA.LeaveApplication_Id = LA_FU.LeaveApplication_Id 
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and lt.Isdeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
	else if(@strLeaveType='Comp Off' or @strLeaveType='ESI')
		begin
			select E.Employee_Code_Id as employeeid,la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end 
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			('Others ' + '/' +la.Type) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority
			,LA_FU.FileName as Download,
			case when LA_FU.FileName is null then cast(@FileNotFound as varchar(100)) else cast(@FileFound as varchar(100)) end as Result
			from  TA_Tbl_LeaveApplication la  
			inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
			left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on LA.LeaveApplication_Id = LA_FU.LeaveApplication_Id 
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
	if(@strLeaveType='Restricted Holiday')
		begin
			select E.Employee_Code_Id as employeeid,la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			(la.Type + ' / ' +h.Holiday_Description) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority
			,LA_FU.FileName as Download,
			case when LA_FU.FileName is null then cast(@FileNotFound as varchar(100)) else cast(@FileFound as varchar(100)) end as Result
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_Holiday h  
			on la.LeaveType_Id = h.Holiday_Id  
			inner join TA_Tbl_Employee e 
			on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
			left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on LA.LeaveApplication_Id = LA_FU.LeaveApplication_Id 
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name  : Proc_TA_GetLeaveApplicationByLeaveApplicationId 7601 
Description  : Get Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included  : TA_Tbl_LeaveApplication  
Created By  : Prabakaran  
Created On  : 24-Jul-07  
Modified By  :   A.K.T.MOORTHI
Modified On  :   24-JUN-2013
Description		:	Add Information To Column In Query
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler] 
@LeaveApplication_Id int =null 
as  
SET NOCOUNT ON;
declare @strLeaveType as nvarchar(50)  
BEGIN  
set @strLeaveType='Leave'  
if(@strLeaveType='Leave')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
case la.Type when 'Comp Off' then 'Others' else lt.LeaveType end as LeaveType,
--(lt.LeaveType) as LeaveType,  
la.Leave_FromDate as LeaveFrom,  
la.Leave_ToDate as LeaveTo,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID ,la.CheckedIDs  ,
la.InformTo
from  TA_Tbl_LeaveApplication la 
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
left outer join TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id  and lt.Isdeleted=0 
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId  
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId 
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id     
where la.LeaveApplication_Id = @LeaveApplication_Id  and la.IsDeleted=0 and la.Type!='LOP'  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
union all  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
('Others ') as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID   ,la.CheckedIDs ,la.InformTo
from  TA_Tbl_LeaveApplication la 
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id   
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId 
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id  and la.IsDeleted=0 and la.Type='LOP'  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
select * from TA_Tbl_LeaveApplicationMaster where LeaveApplication_Id=@LeaveApplication_Id  and Isdeleted=0
end  
else if(@strLeaveType='Comp Off' or @strLeaveType='ESI')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
('Others ' + '/' +la.Type) as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName,  
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID ,la.CheckedIDs  ,la.InformTo 
from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId  
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
end  
if(@strLeaveType='Restricted Holiday')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
(la.Type + ' / ' +h.Holiday_Description) as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID  ,la.CheckedIDs   , la.InformTo
from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
inner join  TA_Tbl_Holiday h on la.LeaveType_Id = h.Holiday_Id    
inner join TA_Tbl_Employee e  on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
end  
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationCancellation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name		:	Proc_TA_GetLeaveApplicationCancellation 10
Description		:	Get Leave Application Details of Employees Based on their LeaveApplication_Id
Tables Included		:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationCancellation]
@LeaveApplication_Id int =null
as
declare @strLeaveType as nvarchar(50)
BEGIN
SET NOCOUNT ON;
set @strLeaveType='Leave'
if(@strLeaveType='Leave' or @strLeaveType='LOP')
begin
	select la.Type as [Leave Category], (lt.LeaveType) as [Leave Type],la.Leave_FromDate as [LeaveFrom],la.Leave_ToDate as [LeaveTo],'' as [From],'' as [To],la.Leave_SessionFrom as [Session From],la.Leave_SessionTo as [Session To],la.NumberOfDays as [No of Days],la.Status as Status,la.IsDeleted as IsDeleted,la.IntimationType as IntimationType from  TA_Tbl_LeaveApplication la inner join  TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id where la.LeaveApplication_Id = @LeaveApplication_Id and lt.Isdeleted=0 And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
else if(@strLeaveType='Comp Off' or @strLeaveType='ESI')
begin
select la.LeaveApplication_Id as LeaveApplication_Id,
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,
e.Employee_Code_Id as Employee_Code_Id,
e.emailId as emailId,
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,
la.Leave_ApplicationDate as Leave_ApplicationDate,
la.LeaveType_id as LeaveType_id,
la.Type as Type,
('Others ' + '/' +la.Type) as LeaveType,
la.Leave_FromDate as Leave_FromDate,
la.Leave_ToDate as Leave_ToDate,
la.Leave_SessionFrom as Leave_SessionFrom,
la.Leave_SessionTo as Leave_SessionTo,
la.NumberOfDays as NumberOfDays,
la.Reason as Reason,
la.Status as Status,
la.IsDeleted as IsDeleted,
la.Remarks as Remarks,
la.IsBorrow as IsBorrow,ld.name as LevelName, ld.id as levelid,
la.IntimationType as IntimationType
 from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
where la.LeaveApplication_Id = @LeaveApplication_Id
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
if(@strLeaveType='Restricted Holiday')
begin
select la.LeaveApplication_Id as LeaveApplication_Id,
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,
e.Employee_Code_Id as Employee_Code_Id,
e.emailId as emailId,
(e.Employee_FirstName + ' ' + isnull(e.Employee_LastName,'')) as Employee_FirstName,
la.Leave_ApplicationDate as Leave_ApplicationDate,
la.LeaveType_id as LeaveType_id,
la.Type as Type,
(la.Type + ' / ' +h.Holiday_Description) as LeaveType,
la.Leave_FromDate as Leave_FromDate,
la.Leave_ToDate as Leave_ToDate,
la.Leave_SessionFrom as Leave_SessionFrom,
la.Leave_SessionTo as Leave_SessionTo,
la.NumberOfDays as NumberOfDays,
la.Reason as Reason,
la.Status as Status,
la.IsDeleted as IsDeleted,
la.Remarks as Remarks,
la.IsBorrow as IsBorrow,ld.name as LevelName, ld.id as levelid,
la.IntimationType as IntimationType 
from  TA_Tbl_LeaveApplication la  
inner join  TA_Tbl_Holiday h  
on la.LeaveType_Id = h.Holiday_Id  
inner join TA_Tbl_Employee e 
on e.Employee_Id=la.Employee_Id
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
where la.LeaveApplication_Id = @LeaveApplication_Id and h.Isdeleted=0
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCommentsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_GetLeaveCommentsById 10 
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveCommentsById]
@LeaveApplicationId int
as
BEGIN
SET NOCOUNT ON;
declare @intOrderBy as int
declare @intCommentsBy as int
set @intOrderBy = (SELECT max(OrderBy) from TA_Tbl_LeaveConversation where LeaveApplicationId=@LeaveApplicationId)
set @intCommentsBy=(SELECT CommentsBy from TA_Tbl_LeaveConversation where OrderBy=@intOrderBy and LeaveApplicationId=@LeaveApplicationId)
select isnull(@intCommentsBy,0) as CommentsBy
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetLeaveConversation 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveConversation] 
	-- Add the parameters for the stored procedure here	
	@leaveApplicationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_LeaveConversation WHERE LeaveApplicationId = @leaveApplicationId Order By OrderBY Desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCountSanctionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
[Proc_TA_GetLeaveCountSanctionDetails] '65','Project Manager'
*/
create PROCEDURE [dbo].[Proc_TA_GetLeaveCountSanctionDetails] 
@Employee_Id int,
@UserGroupName varchar(250) 
as
Begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
		 --Get current date time format.
      DECLARE @dateFormat as INT
      set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
    Insert Into #TempPermissionDetails 
		select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
		from ta_tbl_employee where Isdeleted=0 and Employee_Status=1
declare @sqlQuery as nvarchar(max)
declare @sqlQuery1 as nvarchar(max)
set @sqlQuery=''
set @sqlQuery1=''
set @sqlQuery = 'select  
                                    count(case  when LA.Status=''Approved'' and E.LeaveSanction=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1  end)Approved,
                                    count(case  when LA.Status=''Forwarded'' and E.LeaveSanction=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1 end)Forwarded,
                                    count(case  when LA.Status=''Pending'' and (E.ReportTo=''' +cast(@Employee_Id as nvarchar(50))   + ''' or E.LeaveSanction=''' +cast(@Employee_Id as nvarchar(50))   + ''') then 1  end)Pending from #TempPermissionDetails E '
set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id '
set @sqlQuery = @sqlQuery + ' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id '
set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id '
set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '
set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '
set @sqlQuery = @sqlQuery + ' where' 
set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'
set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) '
	if(@Employee_Id!='')
	begin
		set @sqlQuery = @sqlQuery + ' and (E.ReportTo=''' +cast(@Employee_Id as nvarchar(50))   + ''' or E.LeaveSanction=''' +cast(@Employee_Id as nvarchar(50))   + ''')'
	end
	--print(@sqlQuery)
		exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop Table #TempPermissionDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]
( @LeavetypeId INT )
AS  
Begin
  SET NOCOUNT ON;
	SELECT LeaveDescription FROM TA_Tbl_LeaveType Where LeaveType_Id=@LeavetypeId 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]  
AS    
BEGIN  
	SET NOCOUNT ON;
	SELECT id,LOP,LOPDescription FROM TA_Tbl_LeaveMasterLOP 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[Proc_TA_GetLeaveMasterDetails] as          
BEGIN        
SET NOCOUNT ON;  
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,      
 S.Section_Name,S.Section_Id,T.TitleName,T.TitleId,L.LeaveType,L.LeaveType_Id, A.LOP,A.[id] From TA_Tbl_LeaveMaster A      
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                    
    join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                    
    join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id                    
    JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id            
    JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id            
    JOIN TA_Tbl_Title T ON T.TitleId=A.Title_Id         
    JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=A.LeaveType_Id      
   -- JOIN TA_Tbl_LeaveMasterLOP LP ON LP.id=A.LeaveType_Id    
WHERE A.IsDeleted=1  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_GetLeaveMasterDetailsById]        
(         
 @id int       
)         
As        
 DECLARE @Isdel int        
 SET @Isdel=1        
BEGIN   
	SET NOCOUNT ON;     
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,  
 S.Section_Name,S.Section_Id,T.TitleName,T.TitleId,L.LeaveType,L.LeaveDescription,L.LeaveType_Id, A.LOP From TA_Tbl_LeaveMaster A  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                
    join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                
    join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id                
    JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id        
    JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id        
    JOIN TA_Tbl_Title T ON T.TitleId=A.Title_Id     
    JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=A.LeaveType_Id  
WHERE A.IsDeleted=1  AND A.id=@id        
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePolicyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	[Proc_TA_GetLeavePolicyDetails] '',null,null,null,null
CREATE Proc [dbo].[Proc_TA_GetLeavePolicyDetails]
(    
    @UserGroupName nVarchar(250),
    @EmployeeCategory varchar(50)=null,
    @EmployeeType varchar(50)=null,
    @Gender varchar(10)=null,
    @Religion varchar(20)=null    
)    
AS      
Begin
	SET NOCOUNT ON;
	DECLARE @SQL NVARCHAR(MAX)
	IF(@UserGroupName = 'SuperAdmin')    
		BEGIN    		
			SET @SQL='SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,isnull(isWFH,0) as isWFH FROM TA_Tbl_LeaveType 
			Where IsDeleted=0'						
		END    
	ELSE    
		BEGIN        
			SET @SQL='SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,isnull(isWFH,0) as isWFH FROM TA_Tbl_LeaveType 
			Where IsDeleted=0'
		END    		
	IF @EmployeeCategory is not null
		begin
			if @EmployeeCategory=0
				begin
					set @SQL= @SQL+ ' and (EmployeeCategory in (select EmployeeCategory from ta_tbl_Leavetype) or EmployeeCategory=0)'
				end
			else
				begin
					set @SQL= @SQL+ ' and (EmployeeCategory=' +CONVERT(varchar(10),@EmployeeCategory) +' or EmployeeCategory=0)' 
				end
		end
	IF  @EmployeeType is not null
		if @EmployeeType=0
			begin
				set @SQL= @SQL+ ' and (EmployeeType in (select EmployeeType from ta_tbl_Leavetype) or EmployeeType=0)'
			end
		else			
			begin
				set @SQL= @SQL+ ' and (EmployeeType=' +CONVERT(varchar(10),@EmployeeType)+' or EmployeeType=0)' 
			end
	IF  @Gender is not null
		begin
			if @Gender='Both'
				begin
					set @SQL= @SQL + ' and (Gender=''Female'' or Gender=''Male'' or Gender=''Both'')'
				end
			else
				begin
					set @SQL= @SQL + ' and (Gender='''+CONVERT(varchar(10),@gender)+''' or Gender=''Both'')'
				end
		end
	IF  @Religion is not null-- and @Religion<>0
		IF @Religion=0
			begin
				set @SQL= @SQL + ' and (Religion in(select Religion from Ta_tbl_LeaveType) or Religion=0)'
			end
		else
			begin
				set @SQL= @SQL + ' and (Religion='+CONVERT(varchar(10),@Religion)+' or Religion=0)'
			end			
	set @SQL= @SQL+ ' order by LeaveType_Id'
	execute(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePrivateNotes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetLeavePrivateNotes 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeavePrivateNotes] 
	-- Add the parameters for the stored procedure here	
	@leaveApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LP.LeavePrivateNotesId,LP.LeaveApplicationId,(Emp.Employee_FirstName + ' ' + isnull(Emp.Employee_LastName,'')) as NotesBy,LP.Notes,LP.OrderBy,LP.ToMailIds,LP.CcMailIds,
	LP.Emp_Id,LP.TimeStamp,Emp.EmailId as FromMailId FROM TA_Tbl_LeavePrivateNotes LP
	INNER JOIN TA_Tbl_Employee Emp on Emp.Employee_Id=LP.NotesBy
	WHERE LP.LeaveApplicationId = @leaveApplicationId 
	Order By OrderBY Desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : 
Proc_TA_GetLeaveSanctionDetails '6','1','All','11/01/2019','01/31/2020',0,'','','','Project Manager','1',0,0
select * from ta_tbl_leaveapplication
Description : Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee
Created By : Prabakaran
Created On : 23-Jul-07
Modified By : Prabakaran
Modified On : 24-Jul-07
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails] 
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(max) =null,
@Leave_FromDate datetime =null,
@Leave_ToDate datetime =null,
@Isdeleted bit =0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250), 
@ParentId int,
@EmployeeCategory int, 
@EmployeeType int
as
Begin
	SET NOCOUNT ON;
	if(substring(CONVERT(varchar(20),@Leave_FromDate),1,5)='01/01' and substring(CONVERT(varchar(20),@Leave_ToDate),1,5)='31/12')
	begin		
		set @Leave_ToDate=substring(CONVERT(varchar(20),@Leave_ToDate),4,2)+'/'+substring(CONVERT(varchar(20),@Leave_ToDate),1,2)+'/'+
		substring(CONVERT(varchar(20),@Leave_ToDate),7,4)
	end
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
		 --Get current date time format.
    DECLARE @dateFormat as INT
    set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
    declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	--Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
	
	--select * from #TempPermissionDetails 
	--	Insert Into #TempPermissionDetails 
	--	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	DECLARE @FileNotFound as varchar(200) = 'File Not Found';
	DECLARE @FileFound as varchar(200) = 'Download';
	set @sqlQuery=''
	set @sqlQuery1=''
	set @sqlQuery = 'select e.employee_code_id as employeeid,ld.name,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,
	LA.LeaveApplication_Id,
	LA.Status,
	case when LT.LeaveType is not null then LT.LeaveType + '' - ''+ LA.Type else LA.Type end as Type, 
	case when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') else CONVERT(VARCHAR, LA.Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') end AS Leave_ApplicationDate,
	case when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') else CONVERT(VARCHAR, la.Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') end + '' - '' + case when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') else CONVERT(VARCHAR, la.Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') end +'' (''+ convert(varchar(10),NumberOfDays)+ case when NumberOfDays<=1 then '' day'' else '' days'' end+'')'' AS Duration,'
	set @sqlQuery = @sqlQuery + ' NumberOfDays=convert(varchar(20),LA.NumberOfDays),ReportTo,LeaveSanction,E.Employee_id,LA.Reason 
	,LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
	from #TempPermissionDetails E '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id '
	set @sqlQuery =@sqlQuery + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on LA.LeaveApplication_Id = LA_FU.LeaveApplication_Id '
	set @sqlQuery = @sqlQuery + ' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '
	set @sqlQuery = @sqlQuery + ' where' 
	--set @sqlQuery = @sqlQuery + ' or and '
	set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'
	set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) '
	If not(@strEmployeeCodeId = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		End
	If Not (@strSwipeCardNo = '') 
		Begin 
			Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' ' 
		End 
	If not(@strEmployeeName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName +'' ''+ isnull(E.Employee_LastName,'''') like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''')'
		End		 
	if(@isReportingto > 0)
			BEGIN
			   set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
			END
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if (@UserGroupName!='Superadmin' and @isReportingto!=0)
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((LA.Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
				set @sqlQuery = @sqlQuery + ' or (LA.Status IN (''Forwarded'',''Approved'',''Rejected'')and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)+'))'
			end
	end
	else 
	begin
		set @sqlQuery = @sqlQuery + ' and (LA.Status IN (select value from split(''' + @Status  + ''','','')))'
	End		
	--print(@sqlQuery)		
	--select value from split(@Status,',')
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop Table #TempPermissionDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : 
Proc_TA_GetLeaveSanctionDetails '161','107','Pending,Forwarded,Rejected','01/Nov/2014','26/Dec/2014',0,'','','','Project Leader - MS','107'
select * from ta_tbl_leaveapplication
Description : Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee
Created By : Prabakaran
Created On : 23-Jul-07
Modified By : Prabakaran
Modified On : 24-Jul-07, 14May14 by Gopinath
 // Modified the datetime format conversion due to Bug no.24001
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler] 
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(100) =null,
@Leave_FromDate varchar(20) =null,
@Leave_ToDate varchar(20) =null,
@Isdeleted bit =0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250), 
@ParentId int 
as
begin
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery1=''
	set @sqlQuery = 'select ld.name,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,LA.LeaveApplication_Id,LA.Status,LA.Type,case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, LA.Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') end  AS Leave_ApplicationDate,
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, LA.Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end 
		+ '' - '' +
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, LA.Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end 	
		AS Duration from #TempPermissionDetails E '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '
	set @sqlQuery = @sqlQuery + ' where' 
	set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'
	set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate and LA.Leave_FromDate >= CONVERT(DATETIME,'''+cast(@Leave_FromDate as nvarchar(20))+''', 102) and LA.Leave_ToDate <= CONVERT(DATETIME,'''+cast(@Leave_ToDate as nvarchar(20))+''', 102) order by EffectiveDate desc) '
	If not(@strEmployeeCodeId = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		End
	If Not (@strSwipeCardNo = '') 
		Begin 
			Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' ' 
		End 
	If not(@strEmployeeName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName +'' ''+ isnull(E.Employee_LastName,'''') like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''')'
		End
		 if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))'	
			end
		else if not(@Status is null or @Status='' or @Status='0')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status  + '''))'
			End
			exec(@sqlQuery)
		drop table #LevelRights
		drop table #TempPermissionDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Description		: Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee    
[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin] '','','Pending','04/01/2016','12/31/2020',0,'','','','SuperAdmin','0',0,0
*/    
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin] 
@Employee_ID int,   
@LevelId varchar(2000),    
@Status varchar(100) =null,    
@Leave_FromDate varchar(20)=null,    
@Leave_ToDate varchar(20) =null,    
@Isdeleted bit = 0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250),
@ParentID int,
@EmployeeCategory int, 
@EmployeeType int
as    
begin
	set nocount on
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	Declare @SuccessiveTodate datetime	
	Declare @LevelId1 varchar(2000)
	DECLARE @dateFormat as int
	DECLARE @FileNotFound as varchar(200) = 'File Not Found';
	DECLARE @FileFound as varchar(200) = 'Download';
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @LevelId1=@ParentID
		while((select Id from TA_tbl_LevelDetails where id=@LevelId1) <> '') 
			BEGIN 							
				if((select levelID from TA_tbl_LevelDetails where Id=@LevelId1) <> 1)
					begin						
						set @LevelId1 = (select parentId from TA_tbl_LevelDetails where id=@LevelId1)						
					end
				else
					begin
						break
					end
			ENd
	set @LevelId=@LevelId1
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=DATEADD(d,@SuccessiveDays,TODATE) from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveTodate=TODATE from TA_Tbl_YearSetting where IsActive=1	
	create table #LevelRights(LevelId int)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
    
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
    
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	--select * from #TempPermissionDetails
	
	
	
	set @sqlQuery=''
	set @sqlQuery = 'select	E.Employee_Code_Id as employeeid,
							ld.name,
							(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,LA.LeaveApplication_Id,
							LA.Status,
							case when LT.LeaveType is not null then LT.LeaveType + '' - ''+ LA.Type else LA.Type end as Type,	
							case when '+cast(@dateFormat as varchar(100))+'=106 then	REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
								 else CONVERT(VARCHAR, LA.Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') 
							end  AS Leave_ApplicationDate,
							case when '+cast(@dateFormat as varchar(100))+'=106 then REPLACE(CONVERT(VARCHAR, LA.Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
								 else CONVERT(VARCHAR, LA.Leave_FromDate, '+cast(@dateFormat as varchar(100))+') 
							end 
							+ '' - '' +
							case when '+cast(@dateFormat as varchar(100))+'=106 then	REPLACE(CONVERT(VARCHAR, LA.Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
								 else CONVERT(VARCHAR, LA.Leave_ToDate, '+cast(@dateFormat as varchar(100))+') 
							end +'' (''+ convert(varchar(10),NumberOfDays)+ case when NumberOfDays<=1 then '' day'' else '' days'' end+'')''
	AS Duration,la.NumberOfDays,LA.Reason,LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
							from #TempPermissionDetails E '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id '
	set @sqlQuery =@sqlQuery + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on LA.LeaveApplication_Id = LA_FU.LeaveApplication_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId '    
	set @sqlQuery = @sqlQuery + ' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '    
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=el.levelID '
	set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and LA.IsDeleted=0 ' 
	set @sqlQuery = @sqlQuery + ' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) '
	If not(@strEmployeeCodeId = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		End
	If Not (@strSwipeCardNo = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' '  
		End 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If not(@strEmployeeName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName +'' ''+ isnull(E.Employee_LastName,'''') like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''')'
		End	
	--if not(@Status is null or @Status='' or @Status='All')
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and LA.Status IN (''' + @Status  + ''')'
	--	End
	if (@UserGroupName!='Superadmin' and @isReportingto!=0)
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((LA.Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
				set @sqlQuery = @sqlQuery + ' or (LA.Status IN (''Forwarded'',''Approved'',''Rejected'')and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)+'))'
			end
	end
	else 
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (LA.Status IN (''' + @Status + '''))'
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((LA.Status IN (''Pending''))'
				set @sqlQuery = @sqlQuery + ' or (LA.Status IN (''Forwarded'',''Approved'',''Rejected'')))'
			end
	End	
	
	
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
		end
	if not(cast(@Leave_FromDate as nvarchar(11))='' or cast(@Leave_FromDate as nvarchar(11))='0')
		begin
			--commented on 13-Feb-2020 06:24 PM in scufe client. by maniknadan.rr
			--set @sqlQuery = @sqlQuery + ' and LA.Leave_FromDate>=CONVERT(DATETIME, ''' + cast(@Leave_FromDate as nvarchar(11)) + ''', 102)'
			set @sqlQuery = @sqlQuery + ' and ((CONVERT(DATETIME, ''' + cast(@Leave_FromDate as nvarchar(11)) + ''', 102) between LA.Leave_FromDate and LA.Leave_ToDate) or'
			set @sqlQuery = @sqlQuery + ' (CONVERT(DATETIME, ''' + cast(@Leave_ToDate as nvarchar(11)) + ''', 102) between LA.Leave_FromDate and LA.Leave_ToDate)
			or 
			(LA.Leave_FromDate>=CONVERT(DATETIME, ''' + cast(@Leave_FromDate as nvarchar(11)) + ''', 102)and LA.Leave_ToDate<=CONVERT(DATETIME, ''' + cast(@Leave_ToDate as nvarchar(11)) + ''', 102))
			)'
		End
	--if(@Leave_ToDate >= @ToDate)
	--	begin
	--		set @Leave_ToDate=@ToDate
	--	end
	--if(@SuccessiveTodate=@Leave_ToDate)
	--	begin
	--		set @Leave_ToDate=@ToDate
	--	end
	--if not(cast(@Leave_ToDate as nvarchar(11))='' or cast(@Leave_ToDate as nvarchar(11))='0')
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and LA.Leave_ToDate<=CONVERT(DATETIME, ''' + cast(@Leave_ToDate as nvarchar(11)) + ''', 102)'
	--	End
	set @sqlQuery = @sqlQuery + ' Order by LeaveApplication_Id desc'
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSettingsByComId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

-- ======================================================
-- Author		:  Kumuthini.L
-- Create date		: 19-Apr-08
-- Description		: Get Leave Setting Details by Company Id
-- Procedure Name	: Proc_TA_GetLeaveSettingsByComId 
-- ======================================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSettingsByComId]		
(
	@CompanyId INT
)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Approval,FirstLevelIntimation,SecondLevelIntimation,ApprovalCC,ToMail_DailyReport,CCMail_DailyReport FROM TA_Tbl_LeaveSettings Where CompanyId=@CompanyId	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created By	:	Prabakaran.P
Created On	:	16-Dec-09
--Proc_TA_GetLeaveSummary '12/01/2009','12/31/2009',31
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSummary]
@LeaveFromDate datetime,
@LeaveToDate datetime,
@EmployeeId int
as
BEGIN
SET NOCOUNT ON;
select isnull(Sum(NumberOfDays),0.0) as NumberOfDays from TA_Tbl_LeaveApplication 
where Status='Approved' and IsDeleted=0 and IsBorrow=0 and Type<>'Comp Off'
and 
(
(Leave_FromDate between @LeaveFromDate and @LeaveToDate)
or
(Leave_ToDate between @LeaveFromDate and @LeaveToDate)
or
(@LeaveFromDate between Leave_FromDate and Leave_ToDate)
or
(@LeaveToDate between Leave_FromDate and Leave_ToDate)
) and Employee_Id=@EmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTakenInMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_GetLeaveTakenInMonth 32,1,'01/20/2010','01/20/2010',0 
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveTakenInMonth]
@EmployeeId int,
@leaveTypeId int, 
@dtFromDate datetime, 
@dtTodate datetime,
@LeaveApplicationId int
as
BEGIN
	SET NOCOUNT ON;
declare @LeaveDays as float
if(@LeaveApplicationId=0)
BEGIN
set @LeaveDays=(
select isnull(sum(NumberOfDays),0.0) from TA_Tbl_LeaveApplication
inner join TA_Tbl_LeaveType on TA_Tbl_LeaveType.LeaveType_Id=TA_Tbl_LeaveApplication.LeaveType_Id
where Employee_Id=@EmployeeId and TA_Tbl_LeaveApplication.LeaveType_Id=@leaveTypeId
and TA_Tbl_LeaveApplication.Status!='Rejected' 
--and TA_Tbl_LeaveApplication.LeaveApplication_Id<>@LeaveApplicationId
and TA_Tbl_LeaveApplication.IsDeleted=0 
and TA_Tbl_LeaveApplication.Type='Leave' and
(
(
month(Leave_FromDate)=month(@dtFromDate) 
and year(Leave_FromDate)=year(@dtFromDate)
) 
or 
(month(Leave_ToDate)=month(@dtTodate) 
and year(Leave_ToDate)=year(@dtTodate)
)
)
and TA_Tbl_LeaveType.LeaveType='CL'
)
END
else
BEGIN
set @LeaveDays=(
select isnull(sum(NumberOfDays),0.0) from TA_Tbl_LeaveApplication
inner join TA_Tbl_LeaveType on TA_Tbl_LeaveType.LeaveType_Id=TA_Tbl_LeaveApplication.LeaveType_Id
where Employee_Id=@EmployeeId and TA_Tbl_LeaveApplication.LeaveType_Id=@leaveTypeId
and TA_Tbl_LeaveApplication.Status!='Rejected' 
and TA_Tbl_LeaveApplication.LeaveApplication_Id<>@LeaveApplicationId
and TA_Tbl_LeaveApplication.IsDeleted=0 
and TA_Tbl_LeaveApplication.Type='Leave' and
(
(
month(Leave_FromDate)=month(@dtFromDate) 
and year(Leave_FromDate)=year(@dtFromDate)
) 
or 
(month(Leave_ToDate)=month(@dtTodate) 
and year(Leave_ToDate)=year(@dtTodate)
)
)
and TA_Tbl_LeaveType.LeaveType='CL'
)
END
select @LeaveDays as LeaveDaysCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_GetLeaveTypeDetails 'SuperAdmin'
CREATE  Proc [dbo].[Proc_TA_GetLeaveTypeDetails]
(    
    @UserGroupName nVarchar(250)    
)    
AS      
Begin    
	SET NOCOUNT ON; 
	IF(@UserGroupName = 'SuperAdmin')    
		BEGIN             
			SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,0 as flag,isnull(isWFH,0) as isWFH into #tempLeaveTypes FROM TA_Tbl_LeaveType order by LeaveType_Id
			update #tempLeaveTypes set flag=1 from #tempLeaveTypes inner join
		       (
					select lpd.LeaveType_Id from TA_Tbl_LeavePolicyDetails lpd inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 					
				)as LeaveTypeDetails on #tempLeaveTypes.LeaveType_Id=LeaveTypeDetails.LeaveType_Id
			update #tempLeaveTypes set flag=1 from #tempLeaveTypes TLT inner join TA_Tbl_LeaveApplication LA on TLT.LeaveType_Id=LA.LeaveType_id 
			select * from #tempLeaveTypes 
		END    
	ELSE    
		BEGIN            
			SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,0 as flag,isnull(isWFH,0) as isWFH into #tempLeaveTyp FROM TA_Tbl_LeaveType Where IsDeleted=0 order by LeaveType_Id
			update #tempLeaveTyp set flag=1 from #tempLeaveTyp inner join
		       (
					select lpd.LeaveType_Id from TA_Tbl_LeavePolicyDetails lpd inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 
				)as LeaveTypeDetails on #tempLeaveTyp.LeaveType_Id=LeaveTypeDetails.LeaveType_Id
			update #tempLeaveTyp set flag=1 from #tempLeaveTyp TLT inner join TA_Tbl_LeaveApplication LA on TLT.LeaveType_Id=LA.LeaveType_id 
			select * from #tempLeaveTyp 
		END
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Proc_TA_GetLeaveTypeDetailsById]      
(      
 @LeaveId int,    
 @UserGroupName nVarchar(250)      
)      
AS      
Begin   
  SET NOCOUNT ON;   
  IF(@UserGroupName = 'SuperAdmin')    
    BEGIN    
       SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,       
       (select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategory,EmployeeCategory as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeType,EmployeeType as EmployeeTypes,
              Gender,(select Name from TA_Tbl_Religion where ID=Religion)as Religion,Religion as Religions,
              IsProrataRequired=isnull(IsProrataRequired,1),IsDocProofRequired=isnull(IsDocProofRequired,1)
       FROM TA_Tbl_LeaveType Where LeaveType_Id=@LeaveId
    END    
 ELSE    
   BEGIN    
       SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategory,EmployeeCategory as EmployeeCategorys,
       (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeType,EmployeeType as EmployeeTypes,
       Gender,(select Name from TA_Tbl_Religion where ID=Religion)as Religion
       ,Religion as Religions,IsProrataRequired=isnull(IsProrataRequired,1),IsDocProofRequired=isnull(IsDocProofRequired,1)
        FROM TA_Tbl_LeaveType 
       Where IsDeleted=0 AND LeaveType_Id=@LeaveId      
   END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLeaveTypeForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_Ta_GetLeaveTypeForservice]
	@INLEAVETYPEID INT
AS
BEGIN
	SET NOCOUNT ON;
    SELECT LEAVETYPE FROM TA_TBL_LEAVETYPE WHERE LEAVETYPE_ID = @INLEAVETYPEID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveTypeName] 
	-- Add the parameters for the stored procedure here
	@leaveTypeId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LeaveType FROM TA_Tbl_LeaveType WHERE LeaveType_Id = @leaveTypeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Proc [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]
AS  
begin
SET NOCOUNT ON;
SELECT LeaveType_Id,LeaveType FROM TA_Tbl_LeaveType Where IsDeleted=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelD]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLevelD]
@ParentId int
AS
BEGIN
Select LevelId from Ta_Tbl_levelDetails where id=@ParentId	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[Proc_TA_getLevelDetails]
(
	@levelId int
)
as
Begin
	--select a.levelID,a.levelName,b.* from ta_tbl_level a, ta_tbl_leveldetails b where a.levelId=b.levelID and a.levelID=@levelid
--SELECT     a.levelID , a.levelName , b.*
--FROM         TA_Tbl_Level a LEFT OUTER JOIN
 --                     Ta_Tbl_levelDetails b ON a.levelID = b.levelId
--WHERE     (a.levelID = @levelid)
select a.levelid,a.levelname,b.levelname as childLevelName,b.parentLevelId,b.levelid as childId from ta_tbl_level a left outer join ta_tbl_level b  on a.levelid=b.parentlevelid where b.isdeleted=0 and a.levelid=@levelId
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelDetailsForHoiday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Modified Author:		<R.Manikandan>
-- Modified date: <25-11-2016 11.08>
-- Description:	<Description,,>
-- [Proc_Ta_GetLevelDetailsForHoiday]'Superadmin'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLevelDetailsForHoiday]
	@UsergroupName nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select ld.id,ParentID,Name from ta_tbl_leveldetails ld inner join ta_tbl_levelrights lr on ld.id=lr.LevelId
	inner join TA_Tbl_Usergroup ug on lr.GroupId=ug.groupId
	where ld.isdeleted=0 and groupName=@UsergroupName order by parentid,Name
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelIdForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.MANIKANDAN
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	GETTING LEVEL ID FOR PROCESSING
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLevelIdForService]
	@INCLK_EMPID VARCHAR(50),
	@INCLK_DATE DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @LEVELID INT	
	SELECT @LEVELID=L.LEVELID FROM TA_TBL_EMPLOYEE E INNER JOIN TA_TBL_EMPLOYEELEVEL L ON L.EMPLOYEEID = E.EMPLOYEE_ID 
	WHERE SWIPECARDNO =  @INCLK_EMPID AND ISDELETED = 0 AND 
	L.EFFECTIVEDATE=(SELECT TOP 1 EFFECTIVEDATE FROM TA_TBL_EMPLOYEELEVEL WHERE EMPLOYEEID=E.EMPLOYEE_ID AND 
	EFFECTIVEDATE <=CONVERT(DATETIME,@INCLK_DATE, 102) ORDER BY EFFECTIVEDATE DESC)	
	WHILE((SELECT PARENTID FROM TA_TBL_LEVELDETAILS WHERE ID=@LEVELID)!=0) 
		BEGIN 
			SELECT @LEVELID=PARENTID FROM TA_TBL_LEVELDETAILS WHERE ID=@LEVELID
		END
	SELECT isnull(@LEVELID,0) AS ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_getLevelName]
(
	@levelId int='',
	@UserGroupName nVarchar(250)='',
	@UserLevelId nvarchar(4000)=''
)
as
Begin
	select LevelName from ta_tbl_level where levelId=@levelId
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelName_FromLevelID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Arun vinoth
-- Create date: 14 July 2007
-- Description:	Get Level name from LevelID
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLevelName_FromLevelID]
	-- Add the parameters for the stored procedure here
@LevelID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;
    -- Insert statements for procedure here
SELECT levelName FROM TA_Tbl_Level WHERE levelID = @LevelID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_getLevels]
 AS
Begin
	select *,1 as flag into #tempLevels from ta_tbl_level where isdeleted=0 order by parentLevelid
	update #tempLevels set flag=0 from #tempLevels
	inner join ta_tbl_leveldetails LD  on LD.levelId = #tempLevels.levelID and LD.isDeleted=0
	update #tempLevels set flag=0 from #tempLevels
	inner join ta_tbl_level L on L.parentLevelID = #tempLevels.levelID and L.isDeleted=0
	select * from #tempLevels
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLicenseEmpCountDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLicenseEmpCountDetails]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	declare @licnoofEmployee nvarchar(100)
	declare @NoofEmployee bigint,@ActiveEmployee int,@InActiveEmployee int
    -- Insert statements for procedure here
	Select @NoofEmployee =count(*) from TA_Tbl_Employee where  SwipeCardNo<>'18000000'
	Select @ActiveEmployee =count(*) from TA_Tbl_Employee where (InActive_Status=0 and Employee_Status=1) and SwipeCardNo<>'18000000'
	Select @InActiveEmployee =count(*) from TA_Tbl_Employee where (InActive_Status=1 or Employee_Status=0) and SwipeCardNo<>'18000000'
	Select @licnoofEmployee=NoOfEmployee from TA_Tbl_LIC_Details
	-- rhFTT26IaYPVHpOdiWeR+A== default values 5
	Select isnull(@NoofEmployee,0) as NoofEmployee,isnull(@ActiveEmployee,0) as ActiveEmployee,ISNULL(@InActiveEmployee,0) as InActiveEmployee,isnull(@licnoofEmployee,'rhFTT26IaYPVHpOdiWeR+A==') as LICEmpCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLocationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLocationDetails]
	@landMarkID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * from Ta_tbl_LandMarks where (@landMarkID=0 or id=@landMarkID)

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLogFileSize]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_GetLogFileSize]
AS
	BEGIN
	--Get Log File Details
	DBCC SQLPERF(logspace)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLOPLeaveTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name     :    Proc_TA_GetLOPLeaveTypeDetails    
Description     :    LOP Details from TA_Tbl_LeavePolicyDetails
Tables Included :    TA_Tbl_LeavePolicyDetails and TA_Tbl_Emp_LeavePolicy  
Created By     :    Prabakaran    
Created On     :    20-Nov-07    
Modified By     :    
Modified On     :    
Proc_TA_GetLOPLeaveTypeDetails 56,'',''
*/    
CREATE   PROCEDURE [dbo].[Proc_TA_GetLOPLeaveTypeDetails]
@EmployeeId bigint ,
@LeaveFromDate nvarchar(50),
@LeaveToDate nvarchar(50)  
as    
begin
    SET NOCOUNT ON;
    select distinct lt.LeaveType_Id,lt.LeaveType from TA_Tbl_LeavePolicyDetails lpd
    inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
    inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lpd.LeaveType_Id  
    where elp.EmployeeId=@EmployeeId
    and lpd.LossOfPay=1
    and elp.Isdeleted=0
    --and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
    and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
    inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
    where
    --TA_Tbl_YearSetting.IsActive=1 and
    TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMailConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetMailConfiguration]
AS
BEGIN
     select * from TA_Tbl_MailConfiguration
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntryById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_GetManualEntryById 157
CREATE   PROCEDURE [dbo].[Proc_TA_GetManualEntryById]
(@MID as int)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as varchar(10)
	select @dateFormat=DateFormat,@TimeFormat=TimeFormat from dbo.Func_TA_GetDateTimeFormat()
	
	select M.ManualTimeEntry_Id,Replace(Convert(varchar,M.ManualTimeEntry_Date,@dateFormat),' ','-') as Mdate,
	Replace(Convert(varchar, M.ManualTimeEntry_InDate,@dateFormat),' ','-') as InDate,
	case	when @TimeFormat='hh:mm' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_InTime,0)), 114)
			else substring(M.ManualTimeEntry_InTime,0,6)+' ' + substring(M.ManualTimeEntry_InTime,10,12) end ManualTimeEntry_InTime,
	M.ManualTimeEntry_InReaderID,
	M.ManualTimeEntry_InPunchType,Replace(Convert(varchar, M.ManualTimeEntry_OutDate,@dateFormat),' ','-') as OutDate,
	case	when @TimeFormat='hh:mm' then 
				CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_OutTime,0)), 114)
			else substring(ManualTimeEntry_OutTime,0,6)+' '+substring(ManualTimeEntry_OutTime,10,12) end ManualTimeEntry_OutTime
	,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Remarks,M.ManualTimeEntry_Status,
	E.Employee_FirstName + ' ' + E.Employee_LastName AS 'Employee_Name',
	E.Employee_Code_Id,En.Entrance_Id,En.Entrance_Name,M.IsOnduty  
	FROM TA_Tbl_ManualTimeEntry as M INNER JOIN TA_Tbl_Employee as E ON (E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_Entrance_INOUTDetails eio ON (eio.Reader_Id=M.ManualTimeEntry_InReaderID or eio.Reader_Id=M.ManualTimeEntry_OutReaderID)
	INNER JOIN TA_Tbl_Entrance as En ON (EN.Entrance_Id=eio.Entrance_Id)
	WHERE M.Isdeleted=0 and M.ManualTimeEntry_Id=@MID and En.Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name  : Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin '3','Approved','804','',0,0,'2013/01/01','2013/10/28',0,'','SuperAdmin',3
Description		: Get Manual Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: Kumuthini.L    
Created On		: 08-Jan-08    
Modified By		: Sasireka.M 
Modified On		: 16-May-2009
Modified By     :A.Amsaveni on 25/09/2013 to orderby MT.ManualTimeEntry_Date
Modified By		:	Manjula.P
Modified On		:	03-Jan-2014
Descriptions	:	Changing condition ManualTimeEntry_InDate and ManualTimeEntry_OutDate in where condition instead of ManualTimeEntry_Date
Issue			:	When we putting manual time entry for past date the records is not displaying in manual time entry sanction screen : Code :0021124
Modified By		:K.Gopinath
Modified On		:	01-Feb-2014
Descriptions	: For filter the OD entry.
*/    
CREATE PROCEDURE [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]    
	@Employee_ID int,
	@LevelId varchar(2000),    
	@Status varchar(20) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''
		set @sqlQuery = 'select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,CONVERT(VARCHAR, MT.ManualTimeEntry_Date, 101) AS ManualTimeEntry_Date,CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,101) + ''  '' + MT.ManualTimeEntry_InTime AS ''InDateTime'', CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,101) + ''  '' + MT.ManualTimeEntry_OutTime AS ''OutDateTime'',MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''0'' as SelectedRecords  from TA_TBL_Employee E '
		set @sqlQuery = @sqlQuery + ' inner join TA_TBL_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
		set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id '
		set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and MT.IsDeleted=0 and ys.IsActive=1 and MT.IsOnDuty=0'   
		if not(@EmployeeName='')
		begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
		if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
		end
		if not (@EmployeeId='')
		begin
				set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
		end		
		if not(@Status is null or @Status='' or @Status='0' or @Status='All')
		begin
			set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Status IN (''' + @Status  + '''))'
		End
		if not(cast(@ManualEntry_FromDate as nvarchar(11))='' or cast(@ManualEntry_FromDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (( isnull(MT.ManualTimeEntry_InDate,'''+cast('1990/01/01' as nvarchar(11))+''') between ''' + cast(@ManualEntry_FromDate as nvarchar(11)) +''' and ''' + cast(@ManualEntry_ToDate as nvarchar(11)) +''') '
		End
		if not(cast(@ManualEntry_ToDate as nvarchar(11))='' or cast(@ManualEntry_ToDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' or ( isnull(MT.ManualTimeEntry_OutDate,'''+cast('1990/01/01' as nvarchar(11))+''') between  ''' + cast(@ManualEntry_FromDate as nvarchar(11)) +''' and ''' + cast(@ManualEntry_ToDate as nvarchar(11)) +''')) '
		End
           set @sqlQuery = @sqlQuery + ' order by MT.ManualTimeEntry_Date desc '
	exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualODEntryById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_GetManualODEntryById] 121
--select CONVERT(varchar,getdate(),101)
-- Modified by Gopinath on 11 feb 2014 for Datetime conversion
CREATE PROCEDURE [dbo].[Proc_TA_GetManualODEntryById]
	(@MID as int)
AS
	DECLARE @Isdel int
	SET @Isdel=0
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	select M.ManualTimeEntry_Id,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_Date,106),' ','-')
		 else 																
				convert(varchar, ManualTimeEntry_Date,@dateFormat)
	end as Mdate,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_InDate,106),' ','-')
		 else 
			convert(varchar, ManualTimeEntry_InDate,@dateFormat) 
	end as InDate,
	case when (select TimeFormat from TA_Tbl_DateandTimeFormat)='hh:mm' then CONVERT(varchar(8), 
		   DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_InTime,0)), 114) else 
	M.ManualTimeEntry_InTime end ManualTimeEntry_InTime 
	,M.ManualTimeEntry_InReaderID,
	M.ManualTimeEntry_InPunchType,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_OutDate,106),' ','-')
		 else
			  convert(varchar, ManualTimeEntry_OutDate,@dateFormat) 
	end 
	as OutDate,
	case when (select TimeFormat from TA_Tbl_DateandTimeFormat)='hh:mm' then CONVERT(varchar(8), 
		   DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_OutTime,0)), 114) else 
	ManualTimeEntry_OutTime end ManualTimeEntry_OutTime
	,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Remarks,M.ManualTimeEntry_Status,
	E.Employee_FirstName + '' + E.Employee_LastName AS 'Employee_Name',E.Employee_Id,E.Emailid,
	E.Employee_Code_Id,M.IsOnduty,M.shift_id,S.Shift_ShortName,
	ld.name as LevelName, ld.id as levelid,ED.DesignationID 
	FROM TA_Tbl_ManualTimeEntry as M 
	INNER JOIN TA_Tbl_Employee as E ON E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	Inner join TA_Tbl_Shift S on M.shift_id=S.Shift_Id
	inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
	inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
	WHERE M.Isdeleted=@Isdel 
	and M.ManualTimeEntry_Id=@MID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetManualTimeEntrySanctionDetails '3','','','','','2','','08/01/2008','05/31/2009',0
Description		:	Get Manual Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included		:	TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee
Created By		:	Kumuthini.L
Created On		:	09-Jan-09
Modified By		:	Sasireka
Modified On		:	18.05.09
Modified By     :A.Amsaveni on 25/09/2013 to orderby MT.ManualTimeEntry_Date
Modified By		:K.Gopinath
Modified On		:	01-Feb-2014
Descriptions	: For filter the OD entry.
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]
	@Employee_Id int,
	@LevelId varchar(2000),
	@Status varchar(20) =null,
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate datetime =null,
	@ManualEntry_ToDate datetime =null,
	@Isdeleted bit =0,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int    
as
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	set @sqlQuery=''
	set @sqlQuery = 'select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,CONVERT(VARCHAR, MT.ManualTimeEntry_Date, 101) AS ManualTimeEntry_Date,CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,101) + ''  '' + MT.ManualTimeEntry_InTime AS ''InDateTime'', CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,101) + ''  '' + MT.ManualTimeEntry_OutTime AS ''OutDateTime'',MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''0'' as SelectedRecords from TA_TBL_Employee E '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on E.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on E.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '
	set @sqlQuery = @sqlQuery + ' where  (Reporting_to in(Select Reporting_To from ta_Tbl_employee where Reporting_To=''' + cast(@Employee_Id as nvarchar(20)) + ''') '
	set @sqlQuery = @sqlQuery + ' or Leave_Sanc_Authority in (Select Leave_Sanc_Authority from ta_Tbl_employee where Leave_Sanc_Authority=''' + cast(@Employee_Id as nvarchar(20)) + '''))  and '
	set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and MT.IsDeleted=0 and ys.IsActive=1 and MT.IsOnDuty=0'
	set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  MT.ManualTimeEntry_Date order by EffectiveDate desc) '
	if not(@EmployeeName='')
	begin
		set @sqlQuery = @sqlQuery + 'and E.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
	end
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='')
	begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
	end		
 If Not (@EmpSwipeCard = '')  
    Begin  
		  Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End 
		if not(@Status is null or @Status='' or @Status='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Status IN (''' + @Status  + '''))'
		End
		if not(cast(@ManualEntry_FromDate as nvarchar(11))='' or cast(@ManualEntry_FromDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Date>=CONVERT(DATETIME, ''' + cast(@ManualEntry_FromDate as nvarchar(11)) + ''', 102))'
		End
		if not(cast(@ManualEntry_ToDate as nvarchar(11))='' or cast(@ManualEntry_ToDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Date<=CONVERT(DATETIME, ''' + cast(@ManualEntry_ToDate as nvarchar(11)) + ''', 102))'
		End
		set @sqlQuery = @sqlQuery + 'order by MT.ManualTimeEntry_Date desc '
		exec(@sqlQuery)
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getmastersSubMenu]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getmastersSubMenu]
@ReportsMenu int	
AS
BEGIN	
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from TA_Tbl_Page where ParentIdForSubMenu=@ReportsMenu 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetMaxDaysApplicableByLeavePolicy
Description		:	Get Maximum No. of Leaves applicable for a Particular employee based on Leave Policy Details
Tables Included	:	TA_Tbl_LeavePolicyDetails,TA_Tbl_LeaveType,TA_Tbl_Emp_LeavePolicy and TA_Tbl_Employee
Created By		:	Prabakaran
Created On		:	18-Jul-07
Modified By		:
Modified On		:
*/
CREATE Procedure [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]
@Employee_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select lp.LeaveType_Id,lp.MaxDays_applicable as MaxDays_applicable,lt.LeaveType  
	from TA_Tbl_LeavePolicyDetails lp 
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id
	inner join TA_Tbl_Emp_LeavePolicy e on e.LeavePolicy_Id=lp.Policy_Id
	where e.EmployeeId= @Employee_Id  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMaxLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_Ta_GetMaxLevel]
AS
BEGIN	
	select max(levelID) as maxId from ta_tbl_level where isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetMaxPermissionHoursByLeavePolicy 151
Description		:	Get Permisssion Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeavePolicy
Created By		:	Prabakaran
Created On		:	19-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]
	@Employee_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select * from TA_Tbl_LeavePolicy l 
	inner join ta_tbl_Emp_leavepolicyDetails elpd on l.Policy_Id= elpd.Policy_ID
	inner join ta_tbl_emp_leavepolicy elp on elp.Emp_LeavePolicyId=elpd.Emp_LeavePolicyId
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId
	where ys.IsActive=1 and elpd.empid=@Employee_Id and  l.IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxUserLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Proc_TA_GetMaxUserLevel 1,'SuperAdmin',0
--	Modified by		:	Manjula.P
--	Modified On		:	13-May-2014
--	Descriptions	:	Adding if condition and else for staying selected organization levels : Ex Discrepancy entry : Bug code :0023939
CREATE  PROCEDURE [dbo].[Proc_TA_GetMaxUserLevel]
(  
  @TotLevels varchar(4000),
  @UserGroupName varchar(250), 
  @ParentId int 
)  
AS  
BEGIN  
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--declare @qry as varchar(8000)  
	--set @qry =''
	if(isnull(@ParentId,0)=0)
	begin		
		--Added this condition newly to handled one company is having, need to select automatically.
		--on 02-Mar-2020 12:08 PM by Manikanan.rr
		if((select count(*) from ta_tbl_leveldetails where parentId=0 and isDeleted=0)=1)
		begin
			select min(id) as MaxLevel from ta_tbl_leveldetails 
			inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
			where isdeleted=0 and parentID = (select min(parentid) from Ta_Tbl_levelDetails where isdeleted=0)
		end
		else
		begin
			select min(id) as MaxLevel from ta_tbl_leveldetails 
			inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
			where isdeleted=0 and parentID = (select min(parentid) from Ta_Tbl_levelDetails where levelId=3 and isdeleted=0)
		end
	end
	else   
	begin
	  select max(id) as MaxLevel from ta_tbl_leveldetails 
	  inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
	  where isdeleted=0 and parentID = (select min(ParentID) from ta_tbl_leveldetails 
	  inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id where isdeleted=0)
	end
	--exec (@qry)
	drop table #LevelRights 
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getMinimumLevel]
As
BEGIN
	select min(id) as minID  from ta_tbl_leveldetails where isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevelUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_getMinimumLevelUpdated '1,2'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getMinimumLevelUpdated]
	@LevelIDs as nvarchar(100)
As
BEGIN
	declare @Query as varchar(7000)		
	set @Query = 'select min(id) as minID  from ta_tbl_leveldetails where isdeleted=0 and id in (' + @LevelIDs + ')'
	exec (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDate]
	-- Add the parameters for the stored procedure here
	@CompanyId int,
	@DefaultMonthClosureDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @MonthClosure_EndDate datetime
	SELECT @MonthClosure_EndDate= Max(MonthClosure_EndDate) FROM TA_Tbl_MonthClosure where OrgLevel_Id=@CompanyId and IsDeleted = 0 and Process = 'P'
	if (@MonthClosure_EndDate='' or @MonthClosure_EndDate is null)
		begin
			set @MonthClosure_EndDate=@DefaultMonthClosureDate
		end
	if (@MonthClosure_EndDate!='' or @MonthClosure_EndDate is not null)
		begin
			set @MonthClosure_EndDate=@DefaultMonthClosureDate
		end
	else
		begin
			set @MonthClosure_EndDate=GETDATE()
		end	
	DELETE FROM TA_Tbl_DataProcessTemp
    -- Insert statements for procedure here
	;WITH CTE AS
	(    
		SELECT @MonthClosure_EndDate as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,[DATE])FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDateForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 05-01-2015
-- Description:	To Get the MonthClosure date for processing
-- [Proc_Ta_GetMonthClosureEndDateForService]1,'20171231'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDateForService]
	@CompanyId int,
	@DefaultMonthClosureDate datetime	
AS
BEGIN
	SET NOCOUNT ON;
	Declare @MonthClosure_EndDate datetime
	SELECT @MonthClosure_EndDate= Max(MonthClosure_EndDate) FROM TA_Tbl_MonthClosure where OrgLevel_Id=@CompanyId and IsDeleted = 0 and Process = 'P'
	if (@MonthClosure_EndDate!='' and @MonthClosure_EndDate is not null)
	begin
		set @MonthClosure_EndDate=DATEADD(d,1,@MonthClosure_EndDate)
	end
	else
	begin
		if (@DefaultMonthClosureDate!='' and @DefaultMonthClosureDate is not null)
			begin
				set @MonthClosure_EndDate=DATEADD(d,1,@DefaultMonthClosureDate)
			end
		else
			begin
				set @MonthClosure_EndDate=GETDATE()
			end
	end
	----This condition added newly. on 28-May-2019 06:43 PM
	--IF(DATEDIFF(MONTH,@MonthClosure_EndDate,GETDATE())>12)
	--BEGIN
	--	 select @MonthClosure_EndDate=DATEADD(YEAR, DATEDIFF(Year, 0, GETDATE())-1,0)
	--END
	--select @MonthClosure_EndDate
	
	DELETE FROM TA_Tbl_DataProcessTemp
	;WITH CTE AS
	(    
		SELECT @MonthClosure_EndDate as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,convert(datetime,convert(varchar(11),[DATE])))FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetMyCalendarData  5 ,'2019-05-01'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetMyCalendarData]
	-- Add the parameters for the stored procedure here
	@EmployeeID as int,
	@ShiftDate as nvarchar(100)
	--@UserGroupName as nvarchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempMyCalendar(EmployeeCodeId varchar(50),Date nvarchar(20),ShiftName nvarchar(100),HrsWork nvarchar(20),InTime nvarchar(20),OutTime nvarchar(20),LateIn nvarchar(20),EarlyOut nvarchar(20),BrackHrs nvarchar(20),LunchHrs nvarchar(20),AttendanceData nvarchar(100),Shift_TotalWorkingHours nvarchar(10),BreakMins int,HrsWrkMins int)
    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	Declare @StartDate as nvarchar(20)
	Declare @EndDate as nvarchar(20)
	SELECT @StartDate=DATEADD(month, DATEDIFF(month, 0, @ShiftDate), 0)
	select @EndDate=DateAdd(d,-1,DATEADD(M,1,@StartDate))
	declare @query as nvarchar(Max) 
	declare @queryInnerJoin as nvarchar(Max) 
	declare @queryWhere as nvarchar(Max) 
	set @query=''
	set @queryInnerJoin=''
	set @queryWhere=''
	set @query='select  ta_tbl_processedData.Employee_code_id,
	case when '+CONVERT(varchar,@dateFormat) +'=106 then 
		REPLACE(CONVERT(VARCHAR, Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')  
	else 
		CONVERT(VARCHAR, Date, '+CONVERT(varchar,@dateFormat)+') 
	end AS Date,
	isnull(
	SH.Shift_ShortName + ''('' + 
		case	when '''+CONVERT(varchar,@TimeFormat)+''' =''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,SH.Shift_StartTime,0)), 114)
				else
					SH.Shift_StartTime
		end  + '' - '' + 
		case	when '''+CONVERT(varchar,@TimeFormat)+''' =''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,SH.Shift_EndTime,0)), 114)
				else
					SH.Shift_EndTime
		end 
	+ '')'',''Weekly Off'') as shiftName,
		
		case when  HrsWork is null or HrsWork=''00:00'' then ''-'' else 
		HrsWork
		
		end HrsWork,
		
		
		case	when InTime<>''00:00'' then	
		case	when '''+CONVERT(varchar,@TimeFormat)+''' =''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114)
				else
					InTime
		end 
						else ''-''
		end	InTime,
		case	when OutTime<>''00:00'' then	
		case	when '''+CONVERT(varchar,@TimeFormat)+''' =''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114)
				else
					OutTime
		end 
						else ''-''
		end	OutTime , 
		case when  LateIn is null or LateIn=''00:00'' then ''-'' else LateIn end LateIn ,
		case when  EarlyOut is null or EarlyOut=''00:00'' then ''-'' else EarlyOut end EarlyOut ,
		BreakHrs,LunchHrs, 
		(FNAttendanceCode + '' / '' + ANAttendanceCode) as ''Attendancedetails'',
		SH.Shift_TotalWorkingHours,0,
		case when  HrsWork is null or HrsWork=''00:00'' then 0 else	 SUBSTRING(HrsWork,0,charindex('':'',HrsWork))*60+SUBSTRING(HrsWork,charindex('':'',HrsWork)+1,LEN(HrsWork)) end
		from ta_tbl_employee '
		set @queryInnerJoin =@queryInnerJoin + ' 
		inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo 
		inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId 
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id  
		inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId 
		inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId 
		inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId left join TA_Tbl_Shift SH on ta_tbl_processedData.Shift_Id=SH.Shift_Id '
		set @queryWhere = @queryWhere + ' where TA_Tbl_Employee.Report_Exclude=0 and Ta_tbl_employee.Employee_Id='+cast(@EmployeeID as nvarchar(20)) +' and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Employee_status=1 
		And ta_tbl_processedData.date between  '''+cast(@ShiftDate as nvarchar(20)) + '''  AND '''+cast(@ShiftDate as nvarchar(20)) + ''' 
		group by  ta_tbl_processedData.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName,Date,InTime,OutTime,LateIn,
		EarlyOut,LunchHrs,SH.Shift_ShortName,SH.Shift_StartTime,SH.Shift_EndTime,HrsWork,FNAttendanceCode,ANAttendanceCode,SH.Shift_TotalWorkingHours,BreakHrs'
		insert into #TempMyCalendar
		Exec(@query + @queryInnerJoin + @queryWhere)
		
		declare @SQLMonthdata as nvarchar(MAX)
		set @SQLMonthdata=''
		set @SQLMonthdata = @SQLMonthdata + 'select  ''Present'' = sum( CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'	
		set @SQLMonthdata = @SQLMonthdata + ' ''Absent'' = sum( CASE FNAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'  
		set @SQLMonthdata = @SQLMonthdata + ' ''WeeklyOff'' = sum( CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'  
		set @SQLMonthdata = @SQLMonthdata + ' ''Holiday'' = sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'  
		set @SQLMonthdata = @SQLMonthdata + ' ''Leave'' = SUM(CASE WHEN FNAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + 
			SUM( CASE WHEN ANAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),DATENAME(month, DATEADD(month, 0, '''+@StartDate+''')) as MonthName from ta_tbl_employee '
		set @queryInnerJoin=''
		set @queryInnerJoin =@queryInnerJoin + ' inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo 
		inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId 
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id  
		inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId 
		inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId 
		inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId '
		--left join TA_Tbl_Shift SH on ta_tbl_processedData.Shift_Id=SH.Shift_Id '
		set @queryWhere=''
			set @queryWhere = @queryWhere + ' where TA_Tbl_Employee.Report_Exclude=0 and Ta_tbl_employee.Employee_Id='+cast(@EmployeeID as nvarchar(20)) +' and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1 
		  And ta_tbl_processedData.date between  '''+cast(@StartDate as nvarchar(20)) + '''  AND '''+cast(@EndDate as nvarchar(20)) + ''''
		--insert into #TempMyCalendar
		--print @SQLMonthdata + @queryInnerJoin + @queryWhere
		select * from #TempMyCalendar
		Exec(@SQLMonthdata + @queryInnerJoin + @queryWhere)
		--exec(@SQLMonthdata)
		drop table #TempMyCalendar
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarTeamData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R>
-- Create date: <11-May-2017>
-- Description:	<Description,,>
-- Proc_TA_GetMyCalendarTeamData 1,'SuperAdmin'
-- exec Proc_TA_GetMyCalendarTeamData @EmployeeID=N'34',@UserGroupName=N'SuperAdmin'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetMyCalendarTeamData]
	-- Add the parameters for the stored procedure here
	@EmployeeID as int,
	@UserGroupName as nvarchar(100)
AS
BEGIN
		-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @EmplCode as nvarchar(100)
	declare @isReportingto as int
	declare @isindividual as int
	declare @todat datetime
	declare @TotalEmployeeCount as int
	set @todat=GETDATE()
	select @isReportingto=ReportsBasedOn,@isindividual=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName
	select @EmplCode=Employee_Code_ID from TA_Tbl_Employee where Employee_Id=@EmployeeID
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #LevelRights(LevelId INT)
	create table #TempMyCalendar(id int identity(1,1), Date nvarchar(20),Details nvarchar(Max))
	create table #EmployeeIds(EmpAutoId int)
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',0  
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId 
	--select * from #EmployeeIds
	--select * from #EmpDesignation
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	SET @sqlEmpLevel=
	'INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from  (
	SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId WHERE emp.Isdeleted=0 and emp.Report_Exclude=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(getdate() as nVARCHAR(50))+''', 102) and EL.LevelId is not null'  
	print @sqlEmplevel           
	EXECUTE(@sqlEmpLevel)
	if(@isReportingto > 0 or @isindividual>0)
		begin
			set @TotalEmployeeCount=(select COUNT(distinct(EmpAutoId)) from #EmployeeIds)
		end
	else
		begin
			set @TotalEmployeeCount=(select COUNT(distinct(Employee_Code_Id)) from #EmpLevel)
		end
	declare @SQLQuery as nvarchar(Max)
	declare @FromDat as nvarchar(20)
	set @SQLQuery=''
	set @FromDat='01/08/2022'
	SET @sqlQuery = @sqlQuery + ' 
	select CONVERT(VARCHAR(10),P.Date, 126), 
	''P - '' + cast(SUM(CASE P.FNAttendanceCode WHEN ''Present'' THEN 1 Else 0 END) as nvarchar(30)) + '' / '' + cast(SUM( CASE P.ANAttendanceCode WHEN ''Present'' THEN 1 else 0 END) as nvarchar(30)) + '','' + 
	''A - '' + cast(SUM(CASE P.FNAttendanceCode WHEN ''Absent'' THEN 1 else 0 END) as nvarchar(30)) + '' / '' + cast(SUM( CASE P.ANAttendanceCode WHEN ''Absent'' THEN 1 else 0 END) as nvarchar(30)) + '','' + 
	''L - '' + cast(SUM(CASE WHEN P.FNAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 1 else 0 END) as nvarchar(30)) + '' / '' + cast(SUM( CASE WHEN P.ANAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 1 else 0 END)  as nvarchar(30)) + '',''  + 	
	''W - '' + cast(SUM(CASE P.FNAttendanceCode WHEN ''Weekly Off'' THEN 1 else 0 END) as nvarchar(30)) + '' / '' + cast(SUM( CASE P.ANAttendanceCode WHEN ''Weekly Off'' THEN 1 else 0 END) as nvarchar(30)) + '','' + 
	''H - '' + cast(SUM(CASE P.FNAttendanceCode WHEN ''Holiday'' THEN 1 else 0 END) as nvarchar(30)) + '' / '' + cast(SUM( CASE P.ANAttendanceCode WHEN ''Holiday'' THEN 1 else 0 END) as nvarchar(30)) + '',''	from ta_tbl_processeddata P 
	inner join ta_tbl_Employee E on E.Swipecardno=P.Employee_Code_ID and E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_status=1 '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id '
    SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
	 if(@isReportingto > 0 or @isindividual>0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' Where (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	set @sqlQuery = @sqlQuery + ' and P.Date>='+@FromDat
	--if(@isReportingto > 0)
 --           BEGIN
 --              set @sqlQuery = @sqlQuery + ' Where (E.Employee_ID IN (select * from #EmployeeIds)) '  
 --           END
	--SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeIds ON #EmployeeIds.EmpAutoId=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Group by P.Date'
	print @sqlQuery
	insert into #TempMyCalendar
	EXECUTE(@SQLQuery)
	--select * from #TempMyCalendar
		declare @couDate int
		select @couDate=COUNT(*) from #TempMyCalendar
		declare @i int
		set @i=1
		declare @OutputString nvarchar(Max)
		set @OutputString=''
		while @i<=@couDate
		Begin
			DECLARE @StrValue AS NVARCHAR(Max)
			DECLARE @Date  AS NVARCHAR(25)
			select @Date= Date,@StrValue=Details from #TempMyCalendar where id=@i
			set @OutputString = @OutputString + @Date + ',' + @StrValue + '%' 
			set @i=@i+1
		END
		SET @OutputString = SUBSTRING(@OutputString, 0, LEN(@OutputString))
		select @OutputString + '~' + CAST(@TotalEmployeeCount as nvarchar(20)) as 'MyCalendarOutput'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMyProfileDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Rajkumar.J
-- Create date: 07-05-2021
-- Description:	Procedure to get MyProfile Details 
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GetMyProfileDetails]
	-- Add the parameters for the stored procedure here
	@EmployeeID nvarchar(100) = null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	Select Employee_Id from Ta_Tbl_Employee where SwipeCardNo = @EmployeeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMyProfileDetailsForSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	Rajkumar
-- Create date: 10- May - 2021
-- Description:	<Description,,>
-- exec Proc_Ta_GetMyProfileDetailsForSanction '48','All','2021-07-01 00:00:00.000','2021-07-31 00:00:00.000'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetMyProfileDetailsForSanction]
	-- Add the parameters for the stored procedure here
	@EmployeeId nvarchar(50) = null,
	@Status nvarchar(50) = null,
	@FromDate varchar(200)=null,    
	@ToDate varchar(200)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @sqlQuery as nvarchar(4000)
	declare @strStatus as nvarchar(1000)

	set @sqlQuery=''

	set @sqlQuery = 'Select * from Ta_Tbl_MyProfileDetails '
	if(@Status='All')
	BEGIN
	--set @strStatus = ' where Status in (Forwarded,Approved,Rejected,Pending)'
	--select * from Ta_Tbl_MyProfileDetails where Employee_Id = @EmployeeId and Status = @Status and ModifiedDate between @FromDate and @ToDate
	--set @sqlQuery = @sqlQuery + ' and (Status IN (''Forwarded'',''Approved'',''Rejected'')and ModifiedDate = ' + between @FromDate and @ToDate +''
	  select * from Ta_Tbl_MyProfileDetails  where Status in ('Forwarded','Approved','Rejected','Pending') and SwipeCardNo = @EmployeeId and                ModifiedDate between @FromDate and @ToDate
	END
	ELSE IF(@Status='Forwarded')
	BEGIN
	  select * from Ta_Tbl_MyProfileDetails  where Status = 'Forwarded' and SwipeCardNo = @EmployeeId and ModifiedDate between @FromDate and @ToDate
	END
	ELSE IF(@Status='Approved')
	BEGIN
	 select * from Ta_Tbl_MyProfileDetails  where Status = 'Approved' and SwipeCardNo = @EmployeeId and ModifiedDate between @FromDate and @ToDate
	END
	ELSE IF(@Status='Rejected')
	BEGIN
		select * from Ta_Tbl_MyProfileDetails  where Status = 'Rejected' and SwipeCardNo = @EmployeeId and ModifiedDate between @FromDate and @ToDate
	END
	ELSE IF(@Status='Pending')
	BEGIN 
		select * from Ta_Tbl_MyProfileDetails  where Status = 'Pending' and SwipeCardNo = @EmployeeId and ModifiedDate between @FromDate and @ToDate
	END
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNews]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
	created by : senthil
	created on : 10 Aug 2007
	Description : Getting news/Events
---  Proc_TA_getNews  'LeftNewsEvent'
*/
CREATE  procedure [dbo].[Proc_TA_getNews]
(
	@pos as nvarchar(25)
)
as 
Begin
	declare @sqlQuery as nvarchar(500)
	--set @sqlQuery = 'select top 1* from ta_tbl_newsEvents where NewsEventDate=convert(varchar(10),getdate(),101) and isdeleted=0 and NewsEventactive=1 and ' + cast(@pos as nvarchar(20)) + ' =1 order by newid()'  
		set @sqlQuery = 'select * from ta_tbl_newsEvents where (convert(varchar(10),getdate(),101) between NewsEventFromDate and NewsEventToDate) and isdeleted=0 and NewsEventactive=1 and ' + cast(@pos as nvarchar(20)) + ' =1 order by newsEvent_Id'  
	exec (@sqlQuery)
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNewsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		SENTHIL
-- Create date: 11-Sep-07
-- Description:	Edit News
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getNewsById]
(
	@newsId as int
)
AS
BEGIN
	select convert(varchar(15),NewsEventFromDate,101) as NewsEventFromDate,convert(varchar(15),NewsEventToDate,101) as NewsEventToDate,
	NewsEventTitle,NewsEventDescription,NewsEventActive, NewsEventImage, LeftNewsEvent,RightNewsEvent from ta_tbl_newsEvents 
	where isdeleted=0 and newsEvent_Id=@newsId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetnotificationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Karthikeyan.R
-- Create date: 28-11-2016
-- Description:   Get Notification Details
-- Proc_TA_GetnotificationDetails 4,'IndividualUsers'
--Proc_TA_GetnotificationDetails 3,'IndividualUsers'
-- Proc_TA_GetnotificationDetails 24,'SuperAdmin'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetnotificationDetails]
      -- Add the parameters for the stored procedure here
      @employeeID as int,
      @UserGroupName as nvarchar(100)
AS
BEGIN
     SET NOCOUNT ON;
	
	Declare @local_employeeID int
	Declare @local_UserGroupName nvarchar(100)
	set @local_employeeID =@employeeID
	set @local_UserGroupName =@UserGroupName
	
	Declare @Fromdate datetime
	Declare @Todate datetime
	select @Fromdate=FromDate,@Todate=ToDate from TA_Tbl_YearSetting where IsActive=1  
	
	declare @PendingLeave as int=0
	declare @ForwardLeave as int=0
	declare @PendingPermission as int=0
	declare @ForwardPermission as int=0
	declare @PendingOnduty as int=0
	declare @ForwardOnduty as int=0
	
	declare @totalNotification as int=0
	declare @today datetime =getdate()
	declare @IsReportto as int=0
	declare @IsSanctionto as int=0
	declare @isReportingto as int
	declare @isIndividualuser as int

	----Variables for passport&Visa
	declare @IsPassportRemainderReq as bit = 0
	declare @IsVisaRemainderReq as bit = 0
	declare @PassportRemaindDays as int = 0
	declare @VisaRemaindDays as int = 0
	declare @PassportExpiry as int = 0
	declare @VisaExpiry as int =0
	Declare @PassportExpiryDate as Datetime
	Declare @VisaExpiryDate as Datetime
	Declare @PassportExpireDate as Datetime
	Declare @VisaExpireDate as Datetime
	Declare @Valid as int = 0
	Declare @FindPassExpDate as Datetime
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	Declare @TodayExpiry datetime
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	
	--Get the Top level ID
	Create Table #TempSanctionUser(Employee_id int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,0) as LevelId
	select @IsReportto=Count(*) from TA_Tbl_Employee where Reporting_To=@local_employeeID and Employee_Status=1
	select @IsSanctionto=Count(*) from TA_Tbl_Employee where Leave_Sanc_Authority=@local_employeeID  and Employee_Status=1
	select @isReportingto=ReportsBasedOn,@isIndividualuser=IndividualUsers from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from  
	(
		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		from TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@today as nVARCHAR(50)), 102) and EL.LevelId is not null
	and (@isIndividualuser=0 or (@isIndividualuser>0 and el.EmployeeId=CAST(@local_employeeID as nvarchar(10))))
	
	Insert Into #EmployeeIds 
	select employee_id from ta_tbl_employee where (Leave_Sanc_Authority=@local_employeeID or Reporting_To=@local_employeeID)
	and Employee_Status=1
	Insert Into #TempSanctionUser select EmpAutoId from #EmployeeIds
	delete from #TempSanctionUser where Employee_id=@local_employeeID
	--select * from #TempSanctionUser
	
	--Get Pending Leave
	Select @PendingLeave=COUNT(case when Status='Pending' then 1 end),
	@ForwardLeave=COUNT(case when Status='Forwarded' then 1 end)	
	from TA_Tbl_LeaveApplication L 
	inner join TA_Tbl_EmployeeLevel EL ON L.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=L.YearSettings_Id 
	inner join #TempSanctionUser su on su.Employee_id=L.Employee_Id  
	where L.IsDeleted=0 and ys.IsActive=1
	and (Leave_FromDate>=@Fromdate and Leave_ToDate<=@Todate)
	
	--Get Pending Permission 
	Select @PendingPermission=COUNT(case when Permission_Status='Pending' then 1 end) ,
	@ForwardPermission=COUNT(case when Permission_Status='Forwarded' then 1 end)
	from TA_Tbl_Permission P 
	inner join TA_Tbl_EmployeeLevel EL ON P.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id 
	inner join #TempSanctionUser su on su.Employee_id=P.Employee_Id 
	where P.IsDeleted=0 and ys.IsActive=1
	and (Permission_Date>=@Fromdate and Permission_Date<=@Todate)
	
	--Get Pending Onduty
	select @PendingOnduty=COUNT(case when Onduty_Status='Pending' then M.Onduty_ID end) ,
	@ForwardOnduty=COUNT(case when Onduty_Status='Forwarded' then M.Onduty_ID end)	
	from ta_tbl_manualtimeentry M 
	inner join TA_Tbl_OndutyEntry OD on OD.Onduty_ID=M.Onduty_ID and OD.isDeleted=0 
	inner join TA_Tbl_Employee E on OD.Onduty_EmployeeID=E.Employee_Code_Id  
	inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	inner join #TempSanctionUser su on su.Employee_id=E.Employee_Id 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id 
	where OD.Isdeleted=0 and ys.IsActive=1
	and IsOnDuty=1 and (Onduty_FromDate>=@Fromdate and Onduty_ToDate<=@Todate)

	--Get PassportExpiry Details
	CREATE TABLE #TblEmpDetails (IsPassportRemReq bit ,PassportRemaindDays int,PassportExpryDate datetime,IsVisaRemReq bit,
	VisaRemainDays int,VisaExpryDate datetime)
		insert into #TblEmpDetails
		Select IsPassportReminderRequired,PassportRemindDays,Passport_expirydate,IsVisaReminderRequired,VisaRemindDays,Visa_expirydate 
		from TA_Tbl_Employee where Employee_Id = @local_employeeID

		Declare @count as Int
		Select @Count = count (*) from #TblEmpDetails

		If @Count <> 0
		BEGIN
		   -- select * from #TblEmpDetails
		    set @IsPassportRemainderReq = (select IsPassportRemReq from #TblEmpDetails )
            set @IsVisaRemainderReq = (select IsVisaRemReq from #TblEmpDetails )

			
		if( @IsPassportRemainderReq = 1)
		BEGIN

		set @PassportExpiryDate = (select PassportExpryDate from #TblEmpDetails )

			set @PassportRemaindDays = (select PassportRemaindDays from #TblEmpDetails )
			select @FindPassExpDate = DATEADD(Day,@PassportRemaindDays,GETDATE())
			set @PassportExpiryDate = (select PassportExpryDate from #TblEmpDetails )


			

			if(@FindPassExpDate> @PassportRemaindDays)

			--select @Valid = 1 where Convert(date, GETDATE()) between Convert(date, @PassportExpiryDate)  and  @FindPassExpDate
			
			--select @Valid = 2 where @PassportExpiryDate < getdate()

			--set @TodayExpiry = (select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))

			--select @Valid = 3 where @PassportExpiryDate = @TodayExpiry
			
			
			declare @cnt int;

			SET  @cnt=  DATEDIFF(Day,Getdate(),Convert(Date,@PassportExpiryDate))

		

			if(@PassportRemaindDays >= @cnt)
			BEGIN
			 -- select 'Your Passport will be expired '+CONVERT(varchar(20), @PassportExpiryDate)+ ' on  Please update '
				SET	@PassportExpiry = 1
			END
			ELSE
			BEGIN
				SET @PassportExpiry = 0
			END
			
			--IF (@Valid = 1)
			--BEGIN
			--  SET @PassportExpiry = 'Your Passport will be expired on ' +  CONVERT(VARCHAR, @PassportExpiryDate, @DATEFORMAT)  + ' Please update '
			--  SET @PassportExpiry = 1
			--END
			--ELSE IF(@Valid = 2)
			--BEGIN
			--  SET @PassportExpiry = 'Your Passport expired on ' +  CONVERT(VARCHAR, @PassportExpiryDate, @DATEFORMAT)  + ' Please update '
			--   SET @PassportExpiry = 2
			--END
			--ELSE IF (@Valid = 3)
			--BEGIN
			--SET @PassportExpiry = 'Your Passport will expire today ' +  CONVERT(VARCHAR, @PassportExpiryDate, @DATEFORMAT)  + ' Please update '
			-- SET @PassportExpiry = 3
			--END
		END

		--IF(@IsVisaRemainderReq = 1)
		--BEGIN
		--  SET @VisaRemaindDays = (select VisaRemainDays FROM #TblEmpDetails )
		--  select @FindPassExpDate = DATEADD(Day,@VisaRemaindDays,GETDATE())
		--  set @VisaExpiryDate = (select VisaExpryDate from #TblEmpDetails )

		--  select @Valid = 1 where GETDATE() between @FindPassExpDate and @VisaExpiryDate
		--  select @Valid = 2 where @VisaExpiryDate < getdate()
		--  set @TodayExpiry = (select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
		--  select @Valid = 3 where @VisaExpiryDate = @TodayExpiry

		--    IF (@Valid = 1)
		--	BEGIN
		--	  SET @VisaExpiry = 'Your Visa will be expired on ' +  CONVERT(VARCHAR, @VisaExpiryDate, @DATEFORMAT)  + ' Please update '
		--	END
		--	ELSE IF(@Valid = 2)
		--	BEGIN
		--	  SET @VisaExpiry = 'Your Visa expired on ' +  CONVERT(VARCHAR, @VisaExpiryDate, @DATEFORMAT)  + ' Please update '
		--	END
		--	ELSE IF (@Valid = 3)
		--	BEGIN
		--	SET @VisaExpiry = 'Your Visa will expire today ' +  CONVERT(VARCHAR, @VisaExpiryDate, @DATEFORMAT)  + ' Please update '
		--	END
		--END

		END
		
		--set @local_VisaExpiryDate = (select VisaExpryDate from #TblEmpDetails )

			--IF(@local_PassportExpiryDate > GETDATE())
			--BEGIN
			--		SET @PassportExpireDate	= (SELECT DATEDIFF(Day, GETDATE(), @local_PassportExpiryDate) AS PassportExpiresIn);
			--	IF(@PassportExpireDate <= 30)
			--	BEGIN
			--		SET	@PassportExpiry = 1
			--	END
			--END
			--ELSE
			--	BEGIN
			--		SET	@PassportExpiry = 0
			--	END

	--Get VisaExpiry Details

		--IF(@local_VisaExpiryDate > GETDATE())
		--BEGIN
	 --       SET @VisaExpireDate = (SELECT DATEDIFF(Day, GETDATE(), @local_VisaExpiryDate) AS VisaExpiresIn);

		--	if(@VisaExpireDate <= 30)
		--	BEGIN
		--		SET	@VisaExpiry = 1
		--	END
		--END
		--ELSE
		--BEGIN
		--	SET	@VisaExpiry = 0
		--END
	--END

	

		
set @totalNotification = (isnull(@PendingLeave,0) + isnull(@ForwardLeave,0) + isnull(@PendingPermission,0) + isnull(@ForwardPermission,0) + isnull(@PendingOnduty,0)  + isnull(@ForwardOnduty,0) +isnull(@PassportExpiry,0) + isnull(@VisaExpiry,0))
	
	select isnull(@PendingLeave,0) as 'PendingLeave',
	isnull(@ForwardLeave,0) as 'ForwardLeave',
	isnull(@PendingPermission,0) as 'PendingPermission',
	isnull(@ForwardPermission,0) as 'ForwardPermission',
	isnull(@PendingOnduty,0) as 'PendingOnduty',
	isnull(@ForwardOnduty,0) as 'ForwardOnduty', 
	isnull(@PassportExpiry,0) as 'PassportExpiry',
	isnull(@VisaExpiry,0) as 'VisaExpiry',
	isnull(@totalNotification,0) as 'TotalNotification',
	0 as 'LevelID','' as 'FromDate',
	'' as 'ToDate',isnull(@IsReportto,0) as 'IsReportingto',
	isnull(@IsSanctionto,0) as 'IsSanctionto'
	
	drop table #EmpLevel
	drop table #LevelRights
	drop table #TempSanctionUser
	drop table #EmployeeIds	
	drop table #TblEmpDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetNumberOfHolidaysTaken]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetNumberOfHolidaysTaken 10924,3,2
Description		:	Get the Remaining No of Holidays from TA_Tbl_LeaveApplication and TA_Tbl_HolidaySettings
Tables Included	:	Ta_Tbl_Holiday,Ta_Tbl_LeaveApplication and ta_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetNumberOfHolidaysTaken] 
	@Employee_Id int,
	@LeaveType_Id int,
	@YearSettingId int
AS
BEGIN
	DECLARE @LevelId int 
	select @LevelId=LevelId from ta_tbl_employeeLevel where employeeId=@Employee_Id
	while((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@LevelId) <> 1)
				begin
				set @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId) 
				end
			else
			begin
				break
			end
		ENd
	set @LevelId=@LevelId
	if(@LeaveType_Id<>-1)
	BEGIN
		declare @CountRecordExist as int
		set @CountRecordExist=(select count(*) From Ta_Tbl_LeaveApplication la where la.Type='Restricted Holiday' and la.Isdeleted=0 and la.status not in('Rejected')and la.Employee_Id=@Employee_Id and YearSettings_Id=@YearSettingId)
		if @CountRecordExist>0
			begin
				select h.holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate,sum(la.NumberOfDays) as HolidaysTaken from Ta_Tbl_Holiday h
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id
				where   la.Type='Restricted Holiday' and la.Isdeleted=0 and status not in('Rejected') and la.Employee_Id=@Employee_Id 
				and h.YearSettings_Id=@YearSettingId
				group by h.holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate
				union
				select h.Holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate, '0' as HolidaysTaken 
				From TA_Tbl_Holiday h 
				where h.isdeleted=0 and Holiday_Type='Y'  and h.YearSettings_Id=@YearSettingId
			end
		else
			begin
				select 0 as HolidaysTaken,h.Holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate From ta_Tbl_Holiday h
				where h.Holiday_Id=@LeaveType_Id and h.YearSettings_Id=@YearSettingId
			end
	END
	ELSE
	BEGIN
		declare @NumberOfDays as float
		declare @YearlyMaxDays as float
		set @NumberOfDays=(select isnull(sum(NumberOfDays),0.0) as NumberOfDays from TA_Tbl_LeaveApplication la
		inner join TA_Tbl_Holiday h on h.Holiday_Id=la.LeaveType_id
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
		where ys.YearSettings_ID=@YearSettingId and la.Type='Restricted Holiday' and la.Employee_Id=@Employee_Id and la.IsDeleted=0 and la.Status<>'Rejected')
		set @YearlyMaxDays=(select Yearly_Maxdays from TA_Tbl_HolidaySettings hs
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_ID=hs.YearSettingId
		where ys.YearSettings_ID=@YearSettingId)
		set @NumberOfDays= @YearlyMaxDays-@NumberOfDays
		select 'Restricted Holiday' as 'Restricted Holiday',@NumberOfDays as NumberOfDays
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetODEntryById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

--[Proc_TA_GetODEntryById] 16
--select CONVERT(varchar,getdate(),101)
-- Modified by Gopinath on 11 feb 2014 for Datetime conversion
CREATE PROCEDURE [dbo].[Proc_TA_GetODEntryById]
(@ODID as int)
AS
BEGIN
	DECLARE @Isdel int
	SET @Isdel=0
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	DECLARE @TimeFormat as nvarchar(25)
	SELECT @date=DateFormat,@TimeFormat=timeformat FROM TA_Tbl_DateandTimeFormat
	IF(@date='dd/MM/yyyy')
	BEGIN
		SET @dateFormat = 103
	END
	ELSE IF(@date='MM/dd/yyyy')
	BEGIN
		SET @dateFormat = 101
	END
	ELSE
	BEGIN
		SET @dateFormat = 106
	END
	--set @TimeFormat='hh:mm'
	select OD.Onduty_ID,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, Onduty_EntryDate,106),' ','-')
			else convert(varchar, Onduty_EntryDate,@dateFormat)
	end as Onduty_EntryDate,
	case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Onduty_FromDate,106),' ','-')
			else convert(varchar, Onduty_FromDate,@dateFormat) 
	end as Onduty_FromDate,
	case	when (@TimeFormat)='hh:mm' then CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OD.Onduty_FromTime,0)), 114) 
			else Onduty_FromTime
	end Onduty_FromTime,
	case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Onduty_ToDate,106),' ','-')
			else convert(varchar, Onduty_ToDate,@dateFormat) 
	end as Onduty_ToDate,
	case when (@TimeFormat)='hh:mm' then CONVERT(varchar(8), DATEADD(minute,0,convert(datetime,OD.Onduty_ToTime,0)), 114) 
			else Onduty_ToTime
	end Onduty_ToTime
	,OD.Onduty_Reason,OD.Onduty_Status,Onduty_Type,IncludeWeekOff,From_session,To_session,
	E.Employee_FirstName + '' + E.Employee_LastName AS 'Employee_Name',E.Employee_Id,E.Emailid,
	E.Employee_Code_Id,ld.name as LevelName, ld.id as levelid,ED.DesignationID,e.Reporting_To,e.Leave_Sanc_Authority
	FROM TA_Tbl_OndutyEntry as OD 
	INNER JOIN TA_Tbl_Employee as E ON E.Employee_Code_Id=OD.Onduty_EmployeeID
	inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
	inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
	WHERE OD.Isdeleted=@Isdel and OD.Onduty_ID=@ODID
	select * from TA_Tbl_OnDutyConversation where OnDutyApplicationId=@ODID order by OnDutyConversationId desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gopinath.K
-- Create date: 17June2014
-- Description:For get the OD conversation details.
--Proc_TA_GetLeaveConversation 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetOnDutyConversation] 
	@OnDutyApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @OnDutyApplicationId Order By OrderBY Desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
[Proc_TA_GetOnDutyEntrySanctionCountDetails] '65','Project Manager'
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]
@Employee_Id int,
@UserGroupName varchar(250)
as
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate,@ToDate=TODATE  from TA_Tbl_YearSetting where IsActive=1	 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery = 'select count(case  when OD.Onduty_Status=''Approved'' and E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1  end)Approved,
                            count(case  when OD.Onduty_Status=''Forwarded'' and E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''' then 1 end)Forwarded,
                            count(case  when OD.Onduty_Status=''Pending''  and (E.Reporting_To=''' +cast(@Employee_Id as nvarchar(50))   + ''' or E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''') then 1  end)Pending  from TA_TBL_Employee E '
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
		set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
		set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and OD.IsDeleted=0'
	if(@Employee_Id!='')
	begin
		set @sqlQuery = @sqlQuery + ' and (E.Reporting_To=''' +cast(@Employee_Id as nvarchar(50))   + ''' or E.Leave_Sanc_Authority=''' +cast(@Employee_Id as nvarchar(50))   + ''')'
	end
	set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
	set @sqlQuery = @sqlQuery + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)))'
	--print(@sqlQuery)
		exec(@sqlQuery)
		drop table #LevelRights
		drop table #EmpLevel
		drop table #EmpType
		drop table #EmpCategory
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetOnDutyEntrySanctionDetails '3','','','','','2','','08/01/2008','05/31/2009',0
Proc_TA_GetOnDutyEntrySanctionDetails '361','3','All','','',0,0,'04/01/2014','03/31/2015',0,'','EIT - PMs',3
Description		:	Get OnDuty Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included		:	TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee
Created By		:	Gopinath.K
Created On		:	31-Jan-2014
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]
	@Employee_Id int,
	@LevelId varchar(2000),
	@Status varchar(50) =null,
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null, 
	@ManualEntry_ToDate varchar(20)=null,
	@Isdeleted bit =0,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int    
as
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery = 'select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_Date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_Date, 
	  case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, MT.shift_date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, MT.shift_date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS shiftDate, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_InDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_InDate,MT.ManualTimeEntry_InTime,MT.ManualTimeEntry_InPunchType,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_OutDate, 
	 MT.ManualTimeEntry_OutTime,MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,E.Leave_Sanc_Authority,''0'' as SelectedRecords  from TA_TBL_Employee E '
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
			set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id '
			set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and MT.IsDeleted=0 and MT.IsOnDuty=1 and ys.IsActive=1'
			if not(@EmployeeName='')
			begin
				set @sqlQuery = @sqlQuery + 'and E.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
			end
			if(@EmployeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery +' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
			end
			if(@EmployeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))
			end
			if not (@EmployeeId='')
			begin
				set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
			end		
			If Not (@EmpSwipeCard = '')  
			Begin  
			  Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			End 
			if not(@Status is null or @Status='' or @Status='0' or @Status='All')
			begin
				set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Status IN (''' + @Status  + '''))'	
			End
			set @sqlQuery = @sqlQuery + ' and (E.Leave_Sanc_Authority = ''' + cast(@Employee_Id as nvarchar(50)) + ''' or E.Reporting_To= ''' + cast(@Employee_Id as nvarchar(50)) + ''')'	
			if not(cast(@ManualEntry_FromDate as nvarchar(11))='' or cast(@ManualEntry_FromDate as nvarchar(11))='0')
			begin
				set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Date>=CONVERT(DATETIME, ''' + cast(@ManualEntry_FromDate as nvarchar(11)) + ''', 102))'
			End
			if not(cast(@ManualEntry_ToDate as nvarchar(11))='' or cast(@ManualEntry_ToDate as nvarchar(11))='0')
			begin
				set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Date<=CONVERT(DATETIME, ''' + cast(@ManualEntry_ToDate as nvarchar(11)) + ''', 102))'
			End
			if not (@EmployeeId='')
			begin
				set @sqlQuery = @sqlQuery + ' and (E.Leave_Sanc_Authority = ''' + cast(@Employee_Id as nvarchar(50))  + ''')'
			End
			set @sqlQuery = @sqlQuery + ' order by MT.ManualTimeEntry_Date desc '
			exec(@sqlQuery)
			drop table #LevelRights
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name  : Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin '3','Approved','804','',0,0,'2013/01/01','2013/10/28',0,'','SuperAdmin',3
    Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin '3','All','','',0,0,'4/1/2014',
    '3/31/2015',0,'','SuperAdmin',3
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: K.Gopinath   
Created On		: 31-Jan-2014    
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]    
	@LevelId varchar(2000),    
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
		declare @sqlQuery as varchar(max)
		set @sqlQuery=''
		set @sqlQuery = 'select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_Date, '+cast(@dateFormat as varchar(100))+')
	end 
 AS ManualTimeEntry_Date, 
  case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, MT.shift_date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, MT.shift_date, '+cast(@dateFormat as varchar(100))+')
	end 
 AS shiftDate, 
 case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_InDate, '+cast(@dateFormat as varchar(100))+')
	end 
 AS ManualTimeEntry_InDate,MT.ManualTimeEntry_InTime,MT.ManualTimeEntry_InPunchType,
 case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate, '+cast(@dateFormat as varchar(100))+')
	end 
 AS ManualTimeEntry_OutDate, 
 MT.ManualTimeEntry_OutTime,MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''0'' as SelectedRecords  from TA_TBL_Employee E '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and MT.IsDeleted=0  and mt.IsOnDuty=1 and ys.IsActive=1'   
	if not(@EmployeeName='')
	begin
		set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	If Not (@EmpSwipeCard = '')  
	Begin  
	  Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End 
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='')
	begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
	end		
	if not(@Status is null or @Status='' or @Status='0' or @Status='All')
	begin
	set @sqlQuery = @sqlQuery + ' and (MT.ManualTimeEntry_Status IN (''' + @Status  + '''))'
	End
	if not(cast(@ManualEntry_FromDate as nvarchar(11))='' or cast(@ManualEntry_FromDate as nvarchar(11))='0')
	begin
		set @sqlQuery = @sqlQuery + ' and (( isnull(MT.ManualTimeEntry_InDate,'''+cast('1990/01/01' as nvarchar(11))+''') between ''' + cast(@ManualEntry_FromDate as nvarchar(11)) +''' and ''' + cast(@ManualEntry_ToDate as nvarchar(11)) +''') '
	End
	if not(cast(@ManualEntry_ToDate as nvarchar(11))='' or cast(@ManualEntry_ToDate as nvarchar(11))='0')
	begin
		set @sqlQuery = @sqlQuery + ' or ( isnull(MT.ManualTimeEntry_OutDate,'''+cast('1990/01/01' as nvarchar(11))+''') between  ''' + cast(@ManualEntry_FromDate as nvarchar(11)) +''' and ''' + cast(@ManualEntry_ToDate as nvarchar(11)) +''')) '
	End
	   set @sqlQuery = @sqlQuery + ' order by MT.ManualTimeEntry_Date desc '
	exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name  : Proc_TA_GetOnDutyEntrySanctionForSuperAdmin '1','Pending','0','',0,0,'','',0,'','Sanctioner',4
Proc_TA_GetOnDutyEntrySanctionForSuperAdmin 1,1,'Forwarded','','',0,0,'2020/01/01','2020/03/31',0,'','superadmin',1
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: R.Karthikeyan 
Created On		: 14-Mar-2016
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]    
	@Employee_ID int,
	@LevelId varchar(2000),    
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=DATEADD(d,@SuccessiveDays,TODATE) from TA_Tbl_YearSetting where IsActive=1
	--Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	
		DECLARE @dateFormat as int
		set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
			declare @sqlQuery as nvarchar(Max)
			set @sqlQuery=''
			set @sqlQuery = 'select OD.Onduty_ID,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_EntryDate, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_FromDate,OD.Onduty_FromTime,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_ToDate, 
	 OD.Onduty_ToTime,OD.OnDuty_Status,OD.Onduty_Reason,''0'' as SelectedRecords  from TA_TBL_Employee E '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
	set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and OD.IsDeleted=0'   
	--set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and MT.IsDeleted=0  and mt.IsOnDuty=1 and ys.IsActive=1'   
	declare @sqlQuery1 as nvarchar(Max)
	set @sqlQuery1=''
	if not(@EmployeeName='')
	begin
		set @sqlQuery1 = @sqlQuery1 + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If Not (@EmpSwipeCard = '')  
	Begin  
		  Set @sqlQuery1 = @sqlQuery1 + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End 
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery1 = @sqlQuery1 +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery1 = @sqlQuery1 + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='')
	begin
			set @sqlQuery1 = @sqlQuery1 + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
	end		
	if (@UserGroupName!='Superadmin' and @isReportingto!=0)
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))and Leave_Sanc_Authority='+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((OD.Onduty_Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
				set @sqlQuery = @sqlQuery + ' or (OD.Onduty_Status IN (''Forwarded'',''Approved'',''Rejected'')and Leave_Sanc_Authority='+CONVERT(varchar(20),@Employee_Id)+'))'
			end
	end
	else 
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((OD.Onduty_Status IN (''Pending''))'
				set @sqlQuery = @sqlQuery + ' or (OD.Onduty_Status IN (''Forwarded'',''Approved'',''Rejected'')))'
			end
	End
	If (@ManualEntry_FromDate != '' and @ManualEntry_ToDate != '')  
		 Begin  
		  set @sqlQuery1 = @sqlQuery1 + ' AND (((CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
			set @sqlQuery1 = @sqlQuery1 + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102)))'
		 End  
	Else
		 Begin  
		  set @sqlQuery1 = @sqlQuery1 + ' AND (((CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
			set @sqlQuery1 = @sqlQuery1 + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)))'
		 End  
       set @sqlQuery1 = @sqlQuery1 + ' order by OD.Onduty_ID desc '
	exec(@sqlQuery + ' ' + @sqlQuery1) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetOnDutyEntrySanctionForUser '41','1','Pending','','','0','0','01/01/2019','31/12/2019',0,'','Project%20manager',0
exec Proc_TA_GetOnDutyEntrySanctionForUser @Employee_Id='',@LevelId='5',
@Status='Approved,Pending,Forwarded,Rejected',@EmployeeId='',@EmployeeName='',@EmployeeCategory=0,@EmployeeType=0,
@ManualEntry_FromDate='01/07/2017',
@ManualEntry_ToDate='08/30/2017',@Isdeleted=0,
@EmpSwipeCard='',@UserGroupName='Reporting To',@ParentID=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(100) =null,
@EmployeeId varchar(100),
@EmployeeName varchar(50),  
@EmployeeCategory int, 
@EmployeeType int,
@ManualEntry_FromDate varchar(20)=null, 
@ManualEntry_ToDate varchar(20)=null,
@Isdeleted bit =0,
@EmpSwipeCard varchar(20),
@UserGroupName varchar(250),
@ParentID int    
as
begin
	SET NOCOUNT ON;
	if(substring(@ManualEntry_FromDate,1,5)='01/01' and substring(@ManualEntry_ToDate,1,5)='31/12')
	begin		
		set @ManualEntry_ToDate=substring(@ManualEntry_ToDate,4,2)+'/'+substring(@ManualEntry_ToDate,1,2)+'/'+
		substring(@ManualEntry_ToDate,7,4)
	end
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=TODATE from TA_Tbl_YearSetting where IsActive=1
	 declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID  
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery = 'select OD.Onduty_ID,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName,
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_EntryDate, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_FromDate,OD.Onduty_FromTime,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_ToDate, 
	 OD.Onduty_ToTime,OD.OnDuty_Status,OD.Onduty_Reason,E.Leave_Sanc_Authority,''0'' as SelectedRecords  from #TempPermissionDetails E '
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID '
		set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id ' 
		set @sqlQuery = @sqlQuery + ' where E.Isdeleted=0 and OD.IsDeleted=0'
		if not(@EmployeeName='')
		begin
			set @sqlQuery = @sqlQuery + 'and E.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		end
		if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))
		end
		if not (@EmployeeId='')
		begin
				set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
		end		
		 If Not (@EmpSwipeCard = '')  
		Begin  
			  Set @sqlQuery = @sqlQuery + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
		--if not(@Status is null or @Status='' or @Status='0' or @Status='All')
		--begin
		--	set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status  + '''))'	
		--End
		if (@UserGroupName!='Superadmin' and @isReportingto!=0)
		begin
			if (@Status='Pending' or @Status='Rejected')
				begin
					set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
				end
			else if(@Status='Forwarded' or @Status='Approved')
				begin
					set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))and Leave_Sanc_Authority='+CONVERT(varchar(20),@Employee_Id)	
				end	
			else if(@Status='All')		
				begin
					--print 's'
					set @sqlQuery = @sqlQuery + ' and ((OD.Onduty_Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
					set @sqlQuery = @sqlQuery + ' or (OD.Onduty_Status IN (''Forwarded'',''Approved'',''Rejected'')and Leave_Sanc_Authority='+CONVERT(varchar(20),@Employee_Id)+'))'
				end
		end
		else 
		begin
			if (@Status='Pending' or @Status='Rejected')
				begin
					set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
				end
			else if(@Status='Forwarded' or @Status='Approved')
				begin
					set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'
				end	
			else if(@Status='All')		
				begin
					--print 's'
					set @sqlQuery = @sqlQuery + ' and ((OD.Onduty_Status IN (''Pending''))'
					set @sqlQuery = @sqlQuery + ' or (OD.Onduty_Status IN (''Forwarded'',''Approved'',''Rejected'')))'
				end
		End
		
	--	if @Status='Pending' or @Status='Rejected'
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
	--	end
	--else if(@Status='Forwarded' or @Status='Approved')
	--	begin
	--		--set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))'		
	--		set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''' + @Status + '''))and E.Leave_Sanc_Authority='+CONVERT(varchar(20),@Employee_Id)	
	--		--set @sqlQuery = @sqlQuery + ' and E.LeaveSanction = ''' + cast(@Employee_Id as nvarchar(50)) + ''''			
	--	end	
	--else if(@Status='All')		
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected''))'
	--	end
	--else 
	--begin
	--	set @sqlQuery = @sqlQuery + ' and (OD.Onduty_Status IN (select value from split(''' + @Status  + ''','','')))'
	--End	
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END	
		If(@ManualEntry_FromDate != '' and @ManualEntry_ToDate != '')  
			 Begin  
			  set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
				set @sqlQuery = @sqlQuery + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@ManualEntry_FromDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ManualEntry_ToDate as nvarchar(50))   + ''', 102)))'
			 End  
		Else
			 Begin  
			  set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
				set @sqlQuery = @sqlQuery + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@Fromdate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@ToDate as nvarchar(50))   + ''', 102)))'
			 End  
		set @sqlQuery = @sqlQuery + ' order by OD.Onduty_ID desc '
		exec(@sqlQuery)
		drop table #LevelRights
		drop table #EmpLevel
		drop table #EmpType
		drop table #EmpCategory
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOracelDBDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetOracelDBDetails]
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT HostName,Port,ServiceName,UserName,Pwd FROM Ta_tbl_OracleDBConfiguration
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId = @shiftSettingId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatus]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    Declare @OTApproval varchar(20)
    Declare @status varchar(20)
    set @status=''
    -- Insert statements for procedure here
	SELECT CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry FROM TA_Tbl_ApprovalSettings WHERE CompanyId = @CompanyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Overtime status
-- drop procedure Proc_Ta_GetOverTimeApprovalStatus
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	BEGIN TRY
		BEGIN TRANSACTION
		SELECT CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry FROM TA_Tbl_ApprovalSettings WHERE CompanyId = @CompanyId
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPageName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetPageName]
@strType varchar(20)-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@strType!='Standard')
	begin
		-- Insert statements for procedure here
		SELECT pageId, displayname+'_Title', path,
		case	when pageId=177 then 177 
				when pageId=179 then 179 
				when pageId=246 then 246 
				when pageId=249 then 249
				when pageId=312 then 312
				else parentId end as parentId, orderby from ta_tbl_page where parentId=0 
		order by orderBy 
		--where (path is not null and path<>'') 
		--group by pageId,displayname,path,parentId,orderby 
		--order by parentId,orderby
	END
	else
	BEGIN
		-- Insert statements for procedure here
		SELECT	pageId, displayname+'_Title', path,
				case	when pageId=177 then 177 
						when pageId=179 then 179 
						when pageId=246 then 246 
						when pageId=249 then 249
						when pageId=312 then 312
						else parentId end as parentId, orderby from ta_tbl_page 
		where pageId not in (20,24,25,69,96,97,98,108,110,174) and parentId=0 
		--and (path is not null and path<>'') 
		group by pageId,displayname,path,parentId,orderby order by parentId,orderby
	END
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 26-07-2017 03.51 PM
-- Description:	Getting Parent Level details using usergroup
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]
@UserGroupName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @GroupID int
	SELECT @GroupID=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
	select ld.id,ld.name from TA_Tbl_LevelRights lr
	inner join Ta_Tbl_levelDetails ld on lr.LevelId=ld.id
	where lr.GroupId=@GroupID and ld.parentId=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]
	-- Add the parameters for the stored procedure here
	@EmailLevelid int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempLevelDetails(Levelid int,parentId int)
	Declare @LevelId int
	Declare @ParentId int
    -- Insert statements for procedure here
    if((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)!=0)
		begin
			while((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)!=0)
				begin
					select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
					insert into #TempLevelDetails values(@LevelId,@ParentId)
					set @EmailLevelid=@ParentId 
					if((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)=0)
						begin
							select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
							insert into #TempLevelDetails values(@LevelId,@ParentId)
						end
				end
		end
	else
		begin
			if Exists(select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)
				begin
					select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
					insert into #TempLevelDetails values(@LevelId,@ParentId)		
				end
		end
	select * from #TempLevelDetails 	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 2016-01-05
-- Description:	Getting Parent level id For Successive year value calculation
-- After getting the issue in client place while using successive year in leave application,its not allowing to save the data.
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]
	-- Add the parameters for the stored procedure here
	@EmployeeAutoID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,	
		SWIPECARD VARCHAR(50)
	)
	Declare @levelId int	
	set @levelId=
	(
		SELECT top 1 EL.LEVELID FROM 
		(
			SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EMPLOYEEID FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 	
			WHERE EMP.ISDELETED=0 and EMP.Employee_id=@EmployeeAutoID
			group by EmployeeId
		) ELEVEL
		INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID	
		AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(getdate() AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
	)
	while((select parentId from Ta_Tbl_levelDetails where id=@levelId)!=0)
	begin
		select @levelId=parentId from Ta_Tbl_levelDetails where id=@levelId
	end
	select @levelid
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPassportExpiryAlert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Velumani P
-- Create date:  31 Jan 2020
-- Description:   Get Passport notification Details
-- Proc_TA_GetPassportExpiryAlert 4,'IndividualUsers'
--Proc_TA_GetPassportExpiryAlert 3,'IndividualUsers'
--Proc_TA_GetPassportExpiryAlert 2,'IndividualUsers'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPassportExpiryAlert]
      -- Add the parameters for the stored procedure here
      @employeeID as int,
      @UserGroupName as nvarchar(100)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
		declare @PassportExpiry varchar(250) 
		declare @PassportFromdate datetime
		Declare @PassportTodate datetime
		Declare @TodayExpiry datetime
		Declare @Valid int
		DECLARE @DATEFORMAT AS INT
		DECLARE @TIMEFORMAT AS NVARCHAR(10)
		SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
		set @Valid= 0
		select @PassportFromdate = dateadd(dd, -50,Passport_expirydate) from TA_Tbl_Employee where Employee_Id = @employeeID
		select @PassportTodate = Passport_expirydate from TA_Tbl_Employee where Employee_Id = @employeeID
		select @Valid = 1 where getdate() between @PassportFromdate and @PassportTodate
		select @Valid = 2 where @PassportTodate < getdate()
		set @TodayExpiry = (select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
		select @Valid = 3 where @PassportTodate = @TodayExpiry

		if(@Valid = 1)
		begin
			set @PassportExpiry = 'Your Passport will be expired on ' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + '. Please update '
		End
		else if(@Valid = 2)
		begin
			set @PassportExpiry = 'Your Passport expired on ' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + '. Please update '
		End	
		else if(@Valid = 3)
		begin
			set @PassportExpiry = 'Your Passport will expire today ' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + '. Please update '
		End	
		else
		begin
			set @PassportExpiry = '0'
		End

		------

	select isnull(@PassportExpiry,0) as Passport

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPassportExpiryForEmail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- exec Proc_TA_GetPassportExpiryForEmail 24
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetPassportExpiryForEmail]
	-- Add the parameters for the stored procedure here
	@employeeID as int = 0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	declare @IsPassportRemainderReq as bit = 0
	declare @IsVisaRemainderReq as bit = 0
	declare @PassportRemaindDays as int = 0
	declare @VisaRemaindDays as int = 0	
	Declare @PassportExpiryDate as Datetime	
	Declare @PassportExpireDate as Datetime
	Declare @VisaExpireDate as Datetime	
	Declare @Cnt as int = 0
	Declare @EmpName nvarchar(100) = null
	Declare @ReportingID as int = 0
	Declare @SancID as int = 0
	Declare @ReportingToMailId as  nvarchar(100) = null
	Declare @LeaveSancAuthorityMailId as nvarchar(100) = null


	Select EmailId,
(Select EmailId from TA_Tbl_Employee R where R.Employee_Id=E.Reporting_To) as Reporting_ToEmail,
(Select EmailId from TA_Tbl_Employee A where A.Employee_Id=E.Leave_Sanc_Authority) as Leave_Sanc_AuthorityEmail,
PassportRemindDays,case when DATEDIFF(DD,getdate(), E.Passport_expirydate) > 0 then
('Remainder!!! <br> <br> Dear '+isnull(E.Employee_FirstName,'') + isnull(E.Employee_LastName,'')+',<br> your Passport No.('+ E.Passport_No +') will be expired in '+ Convert(varchar(10), DATEDIFF(DD,getdate(),E.Passport_expirydate))+' days on '+CONVERT(varchar(20), E.Passport_expirydate)+ '  please update <br> Thanks & Regards <br><br> Timecheck  ')  
else
'Remainder!!! <br> <br> Dear '+isnull(E.Employee_FirstName,'') + isnull(E.Employee_LastName,'')+', Your Passport No.('+ E.Passport_No +') has be expired '+CONVERT(varchar(20), E.Passport_expirydate)+ ' on  Please update <br> Thanks & Regards <br> <br> Timecheck' end as PassportExpiresOn
from TA_Tbl_Employee E where e.IsPassportReminderRequired=1
and DATEDIFF(DD,getdate(),E.Passport_expirydate)<=E.PassportRemindDays





 Select  EmailId,
(Select EmailId from TA_Tbl_Employee R where R.Employee_Id=E.Reporting_To) as Reporting_ToEmail,
(Select EmailId from TA_Tbl_Employee A where A.Employee_Id=E.Leave_Sanc_Authority) as Leave_Sanc_AuthorityEmail,
VisaRemindDays,case when DATEDIFF(DD,getdate(),E.Visa_expirydate)>0 then 
('Remainder!!! <br> <br> Dear '+isnull(E.Employee_FirstName,'') + isnull(E.Employee_LastName,'')+', <br> your Visa No.('+ E.Visa_No +') will be expired in '+ Convert(varchar(10), DATEDIFF(DD,getdate(),E.Visa_expirydate))+' days on '+CONVERT(varchar(20), E.Visa_expirydate)+ '  please update <br> Thanks & Regards <br> <br> Timecheck')  
else
'Remainder!!! <br> <br> Dear '+isnull(E.Employee_FirstName,'') + isnull(E.Employee_LastName,'')+', <br> Your Visa No.('+ E.Visa_No +') has be expired '+CONVERT(varchar(20), E.Visa_expirydate)+ ' on  Please update <br> Thanks & Regards <br> <br> Timecheck' end as VisaExpiresOn
from TA_Tbl_Employee E where e.IsVisaReminderRequired=1 
and DATEDIFF(DD,getdate(),E.Visa_expirydate)<=E.VisaRemindDays


	------Create table #TempEmpDetails (
	------Employee_FirstName nvarchar(100),
	------EmailId nvarchar(100),
	------Reporting_To int,
	------Leave_Sanc_Authority int,
	------IsPassportReminderRequired bit,
	------Passport_expirydate datetime,
	------PassportRemindDays int,
	------IsVisaReminderRequired bit,
	------Visa_expirydate datetime,
	------VisaRemindDays int)

	------insert into #TempEmpDetails
	------select Employee_FirstName,
	------EmailId,
	------Reporting_To,
	------Leave_Sanc_Authority,
	------IsPassportReminderRequired,
	------Passport_expirydate,
	------PassportRemindDays,		
	------IsVisaReminderRequired,
	------Visa_expirydate,
	------VisaRemindDays 
	------from TA_Tbl_Employee where Employee_Id = @employeeID

	------select * from #TempEmpDetails

	------set @ReportingID = (select Reporting_To from #TempEmpDetails )
	------set @SancID = (select Leave_Sanc_Authority from #TempEmpDetails )

	------IF(@ReportingID IS NOT NULL)
	------BEGIN
	------set @ReportingToMailId = (select EmailId from TA_Tbl_Employee where Employee_Id = @ReportingID) 
	------END
	------IF (@SancID IS NOT NULL)
	------BEGIN
	------set @LeaveSancAuthorityMailId = (select EmailId from TA_Tbl_Employee where Employee_Id = @SancID) 
	------END
	
	------select @ReportingToMailId as ReportingToMailID
	------select @LeaveSancAuthorityMailId as LeaveSancationMailID

	------set @IsPassportRemainderReq = (Select IsPassportReminderRequired from #TempEmpDetails )
	------set @IsVisaRemainderReq = (Select IsVisaReminderRequired from #TempEmpDetails )
	------set @EmpName = (Select Employee_FirstName from #TempEmpDetails )

	------IF(@IsPassportRemainderReq = 1 )
	------BEGIN
	------  SET @PassportExpiryDate = (select Passport_expirydate from #TempEmpDetails )	 
	------  SET @PassportRemaindDays = (select PassportRemindDays from #TempEmpDetails )
	------  SET  @cnt=  DATEDIFF(Day,Getdate(),Convert(Date,@PassportExpiryDate))

	------  IF(@PassportRemaindDays >= @cnt)
	------		BEGIN
	------		  --select 'Your Passport will be expired '+CONVERT(varchar(20), @PassportExpiryDate)+ ' on  Please update '
 ------              select 'Dear '+@EmpName+' your Passport will be expired in '+ Convert(varchar(10), @cnt)+' days on '+CONVERT(varchar(20), @PassportExpiryDate)+ '  please update '                as PassportExprieson
	------		END
	------		ELSE
	------		BEGIN
	------			select 'Dear '+@EmpName+' Your Passport has be expired '+CONVERT(varchar(20), @PassportExpiryDate)+ ' on  Please update ' as PassportExprieson
	------		END
	------END

	------IF(@IsVisaRemainderReq = 1)
	------BEGIN
	------ SET @cnt = 0
	------ SET @VisaExpireDate = (select Visa_expirydate from #TempEmpDetails )
	------ SET @VisaRemaindDays = (select VisaRemindDays from #TempEmpDetails )
	
	------ SET  @cnt=  DATEDIFF(Day,Getdate(),Convert(Date,@VisaExpireDate))

	------ IF(@VisaRemaindDays >= @cnt)
	------		BEGIN
	------		  --select 'Your Passport will be expired '+CONVERT(varchar(20), @PassportExpiryDate)+ ' on  Please update '
 ------              select 'Dear '+@EmpName+' your Visa will be expired in '+ Convert(varchar(10), @cnt)+' days on '+CONVERT(varchar(20), @PassportExpiryDate)+ '  please update '                as VisaExprieson
	------		END
	------		ELSE
	------		BEGIN
	------			select 'Dear '+@EmpName+' Your Visa has be expired '+CONVERT(varchar(20), @PassportExpiryDate)+ ' on  Please update ' as VisaExprieson
	------		END
	------END

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPassportVisaExpiryDetailsEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Manikandan.RR
-- Create date: 28-May-2022
-- Description:   Get Passport And Visa Expiry Details and not for superadmin login
-- Proc_TA_GetPassportVisaExpiryDetailsEmployee 2,'Approval'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPassportVisaExpiryDetailsEmployee]
      @employeeID as INT,
      @UserGroupName as nvarchar(100)
AS
BEGIN
     SET NOCOUNT ON;
	DECLARE @local_employeeID INT
	DECLARE @local_UserGroupName nvarchar(100)
	SET @local_employeeID =@employeeID
	SET @local_UserGroupName =@UserGroupName
	declare @today datetime =getdate()
	Create Table #TempSanctionUser(Employee_id INT)
	create table #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId INT)
	create table #EmployeeIds(EmpAutoId INT)
	insert INTo  #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@local_UserGroupName,0) as LevelId
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	FROM  
	(
		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@today as nVARCHAR(50)), 102) and EL.LevelId is not null
	and (el.EmployeeId=CAST(@local_employeeID as nvarchar(10)))
	DECLARE @EmpLevel bigINT
	DECLARE @CompanyID bigINT
	SELECT @EmpLevel=LevelId FROM #EmpLevel WHERE EmployeeId=@employeeID
	SELECT @CompanyID=dbo.Func_TA_GetParentIds(@EmpLevel)
	DECLARE @passCount INT
	DECLARE @VisCount INT
	IF(ISNULL(@CompanyID,0)!=0 AND @CompanyID!='')
	BEGIN
		DECLARE @isRemindRrd_Pas_Vis INT
		DECLARE @reminderDays INT
		DECLARE @Main_reminderDays INT
		SELECT @isRemindRrd_Pas_Vis=isRemindRrd_Pas_Vis,@reminderDays=reminderDays FROM TA_Tbl_ShiftSettings WHERE CompanyId=@CompanyID
		IF(ISNULL(@isRemindRrd_Pas_Vis,0)=1)
		BEGIN
			SET @Main_reminderDays=ISNULL(@reminderDays,60)
			SET @reminderDays=ISNULL(@reminderDays,60)
			DECLARE @PassRemndDys_ByEmp INT
			DECLARE @VisRemndDys_ByEmp INT
			DECLARE @Pass_LastUpdated DATETIME
			DECLARE @Visa_LastUpdated DATETIME
			SELECT @PassRemndDys_ByEmp=ISNULL(PassportRemindDays,0),@VisRemndDys_ByEmp=ISNULL(VisaRemindDays,0), 
			@Pass_LastUpdated=IsPass_LastUpdatedOn,@Visa_LastUpdated=IsVisa_LastUpdatedOn
			FROM TA_Tbl_Employee WHERE Employee_Id=@employeeID
			--select @PassRemndDys_ByEmp,@VisRemndDys_ByEmp,@Pass_LastUpdated,@Visa_LastUpdated
			Create table #TempPassVisaExpiry(ExpiryContent varchar(max), ExpiryNumber int)
			IF(@PassRemndDys_ByEmp!=0)
			BEGIN
				SET @reminderDays=@PassRemndDys_ByEmp
			END			
			IF(ISNULL(@Pass_LastUpdated,'')!='')
			BEGIN
				INSERT INTO #TempPassVisaExpiry
				SELECT ExpiryContent='Your Passport will expire on <B>' + CONVERT(varchar(11),Passport_expirydate) +'</B>, please get it renewed.',ExpiryNumber=1  FROM TA_Tbl_Employee WHERE Employee_Id=@employeeID
				AND (Passport_expirydate IS NOT NULL and Passport_expirydate<=DATEADD(d,0,GETDATE()))
				and (DATEADD(d,@reminderDays,@Pass_LastUpdated)<=DATEADD(d,@reminderDays,GETDATE()))
			END
			ELSE
			BEGIN
				INSERT INTO #TempPassVisaExpiry
				SELECT ExpiryContent='Your Passport will expire on <B>' + CONVERT(varchar(11),Passport_expirydate) +'</B>, please get it renewed.',ExpiryNumber=1  FROM TA_Tbl_Employee WHERE Employee_Id=@employeeID
				AND (Passport_expirydate IS NOT NULL and Passport_expirydate<=DATEADD(d,@Main_reminderDays,GETDATE()))
			END
			IF(@VisRemndDys_ByEmp!=0)
			BEGIN
				SET @reminderDays=@VisRemndDys_ByEmp
			END
			IF(ISNULL(@Visa_LastUpdated,'')!='')
			BEGIN
				INSERT INTO #TempPassVisaExpiry
				SELECT ExpiryContent='Your Visa will expire on <B>' + CONVERT(varchar(11),Visa_expirydate) +'</B>, please get it renewed.',2  FROM TA_Tbl_Employee WHERE Employee_Id=@employeeID
				AND (Visa_expirydate IS NOT NULL AND Visa_expirydate<=DATEADD(d,0,GETDATE()))
				and (DATEADD(d,@reminderDays,@Visa_LastUpdated)<=DATEADD(d,0,GETDATE()))
			END
			ELSE
			BEGIN
				--select @reminderDays
				INSERT INTO #TempPassVisaExpiry
				SELECT ExpiryContent='Your Visa will expire on <B>' + CONVERT(varchar(11),Visa_expirydate) +'</B>, please get it renewed.',2  FROM TA_Tbl_Employee WHERE Employee_Id=@employeeID
				AND (Visa_expirydate IS NOT NULL AND Visa_expirydate<=DATEADD(d,@Main_reminderDays,GETDATE()))
			END
			SELECT * FROM #TempPassVisaExpiry	
		END
	END
	drop table #EmpLevel
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollConfigurationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- ================================================
-- Author:		Gopinath
-- Create date: 23-Jul-15
-- Description:	Get the PayrollConfiguration Settings Details
-- ================================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPayrollConfigurationDetails] 
AS
BEGIN
select convert(char(5),dateadd(MINUTE,StartTime1,''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_Lateentry
select  convert(char(5),dateadd(MINUTE,StartTime1,''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_Armis
select  convert(char(5),dateadd(MINUTE,StartTime1,''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_WorkHrs
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPayrollDetails]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ppd.Employee_Id,ppd.HrsWork,ppd.HrsOT,ppd.NormOT,ppd.OffOT,ppd.HolOT,ppd.EarlyOut,ppd.LateIn,ppd.WorkHrs,ppd.HrsLess,ppd.HrsExtra from ta_tbl_payrollprocessdetails ppd,ta_tbl_monthClosure mc where ppd.MonthClosure_Id = mc.MonthClosure_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPenaltyPercentageDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <18-06-2019 10:20 AM>
-- Description:	<Get the Penalty Percentage details for displaying>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPenaltyPercentageDetails]
	@CompanyID int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT CompanyId, categoryID, StartTime1, EndTime1, StartTime2, EndTime2, StartTime3, EndTime3,
	Day1=convert(int,Day1), 
	Day2=convert(int,Day2), 
	Day3=convert(int,Day3), 
	Day4=convert(int,Day4), 
	Day5=convert(int,Day5),
	Day6=convert(int,Day6),
	Day7=convert(int,Day7), 
	Day8=convert(int,Day8), 
	Day9=convert(int,Day9), 
	Day10=convert(int,Day10), 
	Day11=convert(int,Day11), 
	Day12=convert(int,Day12), StartTime1Mins, EndTime1Mins, StartTime2Mins, EndTime2Mins, StartTime3Mins, EndTime3Mins from ta_tbl_PenaltyPercentage where CompanyId=@CompanyID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionByPermissionId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetPermissionByPermissionId 12
Description		:	Get Permission Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetPermissionByPermissionId]
	@Permission_Id int =null
as
begin
	set nocount on;
	select *,EL.LevelId,ED.DesignationId from TA_Tbl_Permission P
	inner join TA_TBL_Employee E on P.Employee_Id=E.Employee_Id
	inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeId 
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=EL.LevelId   
	where 
	((@Permission_Id is null) or (Permission_Id=@Permission_Id)) and 
	EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and 
	EffectiveDate <= P.Permission_AppliedDate order by EffectiveDate desc)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionConversation] 
	@permissionApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_PermissionConversation WHERE PermissionId = @permissionApplicationId Order by OrderBy desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : Proc_TA_GetPermissionHoursAlreadyTaken 5,'11/21/2016'
Description : Get Total No of Permisssion Hours Taken in minutes Based on their Employee_Id
Tables Included : TA_Tbl_Permission
Created By : Prabakaran
Created On : 21-Jul-07
Modified By :
Modified On :
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]
	@Employee_Id bigint,
	@permissionDate datetime
AS
begin
	set nocount on;
	Create table #tempPermission(HoursTakenInMinutes varchar(20), InstancesTaken int)
	insert into #tempPermission 
		Select SUM(
		convert(int,substring(No_Of_Hours,0,charindex(':',No_Of_Hours)))*60+convert(int,substring(No_Of_Hours,charindex(':',No_Of_Hours)+1,LEN(No_Of_Hours)))) as HoursTakenInMinutes ,isnull(count(*),0) as InstancesTaken from TA_Tbl_Permission
		inner join TA_Tbl_YearSetting ys on TA_Tbl_Permission.YearSettings_Id=ys.YearSettings_Id
		where ys.IsActive=1 and Employee_Id =@Employee_Id and IsDeleted = 0 
		and Permission_Status <>'Rejected' 
		and month(Permission_Date)=month(@permissionDate) 
		and year(Permission_Date)=year(@permissionDate)
		select isnull(case when len(HoursTakenInMinutes/60)=1 then '0'+CONVERT(varchar(20),HoursTakenInMinutes/60)
		else CONVERT(varchar(20),HoursTakenInMinutes/60) 
		end 
		+ ':' + 
		case when len(HoursTakenInMinutes%60)=1 then '0'+CONVERT(varchar(20),HoursTakenInMinutes%60)
		else CONVERT(varchar(20),HoursTakenInMinutes%60)
		end,'00:00') as HoursTakenInMinutes,InstancesTaken from #tempPermission 
	drop table #tempPermission
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_employeelevel where employeeid='10861'
--Proc_TA_GetPermissionSanctionDetails  '10864',1,'Forwarded','4/1/2011','3/31/2012',0,'','','','Individual Users',1,0,0
--Proc_TA_GetPermissionSanctionDetails  '5',1,'All','','',0,'','','','Second Level User',1,0,0
-- =============================================
-- Author			: Prabakaran.P
-- Modified date	: 13-Feb-2012
-- Modified by		: Manikandan.R   
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails]  
	@Employee_Id int,  
	@LevelId varchar(2000),  
	@Status varchar(20) =null,  
	@Permission_FromDate varchar(30) =null,  
	@Permission_ToDate varchar(30) =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int,
	@EmployeeCategory int, 
	@EmployeeType int
as 
	begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @sqlQuery as nvarchar(max)
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID     
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @sqlQuery=''
	set @sqlQuery = 'select e.employee_code_id as employeeid,P.Permission_Id,P.Permission_Status, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end AS Permission_AppliedDate,	
	(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '' '', ''/'') + '' - '' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '' '', ''/'')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,''''))as Employee_FirstName '
	set @sqlQuery = @sqlQuery + ' from #TempPermissionDetails E  inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id inner join TA_Tbl_EmployeeLevel ELevel on ELevel.EmployeeId=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=ELevel.levelID '		
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '		
	set @sqlQuery = @sqlQuery + ' where' 
	set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1 and '
	set @sqlQuery = @sqlQuery + ' ELevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id AND EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc) ' 
	if(@strEmployeeCodeId!='' and @strEmployeeCodeId is not null)
		begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		end
	if(@strEmployeeName!='' and @strEmployeeName is not null)
		begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_FirstName = ''' + cast(@strEmployeeName as nvarchar(50)) + ''''
		end				
	If Not (@strSwipeCardNo = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' '  
		End 
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
		end
	if (cast(@Permission_FromDate as nvarchar(20))!='')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date>=CONVERT(DATETIME, ''' + cast(@Permission_FromDate as nvarchar(20)) + ''', 102))'
		End
	if (cast(@Permission_ToDate as nvarchar(20))!='')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date<=CONVERT(DATETIME, ''' + cast(@Permission_ToDate as nvarchar(20)) + ''', 102))'
		End	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if (@UserGroupName!='Superadmin' and @isReportingto!=0)
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((P.Permission_Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
				set @sqlQuery = @sqlQuery + ' or (P.Permission_Status IN (''Forwarded'',''Approved'',''Rejected'')and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)+'))'
			end
	end
	else 
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((P.Permission_Status IN (''Pending''))'
				set @sqlQuery = @sqlQuery + ' or (P.Permission_Status IN (''Forwarded'',''Approved'',''Rejected'')))'
			end
	End
	set @sqlQuery = @sqlQuery + 'order by P.Permission_Id desc'	
		exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop table #TempPermissionDetails
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_employeelevel where employeeid='10861'
--Proc_TA_GetPermissionSanctionDetails  '10864',1,'Forwarded','4/1/2011','3/31/2012',0,'','','','Individual Users',1
--Proc_TA_GetPermissionSanctionDetails  '10863',1,'All','4/1/2011','3/31/2012',0,'','','','ReportingTo',1
-- =============================================
-- Author			: Prabakaran.P
-- Modified date	: 13-Feb-2012
-- Modified by		: Manikandan.R   
--	Modified By		:	Manjula.P
--	Modified On		:	21-Apr-2014
--	Descriptions	:	Adding usergroup and parentId from PRODUCT development for ANGLER Migration 
--	Proc_TA_GetPermissionSanctionDetails 5,'3','Forwarded','03/01/2014 12:00:00 AM','05/31/2014 12:00:00 AM',0,'','','878','EIT - PMs',3           
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]  
	@Employee_Id int,  
	@LevelId varchar(2000),  
	@Status varchar(250) =null,  
	@Permission_FromDate datetime =null,  
	@Permission_ToDate datetime =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int   
as 
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @sqlQuery=''
	set @sqlQuery1=''
	set @sqlQuery = 'select p.permission_reason, lv.name as levelname,e.employee_code_id,P.Permission_Id,P.Permission_Status, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end AS Permission_AppliedDate,	
	(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '' '', ''/'') + '' - '' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '' '', ''/'')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,''''))as Employee_FirstName '
	set @sqlQuery = @sqlQuery + ' from #TempPermissionDetails E  inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id inner join TA_Tbl_EmployeeLevel ELevel on ELevel.EmployeeId=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_leveldetails lv on lv.Id=ELevel.levelID   ' 
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=ELevel.levelID '				
	set @sqlQuery = @sqlQuery + ' where' 
	set @sqlQuery = @sqlQuery + ' E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1 and '
	set @sqlQuery = @sqlQuery + ' ELevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id AND EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc) ' 
	if(@strEmployeeCodeId!='' and @strEmployeeCodeId is not null)
		begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		end
	if(@strEmployeeName!='' and @strEmployeeName is not null)
		begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_FirstName = ''' + cast(@strEmployeeName as nvarchar(50)) + ''''
		end				
	If Not (@strSwipeCardNo = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' '  
		End 
	if not(cast(@Permission_FromDate as nvarchar(11))='' or cast(@Permission_FromDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date>=CONVERT(DATETIME, ''' + cast(@Permission_FromDate as nvarchar(11)) + ''', 102))'
		End
	if not(cast(@Permission_ToDate as nvarchar(11))='' or cast(@Permission_ToDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date<=CONVERT(DATETIME, ''' + cast(@Permission_ToDate as nvarchar(11)) + ''', 102))'
		End	
	if @Status='Pending' or @Status='Rejected' or @Status='Resend' or @Status='Reply'
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'		
		end
	else if(@Status='Forwarded' or @Status='Approved')
		begin			
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'	
			set @sqlQuery = @sqlQuery + ' and (E.LeaveSanction = ''' + cast(@Employee_Id as nvarchar(50)) + ''' or E.ReportTo = ''' + cast(@Employee_Id as nvarchar(50)) + ''') '			
		end
	else if(lower(@Status)='all')		
		begin					
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected'',''Resend'',''Reply''))'					end		
		exec(@sqlQuery)
	drop table #LevelRights
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_GetPermissionSanctionDetailsForSuperAdmin  '20','Rejected','8/1/2008','9/30/2008'
Description		: Get Permission Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,  
Tables Included : TA_Tbl_Permission and TA_TBL_Employee  
Created By		: Prabakaran  
Created On		: 23-Jul-07  
Modified By		: Prabakaran  
Modified On		: 24-Jul-07  
Proc_TA_GetPermissionSanctionDetailsForSuperAdmin 1,1,'Pending','20200101','20200501',0,'','','','SuperAdmin',1,0,0
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]  
	@Employee_ID int,
	@LevelId varchar(2000),  
	@Status varchar(20) =null,  
	@Permission_FromDate VARCHAR(30) =null,  
	@Permission_ToDate VARCHAR(30) =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int,
	@EmployeeCategory int, 
	@EmployeeType int
as  
 begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
    
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(MAX)
	set @sqlQuery=''
	set @sqlQuery = 'select E.Employee_Code_Id as employeeid,P.Permission_Id,P.Permission_Status, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end AS Permission_AppliedDate	
	,(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '' '', ''/'') + '' - '' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '' '', ''/'')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName from #TempPermissionDetails E  '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.levelID '
	set @sqlQuery = @sqlQuery + ' where  E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1'
	set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc)'
	If not(@strEmployeeCodeId = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If Not (@strSwipeCardNo = '')  
		Begin  
			  Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' '  
		End 
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
		end
	If not(@strEmployeeName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''')'
		End
	
	if (@UserGroupName!='Superadmin' and @isReportingto!=0)
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((P.Permission_Status IN (''Pending'')and ReportTo='+CONVERT(varchar(20),@Employee_Id)+')'
				set @sqlQuery = @sqlQuery + ' or (P.Permission_Status IN (''Forwarded'',''Approved'',''Rejected'')and LeaveSanction='+CONVERT(varchar(20),@Employee_Id)+'))'
			end
	end
	else 
	begin
		if (@Status='Pending' or @Status='Rejected')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'		
			end
		else if(@Status='Forwarded' or @Status='Approved')
			begin
				set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status + '''))'
			end	
		else if(@Status='All')		
			begin
				--print 's'
				set @sqlQuery = @sqlQuery + ' and ((P.Permission_Status IN (''Pending''))'
				set @sqlQuery = @sqlQuery + ' or (P.Permission_Status IN (''Forwarded'',''Approved'',''Rejected'')))'
			end
	End
		
	--if (@Status='Pending' or @Status='Rejected' or @Status='Forwarded' or @Status='Rejected' or @Status='Approved')
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status  + '''))'
	--	End
	--else if(@Status='All')
	--	begin				
	--		set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected''))'
	--	end	
	if(cast(@Permission_FromDate as nvarchar(11))!='')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date>=CONVERT(DATETIME, ''' + cast(@Permission_FromDate as nvarchar(11)) + ''', 102))'
		End
	if (cast(@Permission_ToDate as nvarchar(11))!='')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date<=CONVERT(DATETIME, ''' + cast(@Permission_ToDate as nvarchar(11)) + ''', 102))'
		End
	exec(@sqlQuery + ' Order by Permission_Id desc')
	print(@sqlQuery + ' Order by Permission_Id desc')
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
END	
---------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_GetPermissionSanctionDetailsForSuperAdmin  '20','Rejected','8/1/2008','9/30/2008'
Description		: Get Permission Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,  
Tables Included : TA_Tbl_Permission and TA_TBL_Employee  
Created By		: Prabakaran  
Created On		: 23-Jul-07  
Modified By		: Prabakaran  
Modified On		: 24-Jul-07  
Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler 3,'All','03/01/2014 12:00:00 AM','05/31/2014 12:00:00 AM',0,'','','','SuperAdmin',3
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]  
	@LevelId varchar(2000),  
	@Status varchar(250) =null,  
	@Permission_FromDate datetime =null,  
	@Permission_ToDate datetime =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int 
as  
begin
	set nocount on;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery = 'select p.permission_reason, lv.name as levelname, P.Permission_Id,P.Permission_Status, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end AS Permission_AppliedDate	
	,(REPLACE(CONVERT(VARCHAR(11), p.Permission_FromTime, '+cast(@dateFormat as varchar(100))+'), '' '', ''-'') + 
	'' - '' + REPLACE(CONVERT(VARCHAR(11), p.Permission_ToTime, '+cast(@dateFormat as varchar(100))+'), '' '', ''-'')) AS Duration,
	p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) as Employee_FirstName from TA_TBL_Employee E  '
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_leveldetails lv on lv.Id=EL.levelID   '  
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.levelID '
	set @sqlQuery = @sqlQuery + ' where  E.Isdeleted=0 and P.IsDeleted=0 '
	--and ys.IsActive=1'
	set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc)'
	If not(@strEmployeeCodeId = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and E.Employee_Code_Id = ''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''
		End
	If Not (@strSwipeCardNo = '')  
		Begin  
			  Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @strSwipeCardNo + ''' '  
		End 
	If not(@strEmployeeName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''')'
			--set @sqlQuery = @sqlQuery + ' and E.Employee_FirstName like ''' + cast(@strEmployeeName+'%' as nvarchar(100)) + ''''
		End
	if (lower(@Status)<>'all' and isnull(@Status,'')<>'' )
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''' + @Status  + '''))'
		End
	else if(@Status='All')
		begin		
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected'',''Resend'',''Reply'')) '
		end	
	if not(cast(@Permission_FromDate as nvarchar(11))='' or cast(@Permission_FromDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date>=CONVERT(DATETIME, ''' + cast(@Permission_FromDate as nvarchar(11)) + ''', 102))'
		End
	if not(cast(@Permission_ToDate as nvarchar(11))='' or cast(@Permission_ToDate as nvarchar(11))='0')
		begin
			set @sqlQuery = @sqlQuery + ' and (P.Permission_Date<=CONVERT(DATETIME, ''' + cast(@Permission_ToDate as nvarchar(11)) + ''', 102))'
		End
	exec(@sqlQuery + ' Order by Permission_Id,Year(P.Permission_AppliedDate) desc,Month(P.Permission_AppliedDate) desc,Day(P.Permission_AppliedDate) desc')
	drop table #LevelRights
	end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetPolicyConfigurationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <15-Oct-2021 10:27 am>
-- Description:	<Get Policy Configuration Details>
-- Proc_Ta_GetPolicyConfigurationDetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetPolicyConfigurationDetails]	
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Pol_Config_id,
	Daily_Rrd,
	Daily_Hrs=dbo.ConvertMinsToHours(Daily_Hrs),
	Day_Rqrd,
	Day_Value,
	Weekly_Rqrd,
	Weekly_Hrs,
	Quarterly_Rqrd,
	Quarterly_Hrs,
	Cont_Absent,
	Cont_Value,
	CreatedDate,
	ModifiedDate,
	CreatedBy,
	ModifiedBy,
	ApproFolderPath,
	EmpAPI1,
	EmpAPI2,
	EmpAPI3,
	BlockAPI,
	LogDownloadAPI,
	userName,
	password,
	DataProcessDate
	from ta_tbl_policyconfiguration
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_GetPreviousLeaveDetails
Description		: Get Previous Leave Details
Created By		: A.K.T.MOORTHI
Created On		: 03-JUNE-2013
Modified By		: A.K.T.MOORTHI
Modified On		: 10-JULY-2013
Description		: Change the Table header for 'Leave Availed Details' to 'Leave Status'
EXEC [Proc_TA_GetPreviousLeaveDetails] 545, '', 'M'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetPreviousLeaveDetails]
	@EmployeeId INT = NULL,
	@EmployeeCode VARCHAR(60) = NULL,
	@Type VARCHAR(1)
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @EmpFYLeave TABLE(EmployeeId INT, LeaveType VARCHAR(100), NumberOfDays DECIMAL(18,1), LeaveStatus VARCHAR(20))
	DECLARE @EmpCMLeave TABLE(EmployeeId INT, LeaveType VARCHAR(100), NumberOfDays DECIMAL(18,1), LeaveStatus VARCHAR(20))
	DECLARE @FYResult VARCHAR(MAX), @CMResult VARCHAR(MAX)
	INSERT INTO @EmpFYLeave
		SELECT LA.Employee_Id, CASE WHEN LA.[Type] = 'Leave' THEN LT.LeaveType ELSE LA.[Type] END, LA.NumberOfDays, LA.[Status] FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '') OR E.Employee_Code_Id = @EmployeeCode) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN ('Rejected', 'Canceled')
	INSERT INTO @EmpCMLeave
		SELECT LA.Employee_Id, CASE WHEN LA.[Type] = 'Leave' THEN LT.LeaveType ELSE LA.[Type] END, LA.NumberOfDays, LA.[Status] FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '') OR E.Employee_Code_Id = @EmployeeCode) AND
			DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN ('Rejected', 'Canceled')
	IF @Type = 'P' 
	BEGIN
		SELECT 
			LeaveStatus,
			ISNULL(CL, 0) AS CL,
			ISNULL(LOP, 0) AS LOP,
			ISNULL(SL, 0) AS SL,
			ISNULL([Comp Off], 0) AS [Comp Off]
		FROM 
		(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpFYLeave) Tbl
		PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
		SELECT 
			LeaveStatus,
			ISNULL(CL, 0) AS CL,
			ISNULL(LOP, 0) AS LOP,
			ISNULL(SL, 0) AS SL,
			ISNULL([Comp Off], 0) AS [Comp Off]
		FROM 
		(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpCMLeave) Tbl
		PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
	END
	ELSE
	BEGIN
		SET @FYResult = '<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr><tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">No Record Found</font></b></td></tr></table>'
		SET @CMResult = '<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr><tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">No Record Found</font></b></td></tr></table>'
		IF EXISTS(SELECT EmployeeId FROM @EmpFYLeave)
		BEGIN
			SET @FYResult = '<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr>'
			SELECT 
				@FYResult = @FYResult + '<tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">' + CAST(LeaveStatus AS VARCHAR) + '</font></b></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(CL, 0) AS VARCHAR) + '</font></td>' + 
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(LOP, 0) AS VARCHAR) + '</font></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(SL, 0) AS VARCHAR) + '</font></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL([Comp Off], 0) AS VARCHAR) + '</font></td></tr>'
			FROM 
			(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpFYLeave) Tbl
			PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
			SET @FYResult = @FYResult + '</table>'
		END
		IF EXISTS(SELECT EmployeeId FROM @EmpCMLeave)
		BEGIN
			SET @CMResult = '<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr>'
			SELECT 
				@CMResult = @CMResult + '<tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">' + CAST(LeaveStatus AS VARCHAR) + '</font></b></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(CL, 0) AS VARCHAR) + '</font></td>' + 
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(LOP, 0) AS VARCHAR) + '</font></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL(SL, 0) AS VARCHAR) + '</font></td>' +
					'<td height="19"><font face="Arial" size="2">' + CAST(ISNULL([Comp Off], 0) AS VARCHAR) + '</font></td></tr>'
			FROM 
			(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpCMLeave) Tbl
			PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
			SET @CMResult = @CMResult + '</table>'
		END
		SELECT '</br><table border="0" cellpadding="0" cellspacing="1" style="border-collapse: collapse" bordercolor="#111111" width="700"><tr bgColor="#003466"><td height="25" style="border-right: #FFFFFF 1px solid; text-align:center; width:45%;" class="Header">Leave Status - Current Year</td><td style="width:10%; background-color:#FFFFFF;"></td><td height="25" class="Header" style="border-right: #FFFFFF 1px solid; text-align:center; width:45%;">Leave Status - Current Month</td></tr><tr><td style="border-right:#FFFFFF 1px solid; width:45%; vertical-align:top;">' + @FYResult + '</td><td style="width:10%;"></td><td style="border-left:#FFFFFF 1px solid; width:45%; vertical-align:top;">' + @CMResult + '</td></tr></table>' AS 'LeaveDetails'
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousNextLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
					Proc_TA_GetPreviousNextLeave 61,'03/27/2013', '03/29/2013'
					Proc_TA_GetPreviousNextLeave 68,'04/01/2013 12:00:00 AM','04/04/2013 12:00:00 AM'
Created By		:	Manjula.P
Created Date	:	23-May-2013
Descriptions	:	To restrict the combined leave of both CL and SL/Comp Off as per the new leave policy
*/
CREATE proc [dbo].[Proc_TA_GetPreviousNextLeave]
(
@Employee_Id int,
@LeavePrevious datetime,
@LeaveNext datetime
)
as 
begin
	SET NOCOUNT ON;
	select LA.LeaveApplication_Id,LT.LeaveType,LA.Leave_FromDate,LA.Leave_ToDate,Employee_Id,LA.Type, LA.NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
	where (LA.Employee_Id=@Employee_Id) 
	and
	(
	(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
	or
	(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
	or           
	(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
	)
	and LA.IsDeleted=0 and LA.Status<>'Rejected'
end
--SELECT CURRENT_TIMESTAMP
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchTypesByTerminalId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetPunchTypesByTerminalId]
(
	@TerminalId INT,
	@PunchType nVarchar(2)
) 
AS
IF (@PunchType = 'I')
	BEGIN
		 if((select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)=@TerminalId)
			begin
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('In') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('Shift In') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('Break In') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('Lunch In') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('Official In') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '787'
				AND PunchType IN ('Out Duty') AND Isdeleted = 0 and Addedby='A' order by PunchType_Id
			end
		 else
			begin		
				SELECT PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id = @TerminalId 
				AND PunchType IN ('In','Shift In','Break In','Lunch In','Official In','Out Duty') AND Isdeleted = 0
			end
    END
IF (@PunchType = 'O')
    BEGIN
		if((select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)=@TerminalId)
			begin
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('Out') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('Shift Out') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('Break Out') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('Lunch Out') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('Official Out') AND Isdeleted = 0 and Addedby='A'
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != '788' 
				AND PunchType IN ('In Duty') AND Isdeleted = 0 and Addedby='A' order by PunchType_Id
			end
		 else
			begin		
				SELECT PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id = @TerminalId 
				AND PunchType IN ('Out','Shift Out','Break Out','Lunch Out','Official Out','In Duty') AND Isdeleted = 0
			end
    END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchValue]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Proc_TA_GetPunchValue,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPunchValue]
	-- Add the parameters for the stored procedure here
	@inClk_DeviceId varchar(20),
	@inPunchType varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select P.Value from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T  on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID =@inClk_DeviceId
	and P.PunchType = @inPunchType and P.IsDeleted = 0 and T.IsDeleted = 0
END


Select * From TA_Tbl_Terminal

Select * From TA_Tbl_PunchTypes

Select * From TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id='1001'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetQuotaDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Proc_TA_GetQuotaDetails 34,1
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetQuotaDetails]  
@EmpID as int,  
@LeaveTypeID as int  
AS  
BEGIN  
declare @LeaveApplicationCount as int
set @LeaveApplicationCount=(select count(*) from Ta_Tbl_LeaveApplication la
					inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
					where ys.IsActive=1 and la.LeaveType_Id=@LeaveTypeId and la.Employee_Id=@EmpID 
and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
and la.status not in('Rejected')  and la.isdeleted=0 and la.IsBorrow=0)
if(@LeaveApplicationCount > 0)
begin
			 select yc.Current_Quota,lt.LeaveType,sum(isnull(la.NumberOfDays,0)) as Leave_Taken  from ta_tbl_LeaveApplication la  
			 inner join ta_tbl_leavetype lt on la.leavetype_id = lt.LeaveType_ID  
			 inner join ta_tbl_yearclosure yc on yc.Employee_Id=la.Employee_Id and yc.Year_SettingId=la.YearSettings_Id
			and yc.leavetypeid=la.leavetype_id
			 where la.employee_id=@EmpID and la.leavetype_id=@LeaveTypeID and la.Type='Leave' and la.Status<>'Rejected'
			and la.IsDeleted=0  and la.IsBorrow=0 and
			  la.yearsettings_ID= (select yearsettings_ID from ta_tbl_yearsetting where isactive=1)  
			group by yc.Current_Quota,lt.LeaveType
end
else 
		begin
		 select Current_Quota,ta_tbl_leavetype.LeaveType,Leave_Taken  from ta_tbl_yearclosure   
 inner join ta_tbl_leavetype on ta_tbl_yearclosure.leavetypeid = ta_tbl_leavetype.LeaveType_ID  
 where ta_tbl_yearclosure.employee_id=@EmpID and ta_tbl_yearclosure.leavetypeid=@LeaveTypeID and  
  ta_tbl_yearclosure.year_settingID= (select yearsettings_ID from ta_tbl_yearsetting where isactive=1) 
		end
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getRawData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_getRawData '2015/09/01','2015/09/11','101,','karthikeyan','SuperAdmin',0,1,0,0,'Both'
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getRawData]
(
@FromDate varchar(20),
@ToDate varchar(20),
@EmployeeId varchar(max),
@EmployeeName varchar(max),
@UserGroupName varchar(250),
@DesignationID int,
@employeeCategory int,
@employeeType int,
@ParentID int,
@Gender varchar(10)	
)
	-- Add the parameters for the stored procedure here
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		if(@EmployeeId is not null and @EmployeeId <> '')
			begin
				create table #EmployeeID(EmployeeID varchar(25))
				insert into #EmployeeID
				select * from SplitupEmployeeCode(@EmployeeId)
			end	
		if(@EmployeeName is not null and @EmployeeName <> '')
			begin
				create table #EmployeeName(EmployeeID varchar(25))
				insert into #EmployeeName
				select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
			end	
		--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		create table #LevelRights(LevelId int)
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Employee Level Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type insert in Temporary table
		insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
		insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
		insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
		declare @sqlEmpLevel nvarchar(Max)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select * from #LevelRights
		set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.SwipeCardNo '
		End
	Execute(@sqlEmpLevel)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select CAST(Emp_ID as int) from TA_Tbl_Employee
		--select * from #EmployeeID
		--select * from #EmployeeName
		--select * from Ta_Tbl_levelDetails
		declare @sqlQuery as nvarchar(max)
		set @sqlQuery=''
		set @sqlQuery='select RD.CLK_CARDID as ''Employee_Code_Id'',Emp.Employee_FirstName + '' '' + Emp.Employee_LastName as EmployeeName,
Ter.Terminal_Name,CONVERT(nvarchar(20),RD.CLK_DATE, '+ convert(varchar,@dateFormat) +') as ShiftDate,CONVERT(nvarchar(20),RD.CLK_DATE, '+ convert(varchar,@dateFormat) +') as PunchDate,RD.CLK_TIME as PunchTime,PY.PunchType,RD.*,ld.Name as LevelName,CAST(''01-01-1900 '' + RD.CLK_Time as datetime) as OrderTime, case when ReasonId=''0'' then ''Processed'' else case when ReasonId=''1'' then ''Employee is not defined in timecheck'' else case when ReasonId=''2'' then ''Terminal is not created in timecheck application or this device is not used in any entrance master'' else case when ReasonId=''3'' then ''Shift is not allocated for this date'' else ''Punch types is not defined for this device'' end end end end  as Process
from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.Employee_Code_Id=RD.CLK_CARDID  '
		set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID '
		set @sqlQuery = @sqlQuery + ' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value '
		if(@ParentID=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
				set @sqlQuery = @sqlQuery + ' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
				set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
			end
		if(@employeeType=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
			end
		if(@DesignationID=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
			end
		if(@employeeCategory=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
			end
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.SwipeCard '
		End
		If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.SwipeCard '
		End
		set @sqlQuery = @sqlQuery + ' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where RD.CLK_DATE >='''+ @FromDate +''' and RD.CLK_DATE <=''' + @ToDate +''''
		if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and Emp.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		set @sqlQuery = @sqlQuery +'Order by RD.CLK_DATE,OrderTime desc'
		exec(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRawDataFromManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 15.13>
-- Description:	Get the Raw Data from the Manual Time Entry Table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRawDataFromManualEntry]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT M.ManualTimeEntry_Employee_Id,E.SwipeCardNo,M.ManualTimeEntry_Id,convert(varchar(25), M.ManualTimeEntry_InDate,120) as ManualTimeEntry_InDate,
	M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,M.ManualTimeEntry_InReaderID,convert(varchar(25), M.ManualTimeEntry_OutDate,120) as ManualTimeEntry_OutDate,
	M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_Reason,M.Emp_Id,0 as isOnduty,Clock_Address,Latitude_value,Longitude_value FROM TA_Tbl_ManualTimeEntry M 
	INNER JOIN TA_Tbl_Employee E ON M.ManualTimeEntry_Employee_Id = E.Employee_Code_Id 
	WHERE M.Clk_Process = 'N' AND M.Isdeleted = 0  AND M.ManualTimeEntry_Status = 'Approved' and E.Isdeleted=0 and IsOnDuty=0  
	union all
	SELECT M.ManualTimeEntry_Employee_Id,E.SwipeCardNo,M.ManualTimeEntry_Id,convert(varchar(25), M.ManualTimeEntry_InDate,120) as ManualTimeEntry_InDate,
	M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,M.ManualTimeEntry_InReaderID,convert(varchar(25), M.ManualTimeEntry_OutDate,120) as ManualTimeEntry_OutDate,
	M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_Reason,M.Emp_Id,1 as isOnduty,Clock_Address,Latitude_value,Longitude_value FROM TA_Tbl_ManualTimeEntry M 
	INNER JOIN TA_Tbl_Employee E ON M.ManualTimeEntry_Employee_Id = E.Employee_Code_Id
	Inner join TA_Tbl_OndutyEntry OD on (M.OnDuty_ID=OD.Onduty_ID)
	WHERE M.Clk_Process = 'N' AND M.Isdeleted = 0  AND M.ManualTimeEntry_Status = 'Approved' and E.Isdeleted=0 and IsOnDuty=1
	AND OD.Onduty_Status = 'Approved' and OD.Isdeleted=0
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReaderDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 12.47PM>
-- Description:	<Get Reader Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReaderDetails]
	@inTerminalId int
AS
BEGIN	
	SET NOCOUNT ON;
	SELECT Terminal_ReaderId FROM TA_Tbl_Terminal where Terminal_Id = @inTerminalId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name		:	Proc_TA_GetRecordsCountLeaveReportingTo
Description		:	Get Record count of Leave Reporting To details
Tables Included		:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	25-11-2008
Modified By		:	
Modified On		:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo] 
@Employee_Id int
as
begin
	SET NOCOUNT ON;
	select count(*) RecordsCount from TA_TBL_Employee l 
	inner join TA_TBL_Employee r 
	on l.Employee_Id=r.Reporting_To and l.Employee_Id<>r.Leave_Sanc_Authority
	where l.Employee_Id=@Employee_Id and l.Isdeleted=0 and r.Isdeleted=0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name		:	Proc_TA_GetRecordsCountLeaveSanction
Description		:	Get Record count of Leave sanction authority details
Tables Included		:	 TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	27-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE     PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveSanction] 
@Employee_Id int
as
Begin
	SET NOCOUNT ON;
	select count(*) RecordsCount from TA_TBL_Employee l 
	inner join TA_TBL_Employee r 
	on l.Employee_Id=r.Leave_Sanc_Authority 
	where l.Employee_Id=@Employee_Id and l.Isdeleted=0 and r.Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Proc_TA_GetReligionDetailsById]      
(      
 @ID int,    
 @UserGroupName nVarchar(250)      
)      
AS      
  IF(@UserGroupName = 'SuperAdmin')    
    BEGIN    
       SELECT ID,Name,Description,IsDeleted FROM TA_Tbl_Religion Where ID=@ID     
    END    
 ELSE    
   BEGIN    
       SELECT ID,Name,Description,IsDeleted FROM TA_Tbl_Religion Where IsDeleted=0 AND ID=@ID      
   END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- ModifiedBy:		Manikandan.R
-- Modified date:	09-June-2012
-- Description:	to check the check boxes.
-- =============================================
CREATE  Proc [dbo].[Proc_TA_GetReligionTypeDetails]      
(    
	@UserGroupName nVarchar(250)    
)    
AS     
	Create table #TempReligion(ID int,Name nvarchar(100),Description nvarchar(500),IsDeleted bit,flag int)
	IF(@UserGroupName = 'SuperAdmin')    
		BEGIN
			insert into #TempReligion
			SELECT ID,Name,Description,IsDeleted,0 FROM TA_Tbl_Religion order by Name        
		END    
	ELSE    
		BEGIN
			insert into #TempReligion
			SELECT ID,Name,Description,IsDeleted,0 FROM TA_Tbl_Religion Where IsDeleted=0 order by Name           
		END
	Update #TempReligion set flag =1 from #TempReligion TR inner join TA_Tbl_Employee TE on TE.Religion =  TR.ID 
	--where TE.IsDeleted=0
	Update #TempReligion set flag =1 from #TempReligion TR inner join TA_Tbl_leavetype LT on LT.Religion =  TR.ID 
	--where LT.IsDeleted=0
	select * from #TempReligion 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNoOfLOP]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 	:	Proc_TA_GetRemainingNoOfLOP  10924 ,131,'04/09/2012','04/09/2012',4
Description 	:	Get LOP leave quota of Employees Based on their Employee_Id  
Tables Included :	Ta_Tbl_LeaveApplication,TA_Tbl_LeavePolicy  
			TA_Tbl_LeavePolicyDetails,TA_Tbl_Emp_LeavePolicy
			TA_Tbl_YearSetting
Created By 	:	Prabakaran  
Created On	:	20-Nov-07  
Modified By 	: 
Modified On 	:
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNoOfLOP]  
@Employee_Id int,  
@LeaveType_Id int,
@LeaveFromDate datetime,
@LeaveToDate datetime,
@YearSettingId int 
AS  
if(@LeaveType_Id<>-1)
	BEGIN
		declare @LeaveApplicationCount as decimal(18,1)  
        select @LeaveApplicationCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		where la.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id
		and la.Type in ('LOP') and la.status not in('Rejected')  and la.isdeleted=0 
		if(@LeaveApplicationCount > 0)  
			begin  
				Select isnull(lpd.Max_Lop_Days,0.0)-isnull(sum(la.NumberOfDays),0.0) as RemainingNoOfLOPDays,ISNULL(@LeaveApplicationCount,0) as availed
				from TA_Tbl_LeavePolicyDetails lpd
				inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
				inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
				inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId  
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lpd.LeaveType_Id and la.YearSettings_Id=@YearSettingId
				where la.employee_Id=@Employee_Id and elp.EmployeeId=@Employee_Id
				and la.LeaveType_Id=@LeaveType_Id and ys.IsActive=1 and la.Isdeleted=0 
				and la.Status not in ('Rejected') 
				and la.Type in ('LOP') 
				and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
				inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
				where TA_Tbl_YearSetting.IsActive=1
				--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
				and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
				Group by lpd.Max_Lop_Days 
			end  
		else  
			begin  
				Select isnull(lpd.Max_Lop_Days,0.0) as RemainingNoOfLOPDays,ISNULL(@LeaveApplicationCount,0) as availed 
				from TA_Tbl_LeavePolicyDetails lpd
				inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
				inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
				inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId 
				where ys.IsActive=1 and lpd.LeaveType_Id=@LeaveType_Id and elp.EmployeeId=@Employee_Id
				and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
				inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
				where TA_Tbl_YearSetting.IsActive=1
				--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between			TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
				and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			end 
	END 
ELSE
	BEGIN
		    Select lt.LeaveType, isnull(lpd.Max_Lop_Days,0.0)-isnull(sum(la.NumberOfDays),0.0) as RemainingNoOfLOPDays   
			from TA_Tbl_LeavePolicyDetails lpd
			--inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
			inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId  
			inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lpd.LeaveType_Id and la.YearSettings_Id=@YearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id= la.LeaveType_Id 
			where la.employee_Id=@Employee_Id and elp.EmployeeId=@Employee_Id
			and ys.IsActive=1 and la.Isdeleted=0 
			and la.Status not in ('Rejected') 
			and la.Type in ('LOP') and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			--and la.Type in ('LOP') and elp.ToDate in(select TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc) 
			and lpd.LossOfPay=1
			Group by lpd.Max_Lop_Days,lt.LeaveType 
			union
			Select lt.LeaveType,isnull(lpd.Max_Lop_Days,0.0) as RemainingNoOfLOPDays 
			from TA_Tbl_LeavePolicyDetails lpd
			--inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
			inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			inner join  TA_Tbl_LeaveType lt on lt.LeaveType_Id= lpd.LeaveType_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId 
			where ys.IsActive=1 and  elp.EmployeeId=@Employee_Id
			and lpd.LeaveType_Id not in (select LeaveType_Id from Ta_Tbl_LeaveApplication where employee_Id=@Employee_Id and Status not in ('Rejected') and Type in ('LOP')and IsDeleted=0 and YearSettings_Id=@YearSettingId )
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc) 
			and lpd.LossOfPay=1
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetRemainingNumberOfBorrowLeaves 5 ,52
Description		:	Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	19-Feb-08
Modified By		:	
Modified On		:	
*/
CREATE    PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]  
@Employee_Id int,
@LeaveType_Id int
AS
declare @LeaveApplicationCount as int
declare @NumberOfLeavesCount as float
declare @BorrowLeavesCount as float
declare @RemainingNoOfBorrowLeaves as float
BEGIN
SET NOCOUNT ON;
set @LeaveApplicationCount=(
select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id  
where ys.IsActive=1 and la.LeaveType_Id=@LeaveType_Id 
and la.Employee_Id=@Employee_Id 
and la.Type not in ('Restricted Holiday','Comp Off','ESI') 
and la.status not in('Rejected')  and la.isdeleted=0 and la.IsBorrow=1)
set @NumberOfLeavesCount=(
Select ISNULL(sum(la.NumberOfDays),0.0) as RemainingNoOfLeaves 
from TA_tbl_Yearclosure yc
inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and ys.YearSettings_Id=la.YearSettings_Id
where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id
and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id 
and ys.IsActive=1 and la.Isdeleted=0 and la.Status in ('Pending','Forwarded','Approved') 
and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.IsBorrow=1 
)
set @BorrowLeavesCount=(select (lpd.MaxDays_applicable) as RemainingNoOfBorrowLeaves
from TA_Tbl_LeavePolicyDetails lpd
inner join TA_Tbl_Emp_LeavePolicy elp
on elp.LeavePolicy_Id=lpd.Policy_Id
inner join TA_Tbl_YearSetting  ys
on ys.YearSettings_Id=elp.YearSettingId
inner join TA_Tbl_YearClosure yc
on yc.Year_SettingId=ys.YearSettings_Id and yc.Employee_Id=elp.EmployeeId and yc.LeaveTypeID=lpd.LeaveType_Id
where elp.EmployeeId=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.IsActive=1 and elp.Isdeleted=0)
if(@LeaveApplicationCount > 0)
begin
set @RemainingNoOfBorrowLeaves=@BorrowLeavesCount - @NumberOfLeavesCount
end
else
begin
set @RemainingNoOfBorrowLeaves=@BorrowLeavesCount
end
select @RemainingNoOfBorrowLeaves as RemainingNoOfBorrowLeaves
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeaves]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 /*  
Procedure Name : Proc_TA_GetRemainingNumberOfLeaves 35,1,0,'01/28/2019' 
Select ISNULL(NumberOfDays,0.0) from Ta_Tbl_LeaveApplication where LeaveApplication_Id = 1 and LeaveType_id = 1 and Employee_Id = 3 
Description  : Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id  
Tables Included : Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting  
Created By  : Prabakaran  
Created On  : 09-Aug-07  
Modified By  : Prabakaran  
Modified On  : 13-Aug-07  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeaves]  
@Employee_Id int,  
@LeaveType_Id int,
@leaveApplicationId int,
@FromDate datetime  
AS  
declare @LeaveApplicationCount as int  
DECLARE @resendLeaveDays as int
declare @YearSettingId as int
begin
	SET NOCOUNT ON;
	if(@LeaveType_Id<>-1)
		BEGIN
			select @YearSettingId = YearSettings_Id from Ta_Tbl_LeaveApplication where LeaveApplication_Id = @leaveApplicationId
		END
	else
		BEGIN
			select @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate
		END
	if(@LeaveType_Id<>-1 and @leaveApplicationId<>0)  
		 begin  
			set @LeaveApplicationCount=(select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la  
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id   
			where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.status not in('Rejected')  and la.isdeleted=0 and la.IsBorrow=0)  
			if(@leaveApplicationId<>0)
					begin				
						SET @resendLeaveDays = (Select ISNULL(NumberOfDays,0.0) from Ta_Tbl_LeaveApplication where LeaveApplication_Id = @leaveApplicationId and LeaveType_id = @LeaveType_Id and Employee_Id = @Employee_Id)			
					end
			else
					begin
						SET @resendLeaveDays = 0
					end	
			 if(@LeaveApplicationCount > 0)  	
				  begin 
					  Select (@resendLeaveDays + ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves   
					  from TA_tbl_Yearclosure yc  
					  inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
					  inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id  
					  where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 and la.Status in ('Pending','Forwarded','Approved','Resend','Reply') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment  
				  end  
			else   
				  begin  
				  Select ((ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves   
				  from TA_tbl_Yearclosure yc  
				  inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
				  where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId  Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment  
				  end  
		 END  
	else  
		begin  
		if(@LeaveType_Id=-1 and @leaveApplicationId=0)  
		BEGIN
			 Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as 'Number of Days'  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			 where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0  		and la.Status  not in ('Rejected')
			 and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP')   
			 and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType  
			 union  
			 Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as 'Number of Days'  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (  
			 select LeaveType_Id from Ta_Tbl_LeaveApplication la  
			 inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id  
			 where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0   
			 and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and Status not in ('Rejected') and ys.YearSettings_Id=@YearSettingId)  
			 and ys.YearSettings_Id=@YearSettingId    
		END
	else
		BEGIN
			Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as 'Number of Days'  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			 where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id 
			and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
			and LeaveApplication_Id<>@leaveApplicationId   
			 --and la.Status  in ('Pending','Forwarded','Approved') 
			and la.Status  not in ('Rejected')
			 and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP')   
			 and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType  
			 union  
			 Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as 'Number of Days'  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (  
			 select LeaveType_Id from Ta_Tbl_LeaveApplication la  
			 inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id  
			 where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0   
			 and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and Status not in ('Rejected') and ys.YearSettings_Id=@YearSettingId)  
			 and ys.YearSettings_Id=@YearSettingId 
		END
	 END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetRemainingNumberOfLeaves 10849
Description		:	Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
Create PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]
@Employee_Id int,
@LeaveType_Id int
AS
declare @LeaveApplicationCount as int
if(@LeaveType_Id<>-1)
	begin
	set @LeaveApplicationCount=(select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
					inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
					where ys.IsActive=1 and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.status not in('Rejected')  and la.isdeleted=0 and la.IsBorrow=0)
	if(@LeaveApplicationCount > 0)
		begin
		Select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.IsActive=1 and la.Isdeleted=0 and la.Status in ('Pending','Forwarded','Approved') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment
		end
	else 
		begin
		Select ((ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
		where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.IsActive=1  Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment
		end
	end
else
	begin
	-- For Leave Quota Popup Page
	Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as 'Number of Days'
	from TA_tbl_Yearclosure yc
	inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
	left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id
	where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.IsActive=1 and la.Isdeleted=0 
	and la.Status in ('Pending','Forwarded','Approved') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
	and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType
	union
	Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as 'Number of Days'
	from TA_tbl_Yearclosure yc
	inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
	where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (
	select LeaveType_Id from Ta_Tbl_LeaveApplication la
	inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id
	where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
	and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and Status not in ('Rejected') and ys.IsActive=1)
	and ys.IsActive=1  
	end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- [Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear] 2,-1,9
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]
(
	@Employee_Id int,
	@LeaveType_Id int,
	@YearSettingId int
)
AS
Begin
	SET NOCOUNT ON;
	declare @LeaveApplicationCount as decimal(18,1)
	declare @LOPCount as decimal(18,1)
	declare @CurrentyearSettingId int
	Declare @SuccessiveYearSettingId int
	Declare @SuccesiveLeavepolicyCount float
	Declare @MaxapplicableDays float
	Declare @CurrentYearStartDate datetime
	declare @isWFH int
	declare @IsProrataRequired int
	declare @IsDocProofRequired int
	select @CurrentyearSettingId=yearsettings_Id,@CurrentYearStartDate=FromDate from ta_tbl_yearsetting where Isactive=1	
	select top 1 @SuccessiveYearSettingId = yearsettings_Id from ta_tbl_yearsetting where yearSettings_Id > (select Yearsettings_Id from ta_tbl_yearsetting where Isactive=1)
	Declare @DateofJoining datetime
	Select @DateofJoining=DateOfJoining from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0 and Employee_Status=1
	Select @isWFH=isWFH,@IsProrataRequired=IsProrataRequired,@IsDocProofRequired =IsDocProofRequired from TA_Tbl_LeaveType where LeaveType_Id=@LeaveType_Id
	if(@LeaveType_Id<>-1)
	begin
		select @LeaveApplicationCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
		where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id 
		and la.Employee_Id=@Employee_Id and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
		and la.status not in('Rejected') and la.isdeleted=0 and la.IsBorrow=0
		select @LOPCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
		where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id 
		and la.Employee_Id=@Employee_Id and la.Type in ('LOP') 
		and la.status not in('Rejected') and la.isdeleted=0 and la.IsBorrow=0
		if(@YearSettingId = @CurrentyearSettingId)
		begin
			if(@LeaveApplicationCount > 0)
			begin
				Select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeavesCurrentYear,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed,
				case when(CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										end *LPD.MaxDays_Month
						end			
					else
						case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										end *LPD.MaxDays_Month
						end
			end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											end *LPD.MaxDays_Month
							end			
						else
							case when LPD.No_Of_Days<=(
							case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
							end) then LPD.No_Of_Days 
							else    case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
											when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
															else DATEDIFF(month,@DateofJoining,getdate())+1
													 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
											else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
									end
							end	
				end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end 
				RemainingNoOfLeaves	,isnull(@isWFH,0) as isWFH,IsProrataRequired=isnull(@IsProrataRequired,1),IsDocProofRequired=isnull(@IsDocProofRequired,0)
				from TA_tbl_Yearclosure yc
				inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId and yc.employee_Id=la.Employee_id and la.YearSettings_Id=ys.YearSettings_Id
				inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
				inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId  and LPD.LeaveType_Id=yc.LeaveTypeID)
				left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
				where yc.employee_Id=@Employee_Id and LPD.LeaveType_Id=@LeaveType_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 and la.Status in ('Pending','Forwarded','Approved') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and la.IsBorrow=0 
				Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			end
			else 
			begin
				declare @TempYearSettingsId int
				--print's'
				set @TempYearSettingsId= (select Yearsettings_Id from ta_tbl_yearSetting where Isactive=1)				
				select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) as RemainingNoOfLeavesCurrentYear,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed,
				case when (CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end
					else
						case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,@DateofJoining,getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end					
			end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 			
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end
						else
							case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end					
				end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end RemainingNoOfLeaves,isnull(@isWFH,0) as isWFH,IsProrataRequired=isnull(@IsProrataRequired,1),IsDocProofRequired=isnull(@IsDocProofRequired,0)
				from TA_tbl_Yearclosure yc
				inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
				inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
				inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId  and LPD.LeaveType_Id=yc.LeaveTypeID)
				left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
				where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId				
				Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			end
		end
		else if(@YearSettingId=@SuccessiveYearSettingId)
		begin	
			select top 1 @MaxapplicableDays=MaxDays_applicable from ta_tbl_leavepolicydetails where policy_Id=(select top 1 Leavepolicy_Id from ta_tbl_emp_leavepolicy where EmployeeId=@Employee_Id and LeaveType_Id=@LeaveType_Id order by ta_tbl_emp_leavepolicy.ToDate desc)
			select @SuccesiveLeavepolicyCount=sum(NumberofDays) from ta_tbl_LeaveApplication where YearSettings_Id=@YearSettingId and Isdeleted=0 and status <> 'Rejected' and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
			and Employee_Id=@Employee_Id and LeaveType_Id=@LeaveType_Id
			if @SuccesiveLeavepolicyCount is null
			begin
				set @SuccesiveLeavepolicyCount=0.0
			end	
			select @MaxapplicableDays - @SuccesiveLeavepolicyCount as RemainingNoOfLeaves,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed
		end
	end
	else
	begin
		if(@YearSettingId = @CurrentyearSettingId)
		begin
			Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as 'Number of Days / year',
			case when(CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										end *LPD.MaxDays_Month
						end			
					else
						case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										end *LPD.MaxDays_Month
						end
			end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											end *LPD.MaxDays_Month
							end			
						else
							case when LPD.No_Of_Days<=(
							case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
							end) then LPD.No_Of_Days 
							else    case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
											when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
															else DATEDIFF(month,@DateofJoining,getdate())+1
													 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
											else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
									end
							end
				end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end 
			as 'Number of Days'
			from TA_tbl_Yearclosure yc
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
			inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId and LPD.LeaveType_Id=lt.LeaveType_Id)
			left outer join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lt.LeaveType_Id and la.YearSettings_Id=ys.YearSettings_Id
			left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
			where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 
			and la.Status in ('Pending','Forwarded','Approved') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
			and la.IsBorrow=0 
			Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			union
			Select lt.LeaveType as 'Leave Type',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as 'Number of Days / year',
			case when (CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end
					else
						case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,@DateofJoining,getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end					
			end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 			
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end
						else
							case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end					
				end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end
			as 'Number of Days'
			from TA_tbl_Yearclosure yc
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
			inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId and LPD.LeaveType_Id=lt.LeaveType_Id)
			left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
			where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (
			select LeaveType_Id from Ta_Tbl_LeaveApplication la
			inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id
			where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
			and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and Status not in ('Rejected') and ys.IsActive=1)
			and ys.YearSettings_Id=@YearSettingId
		end
		else if (@YearSettingId=@SuccessiveYearSettingId)
		begin	
			Select lt.LeaveType as 'Leave Type',(ISNULL(LPD.MaxDays_Applicable,0.0))
			- (ISNULL(sum(la.NumberOfDays),0.0)) as 'Number of Days / year',LPD.MaxDays_Month,
			case when (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month- (ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
			else (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month- (ISNULL(sum(la.NumberOfDays),0.0)) 
			end as 'Number of Days'
			from ta_tbl_leavepolicydetails LPD
			inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=@CurrentyearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=LPD.LeaveType_Id
			left outer join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lt.LeaveType_Id and la.YearSettings_Id=ys.YearSettings_Id
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=elp.EmployeeId and LP.YearSettingId=elp.YearSettingId)			
			where elp.EmployeeId=@Employee_Id 
			and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@CurrentyearSettingId and la.Isdeleted=0 
			and la.Status in ('Pending','Forwarded','Approved') and la.Type not in ('Restricted Holiday','Comp Off','ESI','LOP') 
			and la.IsBorrow=0 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid 
			where TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id and TA_Tbl_YearSetting.IsActive=1 order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			Group by lt.LeaveType_Id,LPD.MaxDays_Applicable,lt.LeaveType,LPD.MaxDays_Month,ys.FromDate
			union
			Select lt.LeaveType as 'Leave Type',(ISNULL(LPD.MaxDays_Applicable,0.0)) as 'Number of Days / year',LPD.MaxDays_Month,
			case when (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month>ELPD.No_Of_Days then ELPD.No_Of_Days else  
			(DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month
			end
			as 'Number of Days'
			from ta_tbl_leavepolicydetails LPD 
			inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=@CurrentyearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=LPD.LeaveType_Id
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=elp.EmployeeId and LP.YearSettingId=elp.YearSettingId)
			inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on 
			(LP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId and ELPD.LeaveType_Id=lt.LeaveType_Id and ELPD.EmpID=LP.EmployeeId)
			where elp.EmployeeId=@Employee_Id and LPD.Leavetype_Id not in(
			select LeaveType_Id from Ta_Tbl_LeaveApplication la
			where la.Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
			and Type not in ('Restricted Holiday','Comp Off','ESI','LOP') and Status not in ('Rejected')and la.YearSettings_Id=@CurrentyearSettingId)
			and ys.YearSettings_Id=@CurrentyearSettingId
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid 
			where TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id and TA_Tbl_YearSetting.IsActive=1 order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		end
	end
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReminderEmailSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReminderEmailSchedule]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT ES.*,ESR.* FROM Ta_Tbl_EmailScheduleReminder ESR
	inner join TA_Tbl_EmailSchedule ES on ESR.ScheduledID=ES.ScheduleId
	WHERE convert(varchar(11),ReminderDate)=convert(varchar(11),GETDATE()) and ESR.status=0
	and Reminder_afterDays!=0 and es.ReportId not in(248,249)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportsForEmailSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:   <Description,,>
-- Modified By   : Thilakraj C
-- Modified date : 25-Feb-2013
-- Description   : make a Inner Join with TA_Tbl_Usergroup table.
-- [Proc_TA_GetReportsForEmailSchedule] 'Superadmin'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReportsForEmailSchedule]  
(
	@UserGroupName varchar(250)
)
AS
BEGIN
   SET NOCOUNT ON;
    -- Insert statements for procedure here
   select P.pageId,case when P.pageId IN(180,183,160) then P.displayName+''+'_Title' else P.displayName end displayName,'../' + P.path as path
   ,case	when P.pageId=183	then	1		when P.pageId=41	then 2	when P.pageId=118	then 3	when P.pageId=40	then 4
					when P.pageId=180 then	5		when P.pageId=105 then 6	when P.pageId=30	then 7	when P.pageId=160 then 9					
					when P.pageId=175 then	8		when P.pageId=34	then 11	when P.pageId=37	then 10	when P.pageId=35	then 12
					when P.pageId=92	then	13	when P.pageId=39	then 14	when P.pageId=36	then 15	when P.pageId=89	then 16
					when P.pageId=127 then	17	when P.pageId=33	then 18	when P.pageId=32	then 19
				end
   from TA_Tbl_Page P
   Inner join TA_Tbl_Usergroup UG on UG.groupName=@UserGroupName
   inner join TA_Tbl_userRights UR on UR.groupId=UG.groupId and UR.pageId=P.pageId   
   where P.pageId in (30,32,33,34,35,36,37,39,40,41,89,92,105,118,127,160,175,180,183)
   and UG.groupName=@UserGroupName and UR.viewPrv=1
   union all
   select '248','Leave Approval','../Transactions/TA_UI_Transaction_Sanctions.aspx',25
   union all
   select '249','Onduty Approval','../Transactions/TA_UI_Transaction_Sanctions.aspx',26
   order by 4
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportsForWhatsAppSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_GetReportsForWhatsAppSchedule] 'Superadmin'

-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReportsForWhatsAppSchedule] 
	-- Add the parameters for the stored procedure here
(
	@UserGroupName varchar(250)
)
AS
BEGIN
   SET NOCOUNT ON;
    -- Insert statements for procedure here
   select P.pageId,case when P.pageId IN(180,183,160) then P.displayName+''+'_Title' else P.displayName end displayName,'../' + P.path as path
   ,case	when P.pageId=183	then	1		when P.pageId=41	then 2	when P.pageId=118	then 3	when P.pageId=40	then 4
					when P.pageId=180 then	5		when P.pageId=105 then 6	when P.pageId=30	then 7	when P.pageId=160 then 9					
					when P.pageId=175 then	8		when P.pageId=34	then 11	when P.pageId=37	then 10	when P.pageId=35	then 12
					when P.pageId=92	then	13	when P.pageId=39	then 14	when P.pageId=36	then 15	when P.pageId=89	then 16
					when P.pageId=127 then	17	when P.pageId=33	then 18	when P.pageId=32	then 19
				end
   from TA_Tbl_Page P
   Inner join TA_Tbl_Usergroup UG on UG.groupName=@UserGroupName
   inner join TA_Tbl_userRights UR on UR.groupId=UG.groupId and UR.pageId=P.pageId   
   where P.pageId in (34,37)
   and UG.groupName=@UserGroupName and UR.viewPrv=1
   order by 4
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportToAndSanctionAuthority]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE Proc [dbo].[Proc_TA_GetReportToAndSanctionAuthority]
(
    @Employee_Code_Id nVarchar(25)
)
AS
SELECT Reporting_To,Leave_Sanc_Authority FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidayCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	27-Dec-2013
Descriptions	:	Added this conditon while taking from process data table
 Proc_TA_GetRestrictedHolidayCount 27
 */
CREATE   Procedure [dbo].[Proc_TA_GetRestrictedHolidayCount]         
(          
	@Holiday_Id int          
)
As	
BEGIN
	DECLARE @Count INT
	DECLARE @Count1 INT
	Select @Count =Count(LeaveType_id) from ta_tbl_Leaveapplication la inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id
	where ys.IsActive=1 and la.LeaveType_id=@Holiday_Id  AND la.Isdeleted=0 AND la.Type='Restricted Holiday' and la.Status <> 'Rejected'
	SELECT @Count1= COUNT(P.Process_Rec_Id) FROM TA_Tbl_ProcessedData P
	inner join TA_Tbl_Holiday H on 1=1 WHERE H.Holiday_Id = @Holiday_Id AND P.ProcessFlag = 1 AND P.Date BETWEEN H.Holiday_FromDate AND H.Holiday_ToDate and P.Date<GETDATE()
	SELECT  isnull(@Count,0) +isnull(@Count1,0) AS RestrictedHolidayCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  Procedure [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]         
As
BEGIN          
	SET NOCOUNT ON;
	select count(isnull(la.NumberOfDays,0)) as RHCount from ta_tbl_Leaveapplication la
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
	where ys.IsActive=1 and la.Type='Restricted Holiday' and la.Isdeleted=0 and la.Status <> 'Rejected' 
	Group by la.Employee_Id  
	--order by count(la.Employee_Id) desc        
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRouteCountFromEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Procedure [dbo].[Proc_TA_GetRouteCountFromEmployee]         
(          
 @RouteId int          
)           
As          
DECLARE @Isdel INT          
SET @Isdel=0       
BEGIN          
   Select Count(bus_id)as RouteCount from ta_tbl_employee          
   where bus_id=@RouteId  AND Isdeleted=@Isdel           
END   
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPage]
AS
BEGIN
	select * from Ta_tbl_PageRedirect where Active=1 order by ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPageStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPageStandard]
AS
BEGIN
	select * from Ta_tbl_PageRedirectStandard where Active=1 order by ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountInPage]
	@PageId as int
AS
BEGIN
	select Rows from Ta_tbl_PageRedirect where PageId=@PageId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPageStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountInPageStandard]
	@PageId as int
AS
BEGIN
	select Rows from Ta_tbl_PageRedirectStandard where PageId=@PageId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSanctionUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 25-05--2017
-- Description:	Get My calendar Data
-- Proc_TA_GetSanctionUser 359
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSanctionUser]
	-- Add the parameters for the stored procedure here
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
	select distinct EmpAutoId from #EmployeeIds  where EmpAutoId not in (@EmployeeID)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSaturday_WorkHrs]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Proc_TA_GetSaturday_WorkHrs 62
Created By		: Manjula.P
Created Date	: 27-May-2013
Descriptions	: For getting saturday work hours per employee for gussing employee category
*/
CREATE proc [dbo].[Proc_TA_GetSaturday_WorkHrs]
(
 @EmployeeId int=0
)
as
begin
select Sat_WorkHrs from TA_Tbl_Employee E 
inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id
inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
where Employee_Id=@EmployeeId
order by EC.EffectiveDate  desc
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetScheduleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_GetScheduleDetails 1,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_GetScheduleDetails]	
(
 @EmployeeId int,
 @UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	if(@UserGroupName = 'SuperAdmin')
	BEGIN
		select ES.ScheduleId,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + ' ' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then 'Enabled' else 'Disabled' end as Enabled,TimeToSend
		from TA_tbl_EmailSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Isdeleted=0 and E.Employee_Status=1 and ES.IsDeleted=0
		order by ScheduleId
	END
	else
	BEGIN
		select ES.ScheduleId,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + ' ' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then 'Enabled' else 'Disabled' end as Enabled,TimeToSend
		from TA_tbl_EmailSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Employee_Id = @EmployeeId and ES.IsDeleted=0
		order by ScheduleId
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftByWeekDayId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	30-Dec-2013
Descriptions	:	Adding this procedure for selecting the tempweekday shifts values
Proc_TA_getShiftByWeekDayId 34
*/
CREATE proc [dbo].[Proc_TA_getShiftByWeekDayId]
(
@TempWeekDayId int
)
as
begin
	create table #temp(ShiftId nvarchar(max))
	declare  @TableShiftId nvarchar(max)
	set @TableShiftId=(SELECT TWD.ShiftId FROM TA_Tbl_TemWeekday TWD	
	WHERE TempWeekday_Id=@TempWeekDayId)
	insert into #temp
	select value from Split((Select * from (select @TableShiftId as ShiftId) A), ',')
	select * from #temp 
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetails_Blocking_Unblocking]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Get the Shift Details for Blocking and Unblocking the card of the employee for the current date>
-- Proc_TA_GetShiftDetails_Blocking_Unblocking 'UB'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftDetails_Blocking_Unblocking]
	@flag char(2)
AS
BEGIN	
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @AllowedMaxMin_AfterShiftEnd int
    set @AllowedMaxMin_AfterShiftEnd=0
    select @AllowedMaxMin_AfterShiftEnd=Daily_Hrs from Ta_tbl_PolicyConfiguration 
    Declare @AllowedMinMin_BeforeShiftStart int
    set @AllowedMinMin_BeforeShiftStart=60
	IF(@flag='B')
	BEGIN
		select currentDateandTime=getdate(),After4hrs30Minutes= CONVERT(varchar(11),getdate())+ DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,Shift_EndTime),
		isLesser=case when getdate()<=DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,Shift_EndTime) then 1 else 0 end,
		NightShift=case when RIGHT(Shift_StartTime,2)='PM' and RIGHT(Shift_EndTime,2)='AM' then 'Yes' else 'No' end,
		Shift_Id from TA_Tbl_Shift where CONVERT(varchar(11),getdate())+ DATEADD(minute,@AllowedMaxMin_AfterShiftEnd,Shift_EndTime)<=GETDATE()
	END
	else if(@flag='UB')
	begin
		select currentDateandTime=getdate(),After1hr= CONVERT(varchar(11),getdate())+ DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,Shift_StartTime),
		isLesser=case when getdate()<=DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,Shift_StartTime) then 1 else 0 end,
		NightShift=case when RIGHT(Shift_StartTime,2)='PM' and RIGHT(Shift_EndTime,2)='AM' then 'Yes' else 'No' end,
		Shift_Id from TA_Tbl_Shift
		where CONVERT(varchar(11),getdate())+ DATEADD(minute,-@AllowedMinMin_BeforeShiftStart,Shift_StartTime)<=GETDATE()
		union all
		select '','',0,'No',-1
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- select * from ta_tbl_leveldetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation] 
	@LevelID int = 37
AS
Begin
	Declare @parentID int
	
	;WITH ChildLevelDetails as
	(
		SELECT id,parentid from Ta_Tbl_levelDetails LD where id=@LevelID
		UNION ALL
		SELECT ld.id,ld.parentId  from Ta_Tbl_levelDetails LD 
		INNER JOIN ChildLevelDetails CL ON LD.id=CL.parentId			
	)
	select @parentID=isnull(id,0) from ChildLevelDetails where parentId=0
	select @LevelID=@parentID;
	DECLARE @timeformat   varchar(10)
	SELECT @timeformat=TimeFormat FROM TA_Tbl_DateandTimeFormat	
	if(@timeformat='hh:mm tt')
		begin
			select 0 Shift_Id,'-Select-' Shift_Name,'-Select-' Shift_ShortName
			union
			SELECT Shift_Id,Shift_Name,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName 
				from TA_Tbl_Shift
			where isdeleted=0 and level_id=@LevelID and ShiftType = 0
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName
			from TA_Tbl_Shift where isdeleted=0 and level_id=0 and ShiftType = 0
		end
	else
		begin
			select 0 Shift_Id,'-Select' Shift_Name,'-Select-' Shift_ShortName
			union
			SELECT Shift_Id,Shift_Name,Shift_ShortName + ' ( ' + convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName 
			from TA_Tbl_Shift where  isdeleted=0 and level_id=@LevelID and ShiftType = 0
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' + convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName
			from TA_Tbl_Shift where  isdeleted=0 and level_id=0 and ShiftType = 0
		end
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Shift Details of all companies>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT	Shift_Id, Level_Id, Shift_Name, Shift_ShortName, Shift_Description, Shift_StartTime, Shift_EndTime, Shift_FirstHalf_StartTime, Shift_FirstHalf_EndTime, 
	Shift_SecondHalf_StartTime, Shift_SecondHalf_EndTime, Shift_GraceInTime, Shift_GraceOutTime, Shift_BreakStartTime1, Shift_BreakEndTime1, Shift_BreakStartTime2, 
	Shift_BreakEndTime2, Shift_BreakStartTime3, Shift_BreakEndTime3, Shift_MinTimeOT, Shift_MaxTimeOT, Shift_WorkingDay_OverTime, Shift_TotalWorkingHours, 
	Shift_LunchOutTimeGrace, Shift_LunchInTimeGrace, Shift_LunchOutTimeGraceBefore, Shift_LunchOutTimeGraceAfter, Shift_LunchInTimeGraceBefore, 
	Shift_LunchInTimeGraceAfter, Shift_LunchOutTimeGraceBeforeChk, Shift_LunchOutTimeGraceAfterChk, Shift_LunchInTimeGraceBeforeChk, Shift_LunchInTimeGraceAfterChk, 
	Isdeleted, Emp_ID, Shift_FirstHalfWorkingHours, Shift_SecondHalfWorkingHours, IsBreakDeducted, DefaultShift, ShiftType, CreatedDate, ModifiedDate, [24HrsShift]	
	,MaxShiftWorkHours as MaxExtraShiftWorkHours
	FROM TA_Tbl_Shift WHERE IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftExchangeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_GetShiftExchangeDetails  
Description : To get the Shift Exchange Employee Details
Tables Included : TA_Tbl_Employee,Ta_Tbl_ShiftExchange,ta_tbl_shift
Created By : Sasireka  
Created On : 13-Jan-2009 
Modified By :  
Modified On :  
*/  
--exec [Proc_TA_GetShiftExchangeDetails] 'S',' ',' ','Super Admin','1','1,47,136,145,146,147,151,152,153,154,1,137,138,2,3,140,47,113,132,133,134,135,150,155,159,160,161,162'
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftExchangeDetails]
@Employee_ID int,
@mode char(1),
@fromdate datetime,
@todate datetime,
@UserGroupName varchar(250), 
@GradeLevel varchar(1000), 
@LevelRights varchar(8000),
@ParentId int 
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
declare @sql as varchar(8000)
set @sql=''
BEGIN
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	IF(@mode = 'A')
	BEGIN
		SET @sql ='select 
		case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, ta_tbl_shiftExchange.Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, ta_tbl_shiftExchange.Date, '+cast(@dateFormat as varchar(100))+') end	as date ,
		e1.Employee_Code_Id + '' - '' + e1.employee_Firstname + '' '' + e1.Employee_LastName as Employee1Name, '
		SET @sql = @sql + ' isnull(s1.shift_Shortname,''Weekly Off'') as ShiftName1 ,e2.Employee_Code_Id + '' - '' + e2.employee_Firstname +  '' '' + e2.Employee_LastName  as Employee2Name,isnull(s2.Shift_ShortName,''Weekly Off'') as ShiftName2 ,ld.name as LevelName'
		SET @sql = @sql + ' from ta_tbl_shiftExchange '
		set @sql = @sql + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=ta_tbl_shiftExchange.YearSettings_Id '
		SET @sql = @sql + ' inner join ta_tbl_LevelDetails ld on ta_tbl_shiftexchange.Level_Id=ld.id '
		SET @sql = @sql + ' inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id '
		SET @sql = @sql + ' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id '
		SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel el1 ON e1.Employee_Id = el1.EmployeeId '
		SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel el2 ON e2.Employee_Id = el2.EmployeeId '
		SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation edes1 ON e1.Employee_Id = edes1.EmployeeId '
		SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation edes2 ON e2.Employee_Id = edes2.EmployeeId '	
		SET @sql = @sql + ' INNER JOIN TA_Tbl_Title tit1 ON tit1.TitleId=edes1.DesignationId '
		SET @sql = @sql + ' INNER JOIN TA_Tbl_Title tit2 ON tit2.TitleId=edes2.DesignationId ' 
		SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade grd1 ON grd1.Grade_ID = tit1.GradeId ' 
		SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade grd2 ON grd2.Grade_ID = tit2.GradeId '
		SET @sql = @sql + ' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift '
		SET @sql = @sql + ' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift '
		SET @sql = @sql + ' INNER JOIN #LevelRights LR1 ON LR1.LevelId = el1.LevelId ' 
		SET @sql = @sql + ' INNER JOIN #LevelRights LR2 ON LR2.LevelId = el2.LevelId '
		SET @sql = @sql + ' where ys.IsActive=1 '
		if(@UserGroupName<>'SuperAdmin')
			begin
				SET @sql = @sql + ' AND grd1.Grade_Level>=' + @GradeLevel + ''
				SET @sql = @sql + ' AND grd2.Grade_Level>=' + @GradeLevel + ''
			end
		if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (e1.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		SET @sql = @sql + ' And el1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
		SET @sql = @sql + ' And el2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
		SET @sql = @sql + ' And edes1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
		SET @sql = @sql + ' And edes2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
		exec (@sql)
	END
	IF(@mode = 'S')
		BEGIN
			SET @sql ='select case when '+cast(@dateFormat as varchar(100))+'=106 then
			REPLACE(CONVERT(VARCHAR, ta_tbl_shiftExchange.Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
			else CONVERT(VARCHAR, ta_tbl_shiftExchange.Date, '+cast(@dateFormat as varchar(100))+') end as date		
			 ,e1.Employee_Code_Id + '' - '' + e1.employee_Firstname as Employee1Name, '
			SET @sql = @sql + ' isnull(s1.shift_Shortname,''Weekly Off'') as ShiftName1,e2.Employee_Code_Id + '' - '' + e2.employee_Firstname as Employee2Name,isnull(s2.Shift_ShortName,''Weekly Off'') as ShiftName2 ,ld.name as LevelName '
			SET @sql = @sql + ' from ta_tbl_shiftExchange '
			set @sql = @sql + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=ta_tbl_shiftExchange.YearSettings_Id '
			SET @sql = @sql + ' inner join ta_tbl_LevelDetails ld on ta_tbl_shiftexchange.Level_Id=ld.id '
			SET @sql = @sql + ' inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id '
			SET @sql = @sql + ' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id '
			SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel el1 ON e1.Employee_Id = el1.EmployeeId '
			SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel el2 ON e2.Employee_Id = el2.EmployeeId '
			SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation edes1 ON e1.Employee_Id = edes1.EmployeeId '
			SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation edes2 ON e2.Employee_Id = edes2.EmployeeId '	
			SET @sql = @sql + ' INNER JOIN TA_Tbl_Title tit1 ON tit1.TitleId=edes1.DesignationId '
			SET @sql = @sql + ' INNER JOIN TA_Tbl_Title tit2 ON tit2.TitleId=edes2.DesignationId ' 
			SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade grd1 ON grd1.Grade_ID = tit1.GradeId ' 
			SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade grd2 ON grd2.Grade_ID = tit2.GradeId '
			SET @sql = @sql + ' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift '
			SET @sql = @sql + ' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift '
			SET @sql = @sql + ' INNER JOIN #LevelRights LR1 ON LR1.LevelId = el1.LevelId ' 
			SET @sql = @sql + ' INNER JOIN #LevelRights LR2 ON LR2.LevelId = el2.LevelId '
			SET @sql = @sql + ' where ys.IsActive=1 and (ta_tbl_shiftExchange.Date >= CONVERT(DATETIME,''' + cast(@fromdate as varchar(20)) + ''', 102))  and '
			SET @sql = @sql + ' (ta_tbl_shiftExchange.Date <= CONVERT(DATETIME,''' + cast(@todate as varchar(20)) + ''',102)) '
			if(@UserGroupName<>'SuperAdmin')
				begin
					SET @sql = @sql + ' AND grd1.Grade_Level>=' + @GradeLevel + ''			
					SET @sql = @sql + ' AND grd2.Grade_Level>=' + @GradeLevel + ''
				end
			if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (e1.Employee_ID IN (select * from #EmployeeIds)) '  
            END
			SET @sql = @sql + ' And el1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
			SET @sql = @sql + ' And el2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
			SET @sql = @sql + ' And edes1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
			SET @sql = @sql + ' And edes2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
			exec (@sql)
			drop table #LevelRights
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetShiftId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GetShiftId] 4,'06/14/2020',787,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetShiftId]
	-- Add the parameters for the stored procedure here
	@EmployeeAutoId int, 
	@ShiftDate datetime, 
	@Employee_Code_Id varchar(50),
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	set @ShiftId=1
	CREATE Table #Temp (ShiftId INT)
	Declare @Date int
	Declare @year int
	declare @month int
	set @Date=datepart(d,@shiftDate)
	set @month=datepart(M,@shiftDate)
	set @year=datepart(y,@shiftDate)
	--select @date 
	-- Check Shift in Temporary Shift Allocation
	SET @query = 'SELECT (tsa.Day'+ CONVERT(varchar(10),@date) + 'Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa 
				where tsa.[Year]= ' + CONVERT(varchar(10),@year) + '  and  tsa.[Month]= ' + CONVERT(varchar(10),@month) + ' and   
				tsa.EmployeeId = '+ CONVERT(varchar(10),@EmployeeAutoId) +''  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)	
	--DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = 'SELECT (psa.Day'+ CONVERT(varchar(10),@date) + 'Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa
			
			where psa.[Year]= ' + CONVERT(varchar(10),@year) + '  and  psa.[Month]= ' + CONVERT(varchar(10),@month) + ' and   
			psa.EmployeeId = '+ CONVERT(varchar(10),@EmployeeAutoId) +''  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	
	IF(@ShiftId = -2 OR @ShiftId = 0 or @ShiftId='')
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0 and Level_Id=@CompanyId)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName ='Nos' AND IsDeleted = 0)
				END
		END	
	Select @ShiftId
	DROP Table #Temp	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetShiftIdBeforeAfterWeekOff 
Description		:	Get ShiftId for a Given From Date
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By		:	Prabakaran
Created On		:	15-Aug-07
Modified By		:
Modified On		:
[Proc_TA_GetShiftIdBeforeAfterWeekOff] 104,'02/16/2011','02/16/2011','A'
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]
@EMPLOYEEID INT,
@FROMDATE DATETIME,
@TODATE DATETIME,
@TYPE VARCHAR(10)
as
BEGIN
	DECLARE @SEARCHDATE AS DATETIME
	DECLARE @QUERY AS VARCHAR(3000)
	DECLARE @TEMPSHIFTID AS INT
	CREATE TABLE #TEMP(SHIFTTEMP INT)
	CREATE TABLE #TEMP1(SHIFTTEMP INT)
	IF @TYPE='A'
		BEGIN
			SET @SEARCHDATE=DATEADD(DAY,-1,@FROMDATE)
		END
	ELSE IF @TYPE='B'
		BEGIN
			SET @SEARCHDATE=DATEADD(DAY,1,@TODATE)
		END
	SET @QUERY = ('SELECT DAY' + CAST(DAY(@SEARCHDATE) AS VARCHAR(25)) + 'SHIFT FROM  TA_TBL_TEMPORARYSHIFTALLOCATION WHERE YEAR = YEAR(''' + CAST(@SEARCHDATE AS VARCHAR(25)) + ''') AND MONTH = MONTH('''+ CAST(@SEARCHDATE AS VARCHAR(25)) +''') AND EMPLOYEEID =' + CAST(@EMPLOYEEID AS VARCHAR(20)))
	INSERT INTO #TEMP EXEC(@QUERY)
	SELECT @TEMPSHIFTID=SHIFTTEMP FROM #TEMP
	DELETE FROM #TEMP
	IF @TEMPSHIFTID=-1 OR @TEMPSHIFTID>0
		BEGIN
			SELECT @TEMPSHIFTID AS SHIFTID
		END
	ELSE IF @TEMPSHIFTID=0 OR @TEMPSHIFTID IS NULL
		BEGIN
			SET @QUERY = ('SELECT DAY' + CAST(DAY(@SEARCHDATE) AS VARCHAR(25)) + 'SHIFT FROM  TA_TBL_PERMANENTSHIFTALLOCATION WHERE YEAR = YEAR(''' + CAST(@SEARCHDATE AS VARCHAR(25)) + ''') AND MONTH = MONTH('''+ CAST(@SEARCHDATE AS VARCHAR(25)) +''') AND EMPLOYEEID =' + CAST(@EMPLOYEEID AS VARCHAR(20)))
			INSERT INTO #TEMP EXEC(@QUERY)
			SELECT @TEMPSHIFTID=SHIFTTEMP FROM #TEMP
			DELETE FROM #TEMP
			IF(@TEMPSHIFTID='' OR @TEMPSHIFTID IS NULL)
			BEGIN
				SELECT @TEMPSHIFTID=SHIFT_ID FROM TA_TBL_SHIFT WHERE SHIFT_NAME='NO SHIFT'
			END
			SELECT @TEMPSHIFTID AS SHIFTID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_GetShiftIdBeforeWeekOff
Description	:	Get ShiftId for a Given From Date
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By	:	Prabakaran
Created On	:	15-Aug-07
Modified By	:
Modified On	:
Proc_TA_GetShiftIdBeforeWeekOff 104,'02/16/2011'
select Employee_Id from TA_tbl_Employee
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]
@EmployeeId int,
@FromDate datetime
as
begin
	declare @SearchDate as datetime
	declare @query as Varchar(3000)
	Declare @TempShiftId as int
	create table #Temp(ShiftTemp int)
	create table #Temp1(ShiftTemp int)
	set @SearchDate=DateAdd(day,-1,@FromDate)
	set @query = ('select Day' + Cast(Day(@SearchDate) as Varchar(25)) + 'Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year(''' + cast(@SearchDate as Varchar(25)) + ''') and Month = month('''+ cast(@SearchDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
	insert into #Temp EXEC(@query)
	set @TempShiftId=(select * from #Temp)
	drop table #Temp
	if @TempShiftId=-1 or @TempShiftId>0
	begin
	select @TempShiftId as ShiftId
	end
	else if @TempShiftId=0 or @TempShiftId is null
	begin
	set @query = ('select Day' + Cast(Day(@SearchDate) as Varchar(25)) + 'Shift from  TA_Tbl_PermanentShiftAllocation where Year = year(''' + cast(@SearchDate as Varchar(25)) + ''') and Month = month('''+ cast(@SearchDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
	insert into #Temp1 EXEC(@query)
	set @TempShiftId=(select * from #Temp1)
	drop table #Temp1
	if(@TempShiftId='' or @TempShiftId is null)
	BEGIN
	set @TempShiftId=(select Shift_Id from TA_tbl_shift where Shift_Name='No Shift')
	END
	select @TempShiftId as ShiftId
	end
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIDForParticularDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11:00 AM>
-- Description:	<Get Shift ID For Particular Date>
--Proc_TA_GetShiftIDForParticularDate '124','2019-07-08 00:00:00.000',1,'08:30:20'
--Proc_TA_GetShiftIDForParticularDate '788','2019-07-08 00:00:00.000',1,'11:47:20'
--Proc_TA_GetShiftIDForParticularDate '8967661','2019-08-14 00:00:00.000',25,'22:30:20'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftIDForParticularDate]
	@Clk_EmpId VARCHAR(50),
	@DATE datetime,
	@COMPANYID INT
	,@Clk_time VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;	
	
	DECLARE @QUERY VARCHAR(2000)   
	DECLARE @SHIFTID INT
	SET @SHIFTID=0
	DECLARE @ISDELETED INT
	CREATE TABLE #TEMP (SHIFTID INT)	
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)
	SET @YEAR=DATEPART(YEAR,@DATE)
	SET @MONTH=DATEPART(MONTH,@DATE)
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	SELECT  @EMPLOYEEAUTOID =Employee_Id FROM TA_Tbl_Employee WHERE SwipeCardNo=@Clk_EmpId and Isdeleted=0
	-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	SET @QUERY = '	SELECT (TSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
					WHERE TSA.[YEAR]= ' + @YEAR + '  AND  TSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = '''+ @EMPLOYEEAUTOID +''' '	
	INSERT INTO #TEMP EXEC(@QUERY)
	SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
	SET @SHIFTID = ISNULL(@SHIFTID,0) 
	DELETE FROM #TEMP
	-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	IF(@SHIFTID = 0)
		BEGIN
			SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)			
			DELETE FROM #TEMP
		END
	IF(@SHIFTID != 0)
		BEGIN			
			IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
				BEGIN
					SET @SHIFTID = ISNULL(@SHIFTID,0)	
						--print @SHIFTID
				END
		END
	--To check current date is weekly off as per the configuration in the shift settings
	--implemented on 08-July-2022 11:14 pm by Manikandan.rr
	IF(@SHIFTID = 0)
	BEGIN		
		IF EXISTS(select WeekOffDay from dbo.Fn_CheckCurrentDayIsWeeklyOff(@COMPANYID) where WeekOffDay=DATENAME(DW,@DATE))
		BEGIN
			SET @SHIFTID = -1
		END
	END	
	-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	IF(@SHIFTID = 0)
		BEGIN
			SET @SHIFTID = (SELECT Shift_Id FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)
			IF(@SHIFTID = 0)
				BEGIN					
					SET @SHIFTID = (SELECT SHIFT_ID FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
							--print @SHIFTID
				END
		END
	IF(@SHIFTID > 0)
		BEGIN
			SELECT ISNULL(SHIFT_ID,0)AS SHIFTID FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
		END
	ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID AS SHIFTID
		END		
	DROP TABLE #TEMP	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdForWeekOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name		:	Proc_TA_GetShiftIdForWeekOff 
Description		:	Get ShiftId for a Given From Date
Tables Included		:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By		:	Prabakaran
Created On		:	02-Dec-08
Modified By		:
Modified On		:
[Proc_TA_GetShiftIdForWeekOff] 157,'08/25/2008','08/25/2008','A'
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetShiftIdForWeekOff]
@EmployeeId int,
@SearchDate datetime
as
Begin
	declare @query as Varchar(3000)
	Declare @TempShiftId as int
	create table #Temp(ShiftTemp int)
	create table #Temp1(ShiftTemp int)
	set @query = ('select Day' + Cast(Day(@SearchDate) as Varchar(25)) + 'Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year(''' + cast(@SearchDate as Varchar(25)) + ''') and Month = month('''+ cast(@SearchDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
	insert into #Temp EXEC(@query)
	set @TempShiftId=(select * from #Temp)
	drop table #Temp
	if @TempShiftId=-1 or @TempShiftId>0
	begin
	select @TempShiftId as ShiftId
	end
	else if @TempShiftId=0 or @TempShiftId is null
	begin
	set @query = ('select Day' + Cast(Day(@SearchDate) as Varchar(25)) + 'Shift from  TA_Tbl_PermanentShiftAllocation where Year = year(''' + cast(@SearchDate as Varchar(25)) + ''') and Month = month('''+ cast(@SearchDate as varchar(25)) +''') and EmployeeId =' + cast(@EmployeeId as varchar(20)))
	insert into #Temp1 EXEC(@query)
	set @TempShiftId=(select * from #Temp1)
	select @TempShiftId as ShiftId
	drop table #Temp1
	end	
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
	Created By		:	A.K.T.MOORTHI
	Created Date	:	17-Dec-2013
	Description		:	Get The Shift Roster Details
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetails]
	@UserGroupName NVARCHAR(250),	
	@ParentId BIGINT
AS
BEGIN
	CREATE TABLE #LevelRights(LevelId INT)
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	SELECT
		SR.ShiftRoaster_Id,
		SR.ShiftRoaster_Name,
		SR.NumberOfPatterns,
		LD.name,
		(CASE WHEN SR.IsDeleted = 1 THEN 'True' ELSE 'False' END) IsDeleted
	FROM TA_Tbl_ShiftRoaster SR
		INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id
		INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	17-Dec-2013
-- Description	:	Get The Shift Roster Value By Id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetailsById]
	@ShiftRosterId BIGINT
AS
BEGIN
	SELECT SR.*,LD.name FROM TA_Tbl_ShiftRoaster SR 
		INNER JOIN TA_Tbl_Leveldetails LD ON SR.Level_Id = LD.id  
	WHERE SR.ShiftRoaster_Id = @ShiftRosterId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getShiftSettings] 
AS
BEGIN
	Select * from TA_Tbl_shiftSettings
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- ================================================
-- Author:		Kumuthini
-- Create date: 15-Jan-09
-- Description:	Get the Shift Settings Details by Company Id
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	19-July-2013
-- Description		:	Added Select Query Column.
-- Modified By		:	Manjula.P
-- Modified On		:	18-Jan-2014
-- Descriptions		:	selecting lunch deduction hours columns for shift settings page
-- ================================================
-- Proc_TA_GetShiftSettingsByComId 1
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComId] 
(
	@CompanyId int
)
AS
BEGIN
		SELECT ShiftSettingId,
		CompanyId,
		MaxHoursBeforeShift,
		MaxHoursAfterShift,
		ShiftBreak,
		ShiftMaxBreakHours,
		MonthlyWorkingHours,
		WeeklyWorkingHours,
		EmpID,
		HolidayOT,
		WeekOffOT,
		otOption,
		DefaultMonthClosureDate,
		IsFlexible,
		FlexibleFlag,
		OTRoundoffEnable,
		FullDayAttendanceHrs,
		HalfDayAttendanceHrs,
		HalfDayAttendance,
		FullDayAttendance,
		WeeklyOffStartHours,
		IgnoreDuplicatePunch,
		PunchInterval,
		AfterShiftTime,
		BeforeShiftTime,
		DefinedWorkhrs,
		NoOfSuccessiveDaysInYear,
		CompensationValitityDays,
		VaildityCompOffDays,
		CAST(HalfDayCompOff AS VARCHAR(5)) AS HalfDayCompOff,
		CAST(FullDayCompOff AS VARCHAR(5)) AS FullDayCompOff,
		lateentry,earlyentry,earlyexit,lateexit,
		--Added by MAnjula.P on 18-Jan-2014
		isnull(IsLunchDeduction,0) as IsLunchDeduction, ISNULL(LunchDeductionHours,'00:00') as LunchDeductionHours,
		Flexi_AfterShiftTime,Flexi_BeforeShiftTime,Flexi_DefinedWorkhrs,
		MaxHoursBeforeShift_24HrsShift,
		WeeklyOffStartHours_24HrsShift,
		CumulativeWeekStartDay,
		CumulativeWeekEndDay,
		[DefaultLunchHours],
		[MaxLunchHours],
		[MaxWorkPlaceInHours],Carry_Forward_COff_Year,isRequestingforCompOff,
		isnull(FirstAndLast,0)as FirstAndLast,
		SpecialOverTime1,SpecialOverTime2
		,isnull(LATEMINSPERDAY,0) as LATEMINSPERDAY,isnull(LATEDAYSPERMONTH,0) as LATEDAYSPERMONTH,isnull(EarlyExitMinsPerDay,0) as EarlyExitMinsPerDay, isnull(EarlyExitDaysPerMonth,0) as EarlyExitDaysPerMonth
		,isnull(EnableAbsent,0) as EnableAbsent,
		isLOPDisplayed=isnull(isLOPDisplayed,1),
		reminderDays=isnull(reminderDays,0),isRemindRrd=isnull(isRemindRrd_Pas_Vis,0),
		mon ,tues,wed,thurs,fri,satur,sun
		FROM TA_Tbl_shiftSettings WHERE CompanyId = @CompanyId
		Declare @SuccessiveyearId int
		set @SuccessiveyearId = (select top 1 yearsettings_Id from ta_tbl_yearSetting where yearsettings_id> (select yearsettings_id from ta_tbl_yearSetting where isactive=1) order by yearsettings_id)
		select count(*) as RecordCount from ta_tbl_leaveApplication LA inner join ta_tbl_yearSetting YS on LA.YearSettings_Id=YS.YearSettings_Id 
		where LA.yearsettings_id=@SuccessiveyearId and LA.companyId=@CompanyId and LA.Successiveyear=1 and LA.isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- ================================================
-- Author:		Karthikeyan.R
-- Create date: 03-Apr-2017
-- Description:	Get the Shift Settings Details by Company Id for compoff request
-- Descriptions		:	selecting lunch deduction hours columns for shift settings page
-- ================================================
-- Proc_TA_GetShiftSettingsByComId 1
Create PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff] 
(
	@CompanyId int
)
AS
BEGIN
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@CompanyId
	if(@isRequestCompOff is null or @isRequestCompOff='')
		BEGIN
			select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		END
	select @isRequestCompOff
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	: Proc_TA_GetShiftShortName
Description	: Get Shift Id and Short Name for display in Shift allocation Report
Tables		: TA_Tbl_Shift
Created By	: Prabakaran
Created on	: 3-Aug-07		
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftShortName]
AS
DECLARE @timeformat   varchar(10)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat='hh:mm tt')
		begin
			Select Shift_Id,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName from TA_Tbl_shift
		end
	else
		begin
			Select Shift_Id,Shift_ShortName + ' ( ' +convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName from TA_Tbl_shift
		end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortNameWithOutTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	: Proc_TA_GetShiftShortNameWithOutTime
Description	: Get Shift Id and Short Name for display in Shift allocation Report
Tables		: TA_Tbl_Shift
Created By	: Karthikeyan R
Created on	: 09-Sep-2015
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftShortNameWithOutTime]
AS
Begin
	Select Shift_Id,Shift_ShortName from TA_Tbl_shift
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftUsingID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Karthikeyan.R>
-- Create date: <Create Date,28-Oct-2015>
-- Description:	<Description,Get Shift name based on the terminal ID>
-- Proc_TA_GetShiftUsingID 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftUsingID]
       -- Add the parameters for the stored procedure here
       @ShiftID as int
AS
BEGIN
       SET NOCOUNT ON;
       if @ShiftID!=-1
		   begin
				  select case when Shift_Name='No Shift'  then 'Fales' else 'True' end as Val
				  from TA_Tbl_Shift where Shift_Id=@ShiftID
		   end 
       else
		   begin
				  select 'True' as val
		   end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSLogDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetSMSLogDetails '-select-','2019-08-01','2019-08-05','','Superadmin',0,1,0
-- Proc_TA_GetSMSLogDetails 'Permission Application - Forward','2016-09-30','2016-09-30','Karthikeyan ,','Superadmin',0,1,2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSMSLogDetails]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(100),
	@fromDat DATETIME,
    @ToDat DATETIME,
    @ReceiverId NVARCHAR(max),
    @UserGroupName NVARCHAR(250),
    @GradeLevel NVARCHAR(20),
    @ParentId INT,
    @Status int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	--Get current date time format.
	DECLARE @dateFormat as INT
	DECLARE @date as nVARCHAR(25)             
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
	IF(@date='dd/MM/yyyy')
	BEGIN
		  SET @dateFormat = 103
	END
	ELSE IF(@date='MM/dd/yyyy')
	BEGIN
		  SET @dateFormat = 101
	END
	ELSE
	BEGIN
		  SET @dateFormat = 106
	END      
	--INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@ReceiverId,''
	--INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@ReceiverId,'' 
	--INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@ReceiverId,''
	if(@ReceiverId is not null and @ReceiverId <> '')
	BEGIN
	  CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	  INSERT INTO #EmployeeID
	  SELECT Value from dbo.SplitUpEmployeeName(@ReceiverId,',')
	end
	DECLARE @sqlQuery as NVARCHAR(max)
	SET @sqlQuery = ''
	SET @sqlQuery = @sqlQuery + ' SELECT sl.logid, TemplateID,TemplateName,SL.Message,TriggeredTimings,E.Employee_FirstName as receivers,
	case	when SL.Status=0 then ''Message Not Sent''
			when SL.STatus=1 then ''Message Sent'' end Status  from ta_tbl_smslogdetails SL'
	SET @sqlQuery = @sqlQuery + ' Inner join Ta_Tbl_SMSTemplates ST on SL.TemplateID=ST.ID'
	SET @sqlQuery = @sqlQuery + ' left outer join ta_tbl_employee E on SL.Receivers=E.swipecardNo '
	--SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id '
	--SET @sqlQuery = @sqlQuery + ' INNER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
 --   SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id '
 --   SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
 --   SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID '
 --   SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id '
 --   SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' where 1=1 '
	if(@fromDat!='' and @ToDat!='')
	begin
		 SET @sqlQuery = @sqlQuery + ' And (TriggeredDate >= CONVERT(DATETIME,'''+cast( @fromDat as nVARCHAR(50))+''', 102)) 
      AND (TriggeredDate <= CONVERT(DATETIME,'''+cast(@todat as nVARCHAR(50))+''', 102)) ' 
	end
	if(@ReceiverId is not null and @ReceiverId <> '')
	begin
		SET @sqlQuery = @sqlQuery + ' And SL.Receivers in(select * from #EmployeeID)'
	end
	if(@Status!=2)
	begin
		SET @sqlQuery = @sqlQuery + ' And SL.Status='+CONVERT(char(1),@status)
	end
	if(@TemplateName!='-Select-')
	begin
		Declare @Templateid int
		set @Templateid=(select id from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName)
		SET @sqlQuery = @sqlQuery + ' And SL.TemplateID='+CONVERT(varchar(10),@Templateid)
	end
	print(@sqlQuery)
	Execute(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSTemplateStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <26-09-2016>
-- Description:	<Checking Template Status using Template Name>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSMSTemplateStatus]
	@TemplateName varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Status,ToEmployee from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSubMenus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <26/jul/07>  
-- Description: Getting Left Menu>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_GetSubMenus]
(  
 @parentId int,  
 @groupId int,
 @strType varchar(20)   
)  
AS  
BEGIN  
if(@strType!='Standard')
	BEGIN
		if (@parentId=0)  
			Begin  
				select * from ta_tbl_page where parentID=0 and pageID in (select pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby  
			End  
		Else  
			Begin  
				select * from ta_tbl_page where parentID=@parentId
			End
	END
else
	BEGIN
		if (@parentId=0)  
			Begin  
				select * from ta_tbl_page where parentID=0 
				and pageID not in (20,24,25,69,96,97,98,108,110) 
				and pageID in (select pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby  
			End  
		Else  
			Begin  
				select * from ta_tbl_page where parentID=@parentId 
				and pageID not in (20,24,25,69,96,97,98,108,110)  
				and  pageID in (select pageID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby  
			End		
	END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTaskDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetTaskDetails 100
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetTaskDetails]
@ProjectID bigint
AS
BEGIN
	SET NOCOUNT ON;
	select 'Iffco customization' as Project_Name,'Testing' as TaskList,'16' as definedHours,'' as TaskDescription,'' as SpentHours,'' as TaskName,''as TaskID from TA_Tbl_Project P
	inner join Ta_tbl_TaskProgressDetails TP on P.Project_Id=TP.ProjectID 
	where Project_Id=@ProjectID	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTaskDetails_ParticularProject]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetTaskDetails_ParticularProject 6,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetTaskDetails_ParticularProject]
	@ProjectID bigint,
	@TaskID bigInt
AS
BEGIN
	SET NOCOUNT ON;
    if(@TaskID!=0)
    begin
		SELECT * from TA_Tbl_Project P 
		Inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
		left outer join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and PT.taskID=TPD.TaskID)
		where Project_Id=@ProjectID and PT.TaskID=@TaskID
	end
	else
	begin		
		SELECT * from TA_Tbl_Project P
		inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
		where Project_Id=@ProjectID	
		--left outer join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and TPD.TaskID=PT.TaskID)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	10-Dec-2013
Descriptions	:	Adding this proce for getting processed data of the temp weekday
*/
CREATE proc [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]
(
@tempWeekday_Id int
)
as
begin
	select COUNT(*) as count from TA_Tbl_ProcessedData P
	inner join TA_Tbl_TemWeekday TW on P.Date between TW.TempWeekday_FromDate and TW.TempWeekday_ToDate
	inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWL.TempWeekday_Id=TW.TempWeekday_Id
	where TW.IsDeleted=0 and TW.timestamp<=P.Date
	and P.ProcessFlag=1 and TW.TempWeekday_Id=@tempWeekday_Id
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTerminalMappingCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified by	:	Prabakaran.P
-- Modified on	:	17-Mar-08
CREATE   PROCEDURE [dbo].[Proc_TA_GetTerminalMappingCount]
(
	@TerminalId INT
)
AS
BEGIN
	DECLARE @Count AS INT
	DECLARE @Count1 AS INT
	SELECT @Count1 =COUNT(P.Terminal_Id) FROM TA_Tbl_Terminal T
	inner join TA_Tbl_PunchTypes P on P.Terminal_Id = T.Terminal_Id WHERE T.Terminal_Id = @TerminalId
	SELECT @Count = COUNT(eio.Entrance_Id) FROM TA_Tbl_Entrance_INOUTDetails eio INNER JOIN TA_Tbl_Entrance en ON en.Entrance_Id=eio.Entrance_Id 
	WHERE eio.Reader_Id=@TerminalId
	SELECT @Count + @Count1 AS TerminalMappingCount
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Surguru]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <27_Aug_2019 02:33 PM>
-- Description:	<This procedure gives dashbaord informations created especially for surguru, four results set added with work location filter>
-- [Proc_TA_GetTheDashboardInformation_Surguru] '', '2019-08-30 00:00:00.000', '2019-08-30 00:00:00.000',0,0,1,'SuperAdmin','0','0',4
--select * from testDashboardSurguru
--select * from Ta_Tbl_levelDetails
	  --insert into testDashboardSurguru values
	  --(
	  --@EMPLOYEECODEID,
   --   @FROMDATE,
   --   @TODATE,
   --   @Session,
   --   @ShiftID,
   --   @ParentID,
   --   @UserGroupName,
   --   @GradeLevel,
   --   @empId,
	  --@WorkLocation 
	  --)
	--  	Create table testDashboardSurguru (

	--  EMPLOYEECODEID VARCHAR(MAX),
 --     FROMDATE datetime,
 --     TODATE datetime,
 --     Session INT,
 --     ShiftID int,
 --     ParentID int,
 --     UserGroupName nvarchar(100),
 --     GradeLevel NVARCHAR(20),
 --     empId NVARCHAR(max),
	--  WorkLocation int
	--)
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Surguru] 
	-- Add the parameters for the stored procedure here
	  @EMPLOYEECODEID VARCHAR(MAX) = NULL,
      @FROMDATE datetime,
      @TODATE datetime,
      @Session INT,
      @ShiftID int,
      @ParentID int,
      @UserGroupName nvarchar(100),
      @GradeLevel NVARCHAR(20),
      @empId NVARCHAR(max),
	  @WorkLocation int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	  SET NOCOUNT ON;
	  Declare @FirstBoard varchar(max)
      Declare @FirstBoard1 varchar(max)
      Declare @SecondBoard varchar(max)
      Declare @ThirdBoard varchar(max)
      Declare @FourthBoard varchar(max)
      Declare @FifthBoard varchar(max)
      Declare @sixthBoard varchar(max)
      Declare @Present_Filters varchar(max)
      Declare @Absetn_Filters varchar(max)
      Declare @Leave_Filters varchar(max)
      Declare @Union varchar(max)
      set @Union=' Union All '
      Declare @FromdateString varchar(20)
      declare @todat as nvarchar(20);
      set @todat=GETDATE();
      if @FROMDATE=''
            begin
                  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(varchar(20),DATEPART(month,getdate()))+'-'+
                  case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(varchar(20),DATEPART(D,GETDATE()))
                  else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
            end   
      else
            begin
                  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(varchar(20),DATEPART(month,@fromdate))+'-'+
                  case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(varchar(20),DATEPART(D,@fromdate))
                  else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
            end
      create table #TempProcesseddata(ProcessRecId bigint,PresentCount bigint)
      create table #TempProcessedPresentdata(ProcessRecId bigint)
      create table #LevelRights(LevelId int)
      create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
      Create table #FirstTableValue(TOPIC varchar(100),ValueCount int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
      Create table #SecondDummyTableValue(TOPIC varchar(100),Count int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
      Create table #ThirdDummyTableValue(Approval varchar(100),Approved int,Forwarded int,Pending varchar(100),ApprovedPercent varchar(30),ForwardedPercent varchar(30),PendingPercent varchar(30))
      CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
      if(@ParentID=0)
      begin
            Declare @groupid int
            set @groupid=(select groupId from TA_Tbl_Usergroup where groupName=@UserGroupName)
            insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
      end
      else
      begin 
            insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId		
      end
	    INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',''
		declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
      Declare @sqlEmpLevel nvarchar(4000) 
      set @sqlEmpLevel=
      'insert into #EmpLevel 
      select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
      (
            select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
            inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
            INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
            inner join #LevelRights on #LevelRights.LevelId= el.LevelId
            where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
            ((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and emp.Employee_Code_Id<>''18000000''
            group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
      ) ELevel
      inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) and EL.LevelId is not null'    
      if(@isReportingto > 0)
            BEGIN
                  set @sqlEmpLevel = @sqlEmpLevel + ' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) '  
            END   
      if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
            BEGIN
                  set @sqlEmpLevel = @sqlEmpLevel + ' and ELevel.EmployeeId in ('+CAST(@empId as nvarchar(10))+')'
            END   
      execute(@sqlEmpLevel)
      Declare @Employeecount int
      Declare @EmployeePresentcount int
      Declare @EmployeecountQuery nvarchar(4000)
      Declare @EmployeePresentcountQuery nvarchar(4000)     
      set @EmployeecountQuery = 'insert into #TempProcesseddata SELECT count(Process_Rec_Id),
      COUNT(case  when(FNAttendanceCode=''Present'' or ANAttendanceCode=''Present'') then 1 else 0 end)
      FROM TA_TBL_PROCESSEDDATA P
                  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
                  WHERE P.DATE='''+convert(varchar(max),@FromdateString)+''''
      if(@ShiftID!=0)
      begin
            set @EmployeecountQuery =@EmployeecountQuery +' and P.Shift_Id='+convert(varchar(10),@shiftId)
      end   
      execute (@EmployeecountQuery)
      select @Employeecount=ProcessRecId,@EmployeePresentcount=PresentCount from #TempProcesseddata
      IF ((ISNULL(@FROMDATE, '') <> ''))
            BEGIN
            --First Gridview Control
            Declare @CommonJoinQueries varchar(max)         
            Declare @CommonSelectQueries varchar(max) 
            set @FirstBoard=''      
            Declare @Firstboardexists int
            set @Firstboardexists=0
            set @CommonJoinQueries=''
            set @CommonJoinQueries=@CommonJoinQueries+' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
            Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
            INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
            INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
            INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID           
			left outer join ta_tbl_shiftadd_location LOC on LOC.EmployeeId = E.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102)'
			-- Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
            set @CommonSelectQueries=''
            set @CommonSelectQueries=@CommonSelectQueries+'select 
                  TOPIC,
                  COUNT,
                  HYPER,
                  REPORTNAME, 
                  Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                              Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeeCount)+' * 100)),0))+'' %'' 
                  End'
            Declare @Filters varchar(max)
            set @Filters=''
            if(@ShiftID!=0)
            begin
                  set @Filters =@Filters+' and P.Shift_Id='+convert(varchar(10),@shiftId)
            end
            if(@UserGroupName<>'SuperAdmin')
            BEGIN
                  SET @Filters = @Filters + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
            END
			--for Surguru--
			if(@WorkLocation<>0)
            BEGIN
                  SET @Filters = @Filters + ' AND LOC.LocationId=' + convert(varchar(100),@WorkLocation)
            END
            -- Added below line by manikandan.r on 16-11-2016
            -- if you remove below line it will bring wrong value for absent column.bug id:0035540
            if(@isReportingto > 0)
            BEGIN  
                  SET @Filters = @Filters + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
            End
            --Getting Present Data
            if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
            begin
                  set @FirstBoard =@CommonSelectQueries+' as PercentageValue from 
                  (
                        SELECT DISTINCT ''Present'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''MonthlyAttendance'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'       
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries
                        SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') 
                        AND (ANAttendanceCode=''PRESENT'' or FNAttendanceCode=''Present'')
                        AND E.Report_Exclude=0 and E.Isdeleted=0 
                        and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
                        and E.Employee_Code_Id<>''18000000'''                       
                  set @FirstBoard=@FirstBoard+@Filters+') as Present'
                  set @Firstboardexists=1
            end
            --Getting Absent Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard =@FirstBoard+@CommonSelectQueries+' as AbsenteesPercent from 
                  (
                        SELECT DISTINCT ''Absent'' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''Absentees'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries        
                        SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') AND 
                        (ANAttendanceCode=''ABSENT'' AND FNAttendanceCode=''Absent'') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                        ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
                        and E.Employee_Code_Id<>''18000000'''
                  set @FirstBoard=@FirstBoard+@Filters+') as Absent'
                  set @Firstboardexists=1
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
            begin
                  declare @LeaveCount varchar(max)
                  --Getting Leave Data          
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard=@FirstBoard+@CommonSelectQueries+' as LeavePercent from 
                  (
                        SELECT DISTINCT ''Approved Leave'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''Leave_Angler'' AS REPORTNAME 
                        FROM TA_TBL_PROCESSEDDATA P'        
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries
                        SET @FirstBoard = @FirstBoard + ' WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') 
                        AND 
                        (
                              FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') or
                              ANAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'')
                        )
                        AND E.Report_Exclude=0 and E.Isdeleted=0 
                        and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
                        and E.Employee_Code_Id<>''18000000'''                       
                  set @FirstBoard=@FirstBoard+@Filters+') as Leave'
                  set @Firstboardexists=1
            end
            --Getting Onduty Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ' as OnDutyPercent from (
                  SELECT DISTINCT ''Approved OnDuty'' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''OnDuty'' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
                  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
				  left outer join ta_tbl_shiftadd_location LOC on LOC.EmployeeId = E.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102)
                  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and
                  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
                  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) '
                  SET @FirstBoard = @FirstBoard + ' WHERE (M.ManualTimeEntry_InDate <= '''+convert(varchar(max),@FromdateString)+''') AND (M.ManualTimeEntry_OutDate  >= '''+convert(varchar(max),@FromdateString)+''') 
                  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
                  and E.Employee_Code_Id<>''18000000'''                       
                  set @FirstBoard=@FirstBoard+@Filters+') as OnDuty'
                  set @Firstboardexists=1
            end
            --Getting Punctuality Data
			set @FirstBoard1 = ''
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard1 =@FirstBoard1+@Union
                  end
                  set @FirstBoard1=@FirstBoard1+@CommonSelectQueries+ ' as PunctualityPercent from (
                  SELECT DISTINCT ''Punctuality'' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''Punctuality'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
                  SET @FirstBoard1 = @FirstBoard1 + @CommonJoinQueries
                  SET @FirstBoard1 = @FirstBoard1 + ' WHERE (P.DATE ='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(LATEINMINS,0)=0 AND 
                  (ANAttendanceCode<>''Weekly Off'' or FNAttendanceCode<>''Weekly Off'') AND (p.LateIn=''00:00'' and p.InTime <> ''00:00'')
                  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) and E.Employee_Code_Id<>''18000000'''
                  set @FirstBoard1=@FirstBoard1+@Filters+') as Punctuality'
                  set @Firstboardexists=1				
            end
            --Getting Rawdata
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard1 =@FirstBoard1+@Union
                  end
                  set @FirstBoard1=@FirstBoard1+@CommonSelectQueries+ '  as RawDataPercent from (
                  Select ''Attendance Summary'' As TOPIC,COUNT(P.DATE) [COUNT],
                  6 as HYPER,''AttendanceSummary'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
                  SET @FirstBoard1 = @FirstBoard1 + @CommonJoinQueries
                  SET @FirstBoard1 = @FirstBoard1 + ' WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102)))
                  and E.Employee_Code_Id<>''18000000'''           
                  set @FirstBoard1=@FirstBoard1+@Filters+ ') as Attendance'
            end
            if(ISNULL(@FirstBoard,'')!='' and ISNULL(@FirstBoard1,'')!='')
            begin	 
                 Execute('insert into #FirstTableValue ' + @FirstBoard + @FirstBoard1)
            end
            select * from #FirstTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            --Second Table
            --Getting Late Entry Data
            Declare @WhereFilter varchar(max)
            set @ThirdBoard=''
            Declare @ThirdBoardvalue int
            set @ThirdBoardvalue =0
            set @WhereFilter =' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
            ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,'''+@FromdateString+''',102))) 
            and E.Employee_Code_Id<>''18000000'''
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
            begin
                  set @ThirdBoard='  
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' 
                        End as Percentage from (
                  SELECT DISTINCT ''Late Entry'' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''LateEntry'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE ='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(LATEINMINS,0)<>0 '
                  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
                  set @ThirdBoardvalue=1
            end
            --Getting Early Exit Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+' 
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
                        as Percentage from (                
                  SELECT DISTINCT ''Early Exit'' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''EarlyExit'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P'
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + 'WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(EarlyOutMins,0)<>0 '
                  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+') as A'
                  set @ThirdBoardvalue=1
            end
            --Getting Less Hours worked Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+'
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End as 
                        Percentage from (                   
                  SELECT DISTINCT ''Less Hours Worked'' AS TOPIC, COUNT(P.DATE) [COUNT],3 AS HYPER, ''LessHoursWorked'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ' WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') AND P.HrsLess is not null and P.HrsLess<>''00:00'' and P.HrsLess<>'''' AND CHARINDEX(''-'',p.HrsLess)=0 '
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
                  set @ThirdBoardvalue=1
            end
            --Getting Approved Overtime Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+'
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
                        as Percentage from (                
                  SELECT DISTINCT ''Approved Over Time'' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''OverTime'' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P '
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '  WHERE (P.DATE='''+convert(varchar(max),@FromdateString)+''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''Approved'' And E.CompOff_Eligible=0 And E.OT_Eligible=1 '
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+') as A'
                  set @ThirdBoardvalue=1 
            end         
            --Getting Discrepancy Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+'
                  select      TOPIC,
                              COUNT,
                              HYPER,
                              REPORTNAME,  
                              Case  when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                                          Else convert(varchar(20),Round(convert(varchar(20),(DistinctCOUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
                                          as Percentage from 
                  ( 
                        SELECT      DISTINCT ''Discrepancy'' AS TOPIC, 
                                    COUNT(C.Clk_EmpId) [COUNT],
                                    COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
                                    5 AS HYPER, 
                                    ''Discrepancy'' AS REPORTNAME 
                        FROM ta_tbl_clockdetails C
                        Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
                        Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                        INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                        INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                        INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                        Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
                  SET @ThirdBoard = @ThirdBoard + '  WHERE (C.Clk_Date ='''+convert(varchar(max),@FromdateString)+''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) '
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+') as A'
                  set @ThirdBoardvalue=1 
            end
            --Getting Non processed data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+'
                  select      TOPIC,
                              COUNT,
                              HYPER,
                              REPORTNAME, 
                              Case  when '+convert(varchar(10),@EmployeePresentcount)+'=0 then ''0 %''
                                          Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/'+convert(varchar(10),@EmployeePresentcount)+' * 100)),0))+'' %'' End 
                                          as Percentage 
                  from(
                              Select      ''Non Processed Record'' As TOPIC,
                                          COUNT(*)[COUNT],
                                          COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
                                          6 as HYPER,
                                          ''Non Process'' AS REPORTNAME 
                              FROM TA_Tbl_Clk_RawData C           
                  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  '
                  SET @ThirdBoard = @ThirdBoard + ' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE ='''+convert(varchar(max),@FromdateString)+''''
                  set @ThirdBoard=@ThirdBoard+') as A'
            end
            --Execute(@ThirdBoard)
            if(ISNULL(@ThirdBoard,'')!='')
            begin
           -- print (@ThirdBoard)
                  Execute(@ThirdBoard)
            end
            else
            begin
                  select * from #SecondDummyTableValue
            end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            Declare @SecondBoardValue int
            set @SecondBoardValue=0
            set @FifthBoard=' '
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
            begin
            set @FifthBoard=@FifthBoard+'
            select 
                  ''Leave'' as Approval,
                  Approved,
                  Forwarded,
                  Pending,
                  Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                              Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/'+convert(varchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
                  End as ApprovedPercent,
                  Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                              Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/'+convert(varchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
                  End as ForwardedPercent,
                  Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                              Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/'+convert(varchar(10),@EmployeeCount)+') * 100),0))+'' %'' 
                  End as PendingPercent from
            (
                        select      
                                    count(case  when L.Status=''Approved'' then 1  end)Approved,
                                    count(case  when L.Status=''Forwarded'' then 1 end)Forwarded,
                                    count(case  when L.Status=''Pending''  then 1  end)Pending
                        from TA_Tbl_LeaveApplication L 
                        Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
                        Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                        INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                        INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                        INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                        Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
                        Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=e.SwipeCardNo and 
                        (((l.Leave_FromDate BETWEEN P.Date AND P.Date) OR (l.Leave_ToDate BETWEEN P.Date AND P.Date)) OR 
                        (P.Date BETWEEN l.Leave_FromDate AND l.Leave_ToDate))  '
                        SET @FifthBoard = @FifthBoard + '  where 
                        L.Leave_FromDate <=''' + CONVERT(varchar(max),@FromdateString) +''' and 
                        L.Leave_ToDate >=''' + CONVERT(varchar(max),@FromdateString) +''' and L.IsDeleted=0'
                        if(@ShiftID!=0)
                              begin
                                    set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(varchar(10),@shiftId)
                              end               
                        if(@UserGroupName<>'SuperAdmin')
                              BEGIN
                                    SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
                              END
                        if(@isReportingto > 0)
                        BEGIN  
                              SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
                        End         
                        set @FifthBoard=@FifthBoard+') as a'
                        set @SecondBoardValue=1                         
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
            begin
                  if @SecondBoardValue=1
                  begin
                        set @FifthBoard =@FifthBoard+@Union
                  end
                  set @FifthBoard=@FifthBoard+ ' select 
                        ''Onduty'' as Approval,
                        Approved,
                        Forwarded,
                        Pending,
                        Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                    Else convert(varchar(20),Round(convert(varchar(20),(Approved*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                        End as ApprovedPercent,
                        Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                    Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                        End as ForwardedPercent,
                        Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                    Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                        End as PendingPercent from
                        (
                                    select                              
                                    count(case  when M.ManualTimeEntry_Status =''Approved'' then 1 else null end) Approved,
                                    count(case  when M.ManualTimeEntry_Status=''Forwarded'' then 1 else null end) Forwarded,
                                    count(case  when M.ManualTimeEntry_Status=''Pending''  then 1 else null end)  Pending
                                    from Ta_Tbl_ManualTimeEntry M Inner join TA_Tbl_Employee E 
                                    on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
                                    Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                                    INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                                    INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                                    INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
                                    Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
                                    Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
                                    (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
                                    (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  '
                  SET @FifthBoard = @FifthBoard + ' where M.IsOnDuty=1 and M.isDeleted=0 and
                  M.ManualTimeEntry_InDate<='''+ CONVERT(varchar(max),@FromdateString) +''' and 
                  M.ManualTimeEntry_OutDate>='''+ CONVERT(varchar(max),@FromdateString) +''' and M.IsDeleted=0'
                  if(@ShiftID!=0)
                        begin
                              set @FifthBoard=@FifthBoard+' and P.Shift_Id='+convert(varchar(10),@shiftId)
                        end         
                  if(@UserGroupName<>'SuperAdmin')
                        BEGIN
                              SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
                        END   
                  if(@isReportingto > 0)
                  BEGIN  
                        SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
                  End               
                  set @FifthBoard=@FifthBoard+') as B '
                  set @SecondBoardValue=1 
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
            begin
                  if @SecondBoardValue=1
                  begin
                        set @FifthBoard =@FifthBoard+@Union
                  end
                  set @FifthBoard=@FifthBoard+' select ''Permission'' as Approval,
                              Approved,
                        Forwarded,
                        Pending,
                              Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                              End as ApprovedPercent,
                              Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                              End as ForwardedPercent,
                              Case  when '+convert(varchar(10),@EmployeeCount)+'=0 then ''0 %''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/'+convert(varchar(10),@EmployeeCount)+')*100),0))+'' %'' 
                              End as PendingPercent from
                  (
                              select 
                                          count(case  when P.Permission_Status=''Approved'' then 1 else null end) Approved,
                                          count(case  when P.Permission_Status=''Forwarded'' then  1 else null end)Forwarded,
                                          count(case  when P.Permission_Status=''Pending''  then 1 else null end) Pending
                              from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
                              Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                              INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                              INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                                    INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
                  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  '
                  SET @FifthBoard = @FifthBoard + ' where P.Permission_Date='''+ CONVERT(varchar(max),@FromdateString) +''' and P.IsDeleted=0'
                  if(@ShiftID!=0)
                        begin
                              set @FifthBoard=@FifthBoard+' and PD.Shift_Id='+convert(varchar(10),@shiftId)
                        end         
                  if(@UserGroupName<>'SuperAdmin')
                        BEGIN
                              SET @FifthBoard = @FifthBoard + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
                        END   
                  if(@isReportingto > 0)
                  BEGIN  
                        SET @FifthBoard = @FifthBoard + ' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) '
                  End   
                  set @FifthBoard=@FifthBoard+')as A'
            end
            if(ISNULL(@FifthBoard,'')!='')
            begin
                  Execute(@FifthBoard)
            end
            else
            begin
                  select * from #ThirdDummyTableValue
            end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
      END
      Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
      drop table #EmpLevel
      drop table #LevelRights
      drop table #FirstTableValue
      drop table #SecondDummyTableValue
      drop table #ThirdDummyTableValue
      drop table #TempProcesseddata
      drop table #TempProcessedPresentdata
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Working]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetTheDashboardInformation_Working '', '2020/08/10', '2020/08/10',0,0,0,'superadmin','0','0'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Working]
      -- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
      @EMPLOYEECODEID VARCHAR(MAX) = NULL,
      @FROMDATE datetime,
      @TODATE datetime,
      @Session INT,
      @ShiftID int,
      @ParentID int,
      @UserGroupName nvarchar(100),
      @GradeLevel NVARCHAR(20),
      @empId NVARCHAR(max)
AS
BEGIN 
	set nocount on;
	
	Declare @FromdateString varchar(20)
	declare @todat as nvarchar(20);
	set @todat=GETDATE();
	if @FROMDATE=''
		begin
			  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+'-'+CONVERT(varchar(20),DATEPART(month,getdate()))+'-'+
			  case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then '0'+CONVERT(varchar(20),DATEPART(D,GETDATE()))
			  else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
		end   
	else
		begin
			  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(varchar(20),DATEPART(month,@fromdate))+'-'+
			  case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(varchar(20),DATEPART(D,@fromdate))
			  else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
	
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	Create table #FirstTableValue(TOPIC varchar(100),ValueCount int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
	Create table #SecondDummyTableValue(TOPIC varchar(100),Count int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
	Create table #ThirdDummyTableValue(Approval varchar(100),Approved int,Forwarded int,Pending varchar(100),ApprovedPercent varchar(30),ForwardedPercent varchar(30),PendingPercent varchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		set @groupid=(select groupId from TA_Tbl_Usergroup where groupName=@UserGroupName)
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--insert into #LevelRights select LocationId from TA_tbl_ShiftAdd_Location where LocationId = @ParentID
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'',''
	declare @isReportingto as int
	declare @IndividualUsers int
	select @isReportingto=ReportsBasedOn,@IndividualUsers=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@isReportingto>0 or @UserGroupName='Superadmin')
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	end
	
	Insert into #EmpLevel
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and
		(isnull(@isReportingto,0)=0 or el.EmployeeId IN (select * from #EmployeeIds))
		and
		(isnull(@empId,0)=0 or @empid='' or (@IndividualUsers=1 and Employee_Id=@empId))
		and
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,@FromdateString,102))) and emp.Employee_Code_Id<>'18000000'
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@FROMDATE as nvarchar(50)), 102) and EL.LevelId is not null
    
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeePresentcountQuery nvarchar(4000)
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode='Present' or ANAttendanceCode='Present') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
		  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
		  WHERE P.DATE=convert(varchar(max),@FromdateString)
		  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
		  
	IF ((ISNULL(@FROMDATE, '') <> ''))
    BEGIN
        --Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case	when isnull(@EmployeeCount,0)=0 then '0 %'
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			  End as PercentageValue from 
			  (
					SELECT	DISTINCT 'Present' AS TOPIC, 
							COUNT(P.DATE) TotalEmployeeCount,
							1 AS HYPER, 'MonthlyAttendance' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id						
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  WHERE (P.DATE=@FROMDATE) 
					AND (ANAttendanceCode='PRESENT' or FNAttendanceCode='Present')
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and 
					(
						(E.Employee_Status=1) or
						(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
					)
					and E.Employee_Code_Id<>'18000000'
					and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
					and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			   )as Present
		end	    
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin                 
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case  when isnull(@EmployeeCount,0)=0 then '0 %'
						  Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			  End as AbsenteesPercent from 
			  (
					SELECT	DISTINCT 'Absent' AS TOPIC, 
							COUNT(*) TotalEmployeeCount,
							2 AS HYPER, 
							'Absentees' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  
					WHERE (P.DATE=@FROMDATE) AND (ANAttendanceCode='ABSENT' AND FNAttendanceCode='Absent') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
					and E.Employee_Code_Id<>'18000000'
					and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
					and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			   ) as Absent
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin                
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case	when isnull(@EmployeeCount,0)=0 then '0 %'
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			End as LeavePercent from 
			(
				SELECT	DISTINCT 'Approved Leave' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						1 AS HYPER, 'Leave_Angler' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  
				WHERE (P.DATE=@FROMDATE) 
				AND
				(
					FNAttendanceCode not in('Present','Absent','Weekly Off','Holiday','RH') or
					ANAttendanceCode not in('Present','Absent','Weekly Off','Holiday','RH')
				)
				AND E.Report_Exclude=0 and E.Isdeleted=0 
				and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Leave
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin 
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case	when isnull(@EmployeeCount,0)=0 then '0 %'
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			  End as OnDutyPercent from 
			  (
				SELECT	DISTINCT 'Approved OnDuty' AS TOPIC, 
						COUNT(M.ManualTimeEntry_InDate) TotalEmployeeCount,
						4 AS HYPER, 
						'OnDuty' AS REPORTNAME 
				FROM Ta_Tbl_ManualTimeEntry M
				inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
				Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id					
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
				(
					((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
					(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)
				)  
				WHERE (M.ManualTimeEntry_InDate <= @FROMDATE) AND (M.ManualTimeEntry_OutDate  >= @FROMDATE)
				AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status ='Approved' And OD.Onduty_Status ='Approved' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				(
					(E.Employee_Status=1) or
					( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				)
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as OnDuty
		end
        ----Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case	when isnull(@EmployeeCount,0)=0 then '0 %'
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			End as PunctualityPercent from 
			(
				SELECT	DISTINCT 'Punctuality' AS TOPIC, 
				COUNT(P.DATE) TotalEmployeeCount,
				6 AS HYPER, 'Punctuality' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE =@FROMDATE) AND ISNULL(LATEINMINS,0)=0 AND 
				(ANAttendanceCode<>'Weekly Off' or FNAttendanceCode<>'Weekly Off') AND (isnull(p.LateIn,'00:00')<>'00:00')
				AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				(
					(E.Employee_Status=1) or
					(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				) and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Punctuality
		end
				----Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
			End  as RawDataPercent from 
			(
				Select	'Attendance Summary' As TOPIC,
				COUNT(P.DATE) TotalEmployeeCount,
				6 as HYPER,
				'AttendanceSummary' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND E.Report_Exclude=0 and E.Isdeleted=0 and       
				(
					(E.Employee_Status=1) or
					(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				)
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Attendance
		end
		select * from #FirstTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        --ThirdBoard Table
        --Getting Late Entry Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
        begin
			 insert into #SecondDummyTableValue
             select	TOPIC,
						TotalEmployeeCount,
						HYPER,
						REPORTNAME,
						Case	when isnull(@EmployeeCount,0)=0 then '0 %'
								Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
						End as Percentage 
			  from 
			  (
				SELECT	DISTINCT 'Late Entry' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						1 AS HYPER, 'LateEntry' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE =@FROMDATE) AND ISNULL(LATEINMINS,0)<>0  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			  ) as A

        end
        --Getting Early Exit Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
					End as Percentage 
			from 
			(                
				SELECT	DISTINCT 'Early Exit' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						2 AS HYPER, 'EarlyExit' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND ISNULL(EarlyOutMins,0)<>0  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
        end
        --Getting Less Hours worked Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
        begin
            insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %' 
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
					End as Percentage 
			from 
			(
				SELECT	DISTINCT 'Less Hours Worked' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						3 AS HYPER, 
						'LessHoursWorked' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND P.HrsLess is not null and P.HrsLess<>'00:00' and P.HrsLess<>'' AND CHARINDEX('-',p.HrsLess)=0  
				AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			)as A

        end
        --Getting Approved Overtime Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
        begin
            insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
					End 
			as Percentage from 
			(
				SELECT	DISTINCT 'Approved Over Time' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						4 AS HYPER, 
						'OverTime' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus ='Approved' 
				And E.CompOff_Eligible=0 And E.OT_Eligible=1  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>'18000000'
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
        end         
        --Getting Discrepancy Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,  
					Case	when isnull(@EmployeeCount,0)=0 then '0 %' 
							Else convert(varchar(20),Round(convert(varchar(20),(DistinctCOUNT*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
					End 
					as Percentage from 
					( 
						SELECT	DISTINCT 'Discrepancy' AS TOPIC, 
								COUNT(C.Clk_EmpId) TotalEmployeeCount,
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								'Discrepancy' AS REPORTNAME 
						FROM ta_tbl_clockdetails C
						Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
						Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
						INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
						Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id   WHERE (C.Clk_Date =@FROMDATE) AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null)  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
						((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
						and E.Employee_Code_Id<>'18000000'
						and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
					) as A
        end
        --Getting Non processed data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME, 
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+' %' 
					End as Percentage 
			from
			(
				Select	'Non Processed Record' As TOPIC,
						COUNT(*)TotalEmployeeCount,
						COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
						6 as HYPER,
						'Non Process' AS REPORTNAME 
				FROM TA_Tbl_Clk_RawData C           
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID   
				where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE =@FROMDATE
				--and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
 
        end
        select * from #SecondDummyTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
        begin 
			insert into #ThirdDummyTableValue      
			select 
			'Leave' as Approval,
			Approved,
			Forwarded,
			Pending,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/isnull(@EmployeeCount,0)) * 100),0))+' %' 
			End as ApprovedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0)) * 100),0))+' %' 
			End as ForwardedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0)) * 100),0))+' %' 
			End as PendingPercent from
			(
				select      
				count(case  when L.Status='Approved' then 1  end)Approved,
				count(case  when L.Status='Forwarded' then 1 end)Forwarded,
				count(case  when L.Status='Pending'  then 1  end)Pending
				from TA_Tbl_LeaveApplication L 
				Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=e.SwipeCardNo and 
				(((l.Leave_FromDate BETWEEN P.Date AND P.Date) OR (l.Leave_ToDate BETWEEN P.Date AND P.Date)) OR 
				(P.Date BETWEEN l.Leave_FromDate AND l.Leave_ToDate))    where 
				L.Leave_FromDate <=@FROMDATE and 
				L.Leave_ToDate >=@FROMDATE and L.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'')='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			) as a  
        end
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
        begin
			insert into #ThirdDummyTableValue
			select 
			'Onduty' as Approval,
			Approved,
			Forwarded,
			Pending,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),(Approved*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
			End as ApprovedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
			End as ForwardedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then '0 %'
			Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
			End as PendingPercent from
			(
				select                              
				count(case  when (M.ManualTimeEntry_Status ='Approved' and OD.Onduty_Status ='Approved') then 1 else null end) Approved,
				count(case  when (M.ManualTimeEntry_Status='Forwarded' and OD.Onduty_Status='Forwarded') then 1 else null end) Forwarded,
				count(case  when (M.ManualTimeEntry_Status='Pending' and OD.Onduty_Status='Pending')  then 1 else null end)  Pending
				from Ta_Tbl_ManualTimeEntry M 
				inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
				Inner join TA_Tbl_Employee E 
				on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
				(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
				(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))   where M.IsOnDuty=1 and M.isDeleted=0 and
				M.ManualTimeEntry_InDate<=@FROMDATE and 
				M.ManualTimeEntry_OutDate>=@FROMDATE and M.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'')='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			) as B 

        end
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
        begin
			insert into #ThirdDummyTableValue
			select	'Permission' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
					End as ApprovedPercent,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
					End as ForwardedPercent,
					Case	when isnull(@EmployeeCount,0)=0 then '0 %'
							Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0))*100),0))+' %' 
					End as PendingPercent 
			from
			(
				select 
				count(case  when P.Permission_Status='Approved' then 1 else null end) Approved,
				count(case  when P.Permission_Status='Forwarded' then  1 else null end)Forwarded,
				count(case  when P.Permission_Status='Pending'  then 1 else null end) Pending
				from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
				Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date   
				where P.Permission_Date=@FROMDATE and P.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or PD.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'')='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			)as A

        end
		select * from #ThirdDummyTableValue
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
select * from TA_Tbl_Usergroup where groupName='Project Manager'
Proc_TA_GetTimeSheetEntryDetails_Sanction 10,1,'Forwarded','','',0,0,'2020/01/01','2020/07/30','superadmin',1
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]
	@login_EmployeeID int,
	@LevelId varchar(2000),
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmpCategory int, 
	@EmpType int,
	@FromDate varchar(20)=null,    
	@ToDate varchar(20) =null,
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	
	if(@isReportingto=1)
	begin
		if(@Status!='Forwarded')
		BEGIN
			insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@login_EmployeeID) as EmpAutoId  
		END
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@login_EmployeeID) as EmpAutoId
		delete from #EmployeeIds where EmpAutoId=@login_EmployeeID
	end
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
	(
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	
	--Employee Type insert in Temporary table
	insert into #EmpType 
	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from 
	(
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
		and(ISNULL(@EmpType,0)=0 or et.TypeId=@EmpType)
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from 
	(
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
		and(ISNULL(@EmpCategory,0)=0 or ec.CategoryId=@EmpCategory)
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1	
	
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	select	E.Employee_Code_Id EmployeeID,
			isnull(E.Employee_FirstName,'')+ isnull(E.Employee_MiddleName,'')+isnull(E.Employee_LastName,'') EmployeeName,
			case	when cast(@dateFormat as varchar(100))=106 then
							REPLACE(CONVERT(VARCHAR(11), tp.ShiftDate,@dateFormat),'','-') 
					else CONVERT(VARCHAR, tp.ShiftDate, @dateFormat)
			end ShiftDate,
			P.Project_Name ProjectName,
			ptl.TaskName,
			tp.TaskHours,
			tp.TaskDescription,
			tp.SpentHours,
			tp.TaskDetailID,
			case when isnull(ts.ApprovedHours,'')<>'' then ts.ApprovedHours else tp.SpentHours end as ApprovedHours,
			tp.Status,
			E.Employee_Id,			
			RecordID=Dense_Rank()over(order by Employee_Code_Id,Shiftdate)
	from TA_TBL_Employee E
	inner join ta_tbl_taskprogressdetails tp on  E.Employee_Id=tp.TaskSubmittedBy
	left outer join ta_tbl_taskprogressStatus ts on tp.TaskDetailID=ts.TaskDetailID
	inner join TA_Tbl_Project P on P.Project_Id=tp.ProjectID
	inner join TA_tbl_ProjectTaskList PTL on (PTL.ProjectID=P.Project_Id and tp.TaskID=PTL.TaskID)
	Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id
	Inner join #EmpType on #EmpType.employeeid = E.Employee_Id
	Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID
	inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id
	where E.Isdeleted=0
	and(ISNULL(@Status,'')='' or ISNULL(@Status,'')='All' or tp.Status=ISNULL(@Status,''))
	order by Employee_Id,convert(datetime,ShiftDate)
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting Terminal data type details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]
AS
BEGIN
	SET NOCOUNT ON;
	select TD.TerminalDatatype_ID,TD.FileType,TB.KeyValue from TA_Tbl_TerminalDatatype TD inner join TA_Tbl_TerminalBrand TB on TD.BrandID=TB.BrandID where TD.IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GettingAttendanceDetailsForSelectedDuration 787,'5/3/2017'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]
@EmpCodeID varchar(50),
@Date datetime
AS
BEGIN
	SET NOCOUNT ON;
	SELECT InTime,OutTime,HrsWork,LateIn,EarlyOut,HrsExtra from TA_Tbl_ProcessedData where Employee_Code_Id=@EmpCodeID and Date=@Date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingBLCountForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingBLCountForService]
	-- Add the parameters for the stored procedure here
	@SwipeCardNo varchar(50),
	@FromDate datetime,
	@Todate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
	select Count(Process_Rec_Id) as BLCount from  Ta_Tbl_ProcessedData  WHERE Employee_Code_Id=@SwipeCardNo
	AND (Date BETWEEN @FromDate AND @Todate) AND Status='BL'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingCompanyDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Compancy Details
-- drop procedure [dbo].[Proc_Ta_GettingCompanyDetailsForService]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingCompanyDetailsForService]
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		BEGIN TRANSACTION		
		select ld.id as CompanyId,replace(ld.name,'&amp;','&') as CompanyName
		from TA_Tbl_LevelDetails ld inner join TA_Tbl_Level l on l.LevelId=ld.LevelId
		where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.parentid=0	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDataFromClockDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Getting Data From  Clock Details>
-- [Proc_TA_GettingDataFromClockDetails]'100102','787,546838471,538109926,538100001,538100002','09/02/2018 12:10 PM','O'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingDataFromClockDetails]
@inClk_EmpId varchar(50),
@strOutDeviceId varchar(max),
@strInDateTime varchar(20),
@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type='I')
    begin
		Select Clk_Id,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_OutDeviceId IN (@strOutDeviceId) AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <  convert(datetime,@strInDateTime)) AND 
		(CAST(Clk_OutDate+Clk_OutTime AS DateTime) > convert(datetime,@strInDateTime)) AND IsVoid=0
    end
    else
    begin
		Select Clk_Id,Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,PunchType_Remarks,Clk_Remarks from TA_Tbl_ClockDetails 
		where Clk_EmpId =  @inClk_EmpId and Clk_InDeviceId IN (@strOutDeviceId) 
		AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <convert(datetime,@strInDateTime)) AND 
		(CAST(Clk_OutDate+Clk_OutTime AS DateTime) > convert(datetime,@strInDateTime)) AND IsVoid=0
    end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDeviceDataBaseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Termainl raw details using file type and terminal id>
-- [Proc_TA_GettingDeviceDataBaseDetails] 'RDBMS',2
-- exec Proc_TA_GettingDeviceDataBaseDetails @FileType=N'MDB',@TerminalDataTypeId=8
-- exec Proc_TA_GettingDeviceDataBaseDetails @FileType=N'MDB',@TerminalDataTypeId=9
-- [Proc_TA_GettingDeviceDataBaseDetails] 'PostgreSQL',13
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingDeviceDataBaseDetails]
	@FileType varchar(30),
	@TerminalDataTypeId int
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @TableName varchar(max)
	DECLARE @RDBMS_ReaderNo varchar(max)
	DECLARE @RDBMS_CardNo varchar(max)
	DECLARE @RDBMS_DateTimeBit varchar(max)
	DECLARE @RDBMS_DateTime varchar(max)
	DECLARE @DateTimeFormat varchar(max)
	DECLARE @RDBMS_Date varchar(max)
	DECLARE @DateFormat varchar(max)
	DECLARE @RDBMS_Time varchar(max)
	DECLARE @TimeFormat varchar(max)
	DECLARE @RDBMS_Type varchar(max)
	DECLARE @RDBMS_MDB_Flag varchar(max)
	DECLARE @RDBMS_TransactionIdentifier varchar(max)
	DECLARE @TransactionIdentifierValue varchar(max)
	DECLARE @TransactionIdentifierBit varchar(max)
	DECLARE @IsEncrypted varchar(max)
	Declare @ConnectionString varchar(max)
	Declare @DynamicSQL_Select varchar(max)
	Declare @IsEmployeeId varchar(max)
	Declare @strSQLUpdate varchar(max)
	Declare @autoID varchar(max)
	Declare @brandID int
	set @DynamicSQL_Select=''
	if(@FileType='RDBMS')
	begin		
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=RDBMS_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=RDBMS_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
		
		---Forming Dyanmic Query
		--Suprema
		IF(@brandID=3)
		BEGIN		
			--SELECT DEVDT=dateadd(SS,t1.DEVDT+14400,'01/01/1970'),DEVUID,USRID,EVT,TNAKEY,EVTLGUID FROM T_LG201709 t1  
			--WHERE TNAKEY IN ('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','255') 
			--AND T1.USRID IS NOT NULL AND T1.USRID <> '' AND T1.EVT IN(55,4865,4098) and EVTLGUID>0			
			SET @DynamicSQL_Select =@DynamicSQL_Select+ 'SELECT ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				
				SET @DynamicSQL_Select = @DynamicSQL_Select+'nDateTime=dateadd(SS,'+ @RDBMS_DateTime + ',''01/01/1970 00:00:00''),'
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + ',' + @RDBMS_Time + ',';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_TransactionIdentifier + +','+@RDBMS_MDB_Flag+ ' FROM '+@TableName+' WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in( ' + @TransactionIdentifierValue + ')';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_Type +' in (''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'',''15'',''16'',''255'')'
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
		END
		--Suprema Biostar 2
		ELSE IF(@brandID=4)
		BEGIN		
			--SELECT DEVDT=dateadd(SS,t1.DEVDT+14400,'01/01/1970'),DEVUID,USRID,EVT,TNAKEY,EVTLGUID FROM T_LG201709 t1  
			--WHERE TNAKEY IN ('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','255') 
			--AND T1.USRID IS NOT NULL AND T1.USRID <> '' AND T1.EVT IN(55,4865,4098) and EVTLGUID>0
			SET @DynamicSQL_Select = @DynamicSQL_Select+'SELECT ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				-- below code UTC Time getting into Timecheck created by Maria Prasanth on 24th Jan

				--SET @DynamicSQL_Select = @DynamicSQL_Select+'DEVDT=dateadd(SS,'+ @RDBMS_DateTime + '+14400,''01/01/1970''),'
				
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime +','

			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + ',' + @RDBMS_Time + ',';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_TransactionIdentifier + +','+@RDBMS_MDB_Flag+ ' FROM #Table_Name WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in( ' + @TransactionIdentifierValue + ')';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_Type +' in (''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'',''15'',''16'',''255'')'
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag

			Print @DynamicSQL_Select

		END
		--ESSL - Dynamic Table
		Else IF(@brandID=5)
		BEGIN
			--select t1.LogDate,t1.DeviceId,t1.UserId,' ',DeviceLogId FROM " + Convert.ToString(strFinaltableName) + " t1 ";
			--dataCollectionQuery += " WHERE T1.UserId IS NOT NULL AND T1.UserId <> ''
			SET @DynamicSQL_Select = @DynamicSQL_Select+'SELECT top 1000 ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_TransactionIdentifier +','+@RDBMS_MDB_Flag+ ' FROM #Table_Name WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
		END
		-- Others
		ELSE IF(@brandID=2)
		BEGIN			
			--Scufe client
			--		SELECT OFFICEPUNCH,Null as date, Null as time,
			--		MC_NO as DevicceId,
			--		55 as nEvent,
			--		a.CARDNO,
			--		NULL as Susername,NULL  as nSource, NULL as bAdminCheck,
			--		MC_NO as nTNAEvent,
			--		0 as strUniquekey
			--		FROM MachineRawPunch a
			--		left outer join tb_reportslist b on b.dtDateTime = a.OFFICEPUNCH and b.nuserid = a.CARDNO 
			--		where (a.MC_NO is not null) and (b.dtDateTime is null) and (a.OFFICEPUNCH > '20191001')
			--		order by OFFICEPUNCH asc		
			
			--	NOTE: IF ANY FLAG FIELD IS NOT AVAILABLE IN DEVICE DATABASE TABLE, REMOVE #LOG_NUMBER IN WHERE CONDITION
			
			SET @DynamicSQL_Select = 'SELECT top 1000 ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + ','+ @RDBMS_TransactionIdentifier 
			if(@RDBMS_MDB_Flag!='NoFlag')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select +','+@RDBMS_MDB_Flag 
			end
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' FROM '+ @TableName + ' WHERE ' 
			print @TableName
			if(@RDBMS_MDB_Flag!='NoFlag')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_MDB_Flag + ' > #log_Number And ';
			end
			else
			begin
				--IF(@RDBMS_DateTimeBit= 1)
				--BEGIN
					Declare @CurrentMonthStartDate datetime
					Declare @CurrentDate datetime
					set @CurrentDate=GETDATE()
					--Two months data it will pick from device database on every day and minutes.
					set @CurrentMonthStartDate=DATEADD(MONTH,DATEDIFF(month,0,DATEADD(month,-1,getdate())),0)				
					SET @DynamicSQL_Select = @DynamicSQL_Select+'('+ @RDBMS_DateTime + '>=convert(datetime,''' + CONVERT(varchar(20),@CurrentMonthStartDate) +''') and ' + @RDBMS_DateTime +'<=convert(datetime,'''+CONVERT(varchar(20),@CurrentDate)+')'') And '
				--END
			end
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			if(@RDBMS_MDB_Flag!='NoFlag')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
			end
		END
		else IF(@brandID=7)
		BEGIN		
			--SELECT DEVDT=dateadd(SS,t1.DEVDT+14400,'01/01/1970'),DEVUID,USRID,EVT,TNAKEY,EVTLGUID FROM T_LG201709 t1  
			--WHERE TNAKEY IN ('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','255') 
			--AND T1.USRID IS NOT NULL AND T1.USRID <> '' AND T1.EVT IN(55,4865,4098) and EVTLGUID>0			
			SET @DynamicSQL_Select =@DynamicSQL_Select+ 'SELECT Rtrim(' + @RDBMS_ReaderNo + ') as ' + @RDBMS_ReaderNo +',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_DateTime + ','
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + ',' + @RDBMS_Time + ',';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_TransactionIdentifier + +','+@RDBMS_MDB_Flag+ ' FROM '+@TableName+' WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in( ' + @TransactionIdentifierValue + ')';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_Type +' in (''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'',''15'',''16'',''255'')'
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
		END
		else if(@brandID=8)
		begin
			SET @DynamicSQL_Select =@DynamicSQL_Select+ 'SELECT ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+''+ @RDBMS_DateTime + ','
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + ',' + @RDBMS_Time + ',';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select +  @RDBMS_Type + ',' + @RDBMS_TransactionIdentifier + +','+@RDBMS_MDB_Flag+ ' FROM '+@TableName+' WHERE ' + @RDBMS_MDB_Flag + ' is null ';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in( ' + @TransactionIdentifierValue + ')';
				END
			END
			
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null and ' + @RDBMS_CardNo +'<>'''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
		end
		select	brandid=@brandID,
				strSQL=@DynamicSQL_Select,
				ConnectionString=@ConnectionString,
				TableName=@TableName,
				RDBMS_ReaderNo=@RDBMS_ReaderNo,
				RDBMS_CardNo=@RDBMS_CardNo,
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then 'True' else 'False' end,
				RDBMS_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				RDBMS_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				RDBMS_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted				
	end
	else if(@FileType='Delimiter' or @FileType='Fixed Length')
	begin
		select File_SourcePath,File_BackupPath,File_BackupType from TA_Tbl_TerminalDataType 
		where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
	end
	else if(@FileType='Delimiter')
	begin
		select ConnectionString,TableName,MDB_ReaderNo,MDB_CardNo,MDB_DateTimeBit,MDB_DateTime,DateTimeFormat,MDB_Date,DateFormat,
		MDB_Time,TimeFormat,MDB_Type,RDBMS_MDB_Flag,MDB_TransactionIdentifier,IsEmployeeId,TransactionIdentifierBit,TransactionIdentifierValue,IsEncrypted 
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
	end
	else if(@FileType='MDB')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=MDB_ReaderNo,
				@RDBMS_CardNo=MDB_CardNo,
				@RDBMS_DateTimeBit=MDB_DateTimeBit,
				@RDBMS_DateTime=MDB_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=MDB_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=MDB_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=MDB_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=MDB_TransactionIdentifier,
				@IsEmployeeId=IsEmployeeId,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted=IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
		--Two columns are need to be created into mdb database file -susername and nindex column. 
		SET @DynamicSQL_Select = 'SELECT Top 1000 '+ @RDBMS_MDB_Flag +' as nIndex,' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
		IF(@RDBMS_DateTimeBit= 1)
		BEGIN
			--SET @DynamicSQL_Select = @DynamicSQL_Select + Format(@RDBMS_DateTime, 'mm/dd/yyyy hh:mm:ss tt') + ','
			SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime + ','
		END
		ELSE IF(@RDBMS_DateTimeBit= 0)
		BEGIN
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + ',' + @RDBMS_Time + ',';
		END
		--SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_MDB_Flag + ' FROM ' + @TableName + ' WHERE ' + @RDBMS_MDB_Flag + ' IS NULL';
		SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_MDB_Flag + ' FROM #Table_Name WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';
		
		IF(@TransactionIdentifierBit is not null)
		BEGIN
			IF(@TransactionIdentifierBit = 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in(' + @TransactionIdentifierValue + ')';
            END
		END
		set @strSQLUpdate = 'UPDATE ' + @TableName + ' SET ' + @RDBMS_MDB_Flag + ' = ''1'' WHERE UserId =  ';
		
		select	ConnectionString=@ConnectionString,
				TableName=@TableName,
				MDB_ReaderNo=@RDBMS_ReaderNo,
				MDB_CardNo=@RDBMS_CardNo,
				MDB_DateTimeBit=case when @RDBMS_DateTimeBit=1 then 'True' else 'False' end,
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then 'True' else 'False' end,
				MDB_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				MDB_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				MDB_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				MDB_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				MDB_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted,
				strSQL=@DynamicSQL_Select,
				strSQLUpdate=@strSQLUpdate,
				@brandID as brandID

	end

	else if(@FileType='PostgreSQL')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId

			from TA_Tbl_TerminalDataType where FileType = 'PostgreSQL' and TerminalDatatype_ID = 13

			SET @DynamicSQL_Select='';

			SET @DynamicSQL_Select = @DynamicSQL_Select+'SELECT ' + @RDBMS_ReaderNo + ',' + @RDBMS_CardNo + ','
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime + ',' 
			END

			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + ',' + @RDBMS_TransactionIdentifier + +','+@RDBMS_MDB_Flag+ ' FROM '+@TableName+' WHERE ' + @RDBMS_MDB_Flag + ' > #log_Number ';

			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + ' AND ' + @RDBMS_TransactionIdentifier + ' in( ' + @TransactionIdentifierValue + ')';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' And ' + @RDBMS_CardNo + ' is not null '
			SET @DynamicSQL_Select = @DynamicSQL_Select + ' order by '+@RDBMS_MDB_Flag
			
			select	brandid=@brandID,
				strSQL=@DynamicSQL_Select,
				ConnectionString=@ConnectionString,
				TableName=@TableName,
				RDBMS_ReaderNo=@RDBMS_ReaderNo,
				RDBMS_CardNo=@RDBMS_CardNo,
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then 'True' else 'False' end,
				RDBMS_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted	

	end
	else if(@FileType='MariaDB')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=RDBMS_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=RDBMS_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId

		select	brandid=@brandID,
				strSQL='select * from tbl_event WHERE ET_GRANTED=''Y'' AND EE_IDX>=#log_Number',
				ConnectionString=@ConnectionString,
				TableName='tbl_event',
				RDBMS_ReaderNo='Dv_IDX',
				RDBMS_CardNo='EP_NO',
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then 'True' else 'False' end,
				RDBMS_DateTime='ET_DTM',
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				RDBMS_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				RDBMS_Type='ET_Granded',
				RDBMS_MDB_Flag='EE_IDX',
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue='y',
				IsEncrypted =@IsEncrypted
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]
AS
BEGIN
	SET NOCOUNT ON;
	select TA_Tbl_Employee.Employee_Id,TA_Tbl_Employee.SwipeCardNo,Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota,TA_Tbl_YearSetting.FromDate,
	TA_Tbl_YearSetting.ToDate from Ta_Tbl_EmployeeBonusLeave INNER JOIN TA_Tbl_Employee ON  TA_Tbl_Employee.Employee_Id=Ta_Tbl_EmployeeBonusLeave.EmployeeId
	INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearSetting.YearSettings_Id=Ta_Tbl_EmployeeBonusLeave.YearSettingId
	Where TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_YearSetting.IsActive=1 
	and Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota >0 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]
	-- Add the parameters for the stored procedure here
	@HolidayId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT distinct Holiday_Description from TA_Tbl_Holiday H inner join
	TA_Tbl_HolidayChildTable HCT on H.Holiday_Id=HCT.Holiday_Id where H.Isdeleted=0 and H.Holiday_Id=@HolidayId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <21-Aug-2019 10:37 AM>
-- Description:	<Verifying this employee is auto shift employee or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]
	@SwipeCardNo nvarchar(40)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @EmployeeAutoId int
	select @EmployeeAutoId = isnull(Employee_Id,0) FROM TA_Tbl_Employee WHERE SwipeCardNo = @SwipeCardNo
	--print @EmployeeAutoId
	IF(@EmployeeAutoId != 0)
	BEGIN
		IF Exists(SELECT AutoShiftConfigId FROM TA_Tbl_AutoShiftConfiguration WHERE EmployeeId = @EmployeeAutoId and (ShiftId1!=0 or ShiftId2!=0 or ShiftId3!=0 or ShiftId4!=0 or ShiftId5!=0))
		BEGIN
			SELECT 'YES' as IsAutoShiftEmployee
		END
		ELSE
		BEGIN
			SELECT 'NO' as IsAutoShiftEmployee
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingLeaveDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingLeaveDetailsForService]
	-- Add the parameters for the stored procedure here
	@inEmployee_Code_Id varchar(max),
	@Date datetime
AS
BEGIN
	SET NOCOUNT ON;
	select la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate,la.Leave_SessionFrom,la.Leave_SessionTo from TA_Tbl_LeaveApplication la,TA_Tbl_Employee emp where la.Employee_Id = emp.Employee_Id and emp.SwipeCardNo = @inEmployee_Code_Id and la.Leave_FromDate <=@Date and la.Leave_ToDate >=@Date and la.Status = 'Approved' and la.IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]
	@inLeaveTypeId int
AS
BEGIN
	SET NOCOUNT ON;
	select LeaveType from TA_Tbl_LeaveType where LeaveType_Id = @inLeaveTypeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLunchDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <27-02-2016>
-- Description:	<Getting Lunch in and Out punch details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingLunchDetails]
	-- Add the parameters for the stored procedure here
	@Employee_Code_id varchar(50),
	@clk_date datetime	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Clk_InTime datetime
	Declare @Clk_OutTime datetime
	Declare @Clk_InDate datetime
	Declare @Clk_OutDate datetime
    -- Insert statements for procedure here
	Select @Clk_InTime=MAX(Clk_InTime),@Clk_InDate= Clk_InDate from ta_tbl_clockdetails
	where clk_empid= @Employee_Code_id and clk_date=@clk_date and Clk_InPunchType='Lunch In'
	and IsVoid=0 group by Clk_InDate
	Select @Clk_OutTime=MIN(Clk_OutTime),@Clk_OutDate=Clk_OutDate from ta_tbl_clockdetails
	where clk_empid=@Employee_Code_id and clk_date=@clk_date and Clk_OutPunchType='Lunch Out'
	and IsVoid=0 group by Clk_OutDate
	select @Clk_InTime as Clk_InTime,@Clk_OutTime as Clk_OutTime,@Clk_InDate,@Clk_OutDate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingMyProfileDetailsByID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Rajkumar.J
-- Create date: 13-05-2021
-- Description:	Getting MyProfile Details By ID
-- exec Proc_Ta_GettingMyProfileDetailsByID 40
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingMyProfileDetailsByID]
	-- Add the parameters for the stored procedure here
	@intEmployeeId int = null
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
	  select * from Ta_Tbl_MyProfileDetails 		
select 

case when E.Employee_FirstName = MP.Employee_FirstName then 0 else 1 end as Employee_FirstName,
case when E.Employee_MiddleName =MP.Employee_MiddleName then 0 else 1 end as Employee_MiddleName,
case when E.Employee_LastName = MP.Employee_LastName then 0 else 1 end as Employee_LastName,
case when E.Father_name = MP.Father_name  then 0 else 1 end as Father_name,
case when E.Mother_name = MP.Mother_name then 0 else 1 end as Mother_name,
case when E.Blood_Group = MP.Blood_Group then 0 else 1 end as Blood_Group,
case when E.DateofBirth = MP.DateofBirth then 0 else 1 end as DateofBirth,
case when E.DateofBirth_Record = MP.DateofBirth_Record then 0 else 1 end as DateofBirth_Record,
case when E.EmailId = MP.EmailId then 0 else 1 end as EmailId,
case when E.Personal_mailid = MP.Personal_mailid then 0 else 1 end as Personal_mailid,
case when E.Contact_Address = MP.Contact_Address then 0 else 1 end as Contact_Address,
case when E.Permanent_Address = MP.Permanent_Address then 0 else 1 end as Permanent_Address,
case when E.Country = MP.Country then 0 else 1 end as Country,
case when E.State = MP.State then 0 else 1 end as State,
case when E.District = MP.District then 0 else 1 end as District,
case when E.Phone_Number = MP.Phone_Number then 0 else 1 end as Phone_Number,
case when E.Mobile_Number = MP.Mobile_Number then 0 else 1 end as Mobile_Number,
case when E.Marital_status = MP.Marital_status then 0 else 1 end as Marital_status,
case when E.Nationality = MP.Nationality then 0 else 1 end as Nationality,
case when E.Religion = MP.Religion then 0 else 1 end as Religion
	  from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id WHERE E.Employee_Id = @intEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <23-02-2017 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_TA_GettingNearShiftDetails_ShiftAllocation '2017/02/01','100',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]
	@FROMDAT datetime,
	@EMPLOYEEID VARCHAR(MAX),
	@CompanyId bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	CREATE TABLE #TEMPPROCESSEDDATA(EMPLOYEE_CODE_ID VARCHAR(20),INTIME NVARCHAR(25),DATE DATETIME)
	SET @SQLTEMPPROCESSEDDATA1=
	'INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			PD.DATE
	FROM TA_TBL_PROCESSEDDATA PD
	WHERE PROCESSFLAG=1 AND (PD.DATE= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))and intime is not null and intime<>''00:00'' ' 
	IF(@EMPLOYEEID<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + ' AND PD.EMPLOYEE_CODE_ID= '+  CAST (@EMPLOYEEID AS NVARCHAR(50))
		END
	--print(@SQLTEMPPROCESSEDDATA1)
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	--select * from #TEMPPROCESSEDDATA
	CREATE TABLE #TEMPMONTHLYATTENDANCE(CloseShifts varchar(max),ShiftID int)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''
	SET @SQLQUERY = 'SELECT 
	(select NearShift from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime]('''+CONVERT(varchar(20),@CompanyId)+''',PD.DATE+PD.INTIME,1,PD.DATE)where Orderby=1),
	(select ShiftID from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime]('''+CONVERT(varchar(20),@CompanyId)+''',PD.DATE+PD.INTIME,1,PD.DATE)where Orderby=1)'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.swipecardno=PD.EMPLOYEE_CODE_ID'   	
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)'    
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	(select NearShift from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime]('''+CONVERT(varchar(20),@CompanyId)+''',PD.DATE+PD.INTIME,2,PD.DATE)where Orderby=2),
	(select ShiftID from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime]('''+CONVERT(varchar(20),@CompanyId)+''',PD.DATE+PD.INTIME,2,PD.DATE)where Orderby=2)'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.swipecardno=PD.EMPLOYEE_CODE_ID'   	
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)'    
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)
	select  CloseShifts NearestShift,ShiftID
	from #TEMPMONTHLYATTENDANCE
	drop table #TEMPPROCESSEDDATA
	drop table #TEMPMONTHLYATTENDANCE
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <24-10-2016>
-- Description:	<Getting Non Processed Raw data details for process>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT top 1000 Clk_Id,Clk_CardId,Clk_DeviceId,Clk_Date,Clk_Time,Clk_Type FROM TA_Tbl_Clk_RawData
	WHERE Clk_Flag = 0 AND Clk_Process = 0 and ReasonId!=6 ORDER BY Clk_Date+CLK_TIME
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GettingOTRoundOffValuesForService] 7,214,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]
	-- Add the parameters for the stored procedure here
	@inShiftSettingId int,
	@inOvertimeMins int,
	@inIsOTRoundOff bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--insert into roundOffOT values(@inShiftSettingId,@inOvertimeMins,@inIsOTRoundOff)
	if(@inIsOTRoundOff=1)
		begin
			-- Insert statements for procedure here
			Declare @StartMins float
			Declare @EndMins float
			Declare @RoundedAs nvarchar(5)
			Declare @Total int
			Declare @Start int
			Declare @dblModValue float
			Declare @dblRoundedOverTimeMins float
			Create table #Temp_TA_Tbl_OTRoundoffSettings(id int identity(1,1),StartMins float,EndMins float,RoundedAs nvarchar(5))
			insert into #Temp_TA_Tbl_OTRoundoffSettings
			SELECT StartMins,EndMins,RoundedAs FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId =@inShiftSettingId
			set @Start=1
			select @Total=COUNT(*) from #Temp_TA_Tbl_OTRoundoffSettings
			set @dblRoundedOverTimeMins=0	
			while @Start<=@Total
				begin
					SELECT @StartMins=StartMins,@EndMins=EndMins,@RoundedAs=RoundedAs FROM #Temp_TA_Tbl_OTRoundoffSettings WHERE id =@Start
					set @dblModValue = @inOvertimeMins % 60;
						
					if (@StartMins <= @dblModValue and @dblModValue <= @EndMins)
						begin
							set @dblRoundedOverTimeMins =CONVERT(float,@inOvertimeMins) + (dbo.ConvertHoursToMinites(@RoundedAs) - @dblModValue);
						end
						set @Start=@Start+1
				end
			if(@dblRoundedOverTimeMins=0)
				begin
					set @dblRoundedOverTimeMins=@inOvertimeMins		
				end					
		end
	else
		begin
			set @dblRoundedOverTimeMins=@inOvertimeMins
		end
	select @dblRoundedOverTimeMins as RoundedOff
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOverTimeParametersForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingOverTimeParametersForService]
	-- Add the parameters for the stored procedure here
	@intCompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if((SELECT COUNT(*) FROM TA_Tbl_ShiftSettings where CompanyId=@intCompanyId)>0)
		begin
			SELECT AfterShiftTime,BeforeShiftTime,MaxHoursBeforeShift,DefinedWorkhrs FROM 
			TA_Tbl_ShiftSettings where CompanyId=@intCompanyId
		end
	else
		begin
			SELECT AfterShiftTime,BeforeShiftTime,MaxHoursBeforeShift,DefinedWorkhrs FROM 
			TA_Tbl_ShiftSettings where CompanyId=-1
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPermissionDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:        R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:   To check Employee applied the permission or not 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPermissionDetailsForService]
      -- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
      @INEMPLOYEE_CODE_ID VARCHAR(50),
      @DTMDATE DATETIME
AS
BEGIN
      SET NOCOUNT ON;
      SELECT      P.PERMISSION_FROMTIME,P.PERMISSION_TOTIME,P.NO_OF_HOURS
                  PERMISSION_ID, P.EMPLOYEE_ID, PERMISSION_APPLIEDDATE, PERMISSION_DATE, 
                  PERMISSION_TYPE,PERMISSION_REASON, 
                  PERMISSION_STATUS, EMP_ID_SANCTION, REMARKS, P.ISDELETED, TIMESTAMP,P.EMP_ID,
                  YEARSETTINGS_ID,P.No_Of_Hours
      FROM TA_TBL_PERMISSION P INNER JOIN TA_TBL_EMPLOYEE E ON E.EMPLOYEE_ID = P.EMPLOYEE_ID
      WHERE E.SWIPECARDNO=@INEMPLOYEE_CODE_ID AND P.PERMISSION_DATE =@DTMDATE AND P.PERMISSION_STATUS='APPROVED' AND P.ISDELETED=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Modified date: <23-11-2016 14.19>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]
AS
BEGIN
	SET NOCOUNT ON;	
	SELECT TOP 1 PunchType,1	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='In'			UNION 
	SELECT TOP 1 PunchType,2	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Out'			UNION
	SELECT TOP 1 PunchType,3	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Shift In'		UNION 
	SELECT TOP 1 PunchType,4	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Shift Out'	UNION
	SELECT TOP 1 PunchType,5	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Break In'		UNION 
	SELECT TOP 1 PunchType,6	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Break Out'	UNION
	SELECT TOP 1 PunchType,7	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Lunch In'		UNION
	SELECT TOP 1 PunchType,8	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Lunch Out'	UNION
	SELECT TOP 1 PunchType,9	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='In Duty'		UNION
	SELECT TOP 1 PunchType,10	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Out Duty'		UNION
	SELECT TOP 1 PunchType,11	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Official In'	UNION
	SELECT TOP 1 PunchType,12	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType='Official Out' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Getting Punch Type Details using device and punch value
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_DeviceId varchar(20),
	@inClk_Type varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select P.PunchType from TA_Tbl_PunchTypes P,TA_Tbl_Terminal T where P.Terminal_Id = T.Terminal_Id 
	and T.Terminal_ReaderID = @inClk_DeviceId and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeRemarks]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeRemarks]
	@Clk_Type nvarchar(10),
	@PunchType nvarchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Punchtype_Remarks from ta_tbl_PunchtypeRemarks 
	where Clk_Type=@Clk_Type and PunchType=@PunchType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingRawDatasForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Get the Raw Data from the TimeCheck Raw Data Table where Clk_Flag = 0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingRawDatasForservice]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Clk_Id,Clk_CardId,Clk_DeviceId,Clk_Date,Clk_Time,Clk_Type FROM TA_Tbl_Clk_RawData WHERE Clk_Flag = 0 AND Clk_Process = 0 ORDER BY Clk_Date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingReceiverDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GettingReceiverDetails 'Leave Application - Apply',787,'Manikandan','2016-09-05 to 2016-09-05','CL','1'
-- Proc_TA_GettingReceiverDetails 'Permission Application - Apply',102,'Rajiv','29-Sep-2016 11:00 To 29-Sep-2016 12:00','','01:00'
-- Proc_TA_GettingReceiverDetails 'OnDuty - Forward',102,'Rajiv','07/Sep/2016 09:00:00 AM To 07/Sep/2016 02:00:00 PM','',''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingReceiverDetails]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(50),
	@Employee_ID varchar(50),
	@EmployeeName varchar(50),
	@LeaveFrom_LeaveTo varchar(50),
	@LeaveType varchar(10),
	@NoofDays varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @TagName VARCHAR(50)
	if(@TemplateName='Leave Application - Apply' or @TemplateName='Leave Application - Forward' or @TemplateName='Leave Application - Approved' or @TemplateName='Leave Application - Rejected')
	begin
		set @TagName='LeaveApplication'
	end
	else if(@TemplateName='Permission Application - Apply' or @TemplateName='Permission Application - Forward' or @TemplateName='Permission Application - Approved' or @TemplateName='Permission Application - Rejected')
	begin
		set @TagName='PermissionApplication'
	end
	else if (@TemplateName='OnDuty - Apply' or @TemplateName='OnDuty - Forward' or @TemplateName='OnDuty - Approved' or @TemplateName='OnDuty - Rejected')
	begin
		set @TagName='OnDuty'
	end
	Declare @TagCount int
	CREATE TABLE #TempTags(id INT IDENTITY(1,1),Tags VARCHAR(max))
	CREATE TABLE #TempTagPosition(id int identity(1,1),Tag varchar(500),position int)
	CREATE TABLE #TempTagPositionFinal(id int identity(1,1),Tag varchar(500),position int,ColumnNames varchar(20))
	create table #TempFinal(id int identity(1,1),EmployeeName varchar(250),EmployeeId varchar(50),FromAndTo varchar(50),Type varchar(10),Days varchar(10))
	insert into #TempFinal values(@EmployeeName,@Employee_ID,@LeaveFrom_LeaveTo,@LeaveType,@NoofDays)
	--select * from #TempFinal
	INSERT INTO #TempTags
	SELECT Tags FROM Ta_Tbl_SMSTags WHERE TemplateName=@TagName and Tags!='{User Name}'
	set @TagCount=(select COUNT(*) from #TempTags)
	--select * from #TempTags
	Declare @Tags varchar(500)
	declare @Start int
	set @Start=1	
	while @Start<=@TagCount
	begin		
		select @Tags=Tags from #TempTags where id=@Start
		--select @Tags
		insert into #TempTagPosition 
		select @Tags,CHARINDEX(@Tags,Tags) from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		and CHARINDEX(@Tags,Tags)!=0
		set @Start=@Start+1
	end	
	insert into #TempTagPositionFinal	
	select Tag,position,
	case	when Tag='{Employee ID}'	then 'EmployeeId'
			when Tag='{Employee Name}'	then 'EmployeeName'
			when Tag='{Leave From - Leave To}' or Tag='{Permission From - Permission To}' or Tag='{OnDuty From - OnDuty To}'	then 'FromAndTo'
			when Tag='{Leave Type}'	then 'Type'
			when Tag='{No.of Days}' or Tag='{No.of Hrs}' then 'Days'			
	end
	from #TempTagPosition order by position
	--select * from #TempTagPosition
	Declare @Totalrecord int
	set @Totalrecord=(select COUNT(*) from #TempFinal)
	declare @i int
	set @i=1
	Create table #FinalStringTable(id int identity(1,1),FinalString varchar(max))
	Declare @TagName1 varchar(20)
	Declare @TagName2 varchar(20)
	Declare @TagName3 varchar(20)
	Declare @TagName4 varchar(20)
	Declare @TagName5 varchar(20)
	select @TagName1=ColumnNames from #TempTagPositionFinal where id=1
	select @TagName2=ColumnNames from #TempTagPositionFinal where id=2
	select @TagName3=ColumnNames from #TempTagPositionFinal where id=3
	select @TagName4=ColumnNames from #TempTagPositionFinal where id=4
	select @TagName5=ColumnNames from #TempTagPositionFinal where id=5
	while @i<=@Totalrecord
	begin		
		Declare @DynamicSQL varchar(max)
		set @DynamicSQL=''		
		set @DynamicSQL=@DynamicSQL+'select '
		if(@TagName1!='')
		begin
			set @DynamicSQL=@DynamicSQL+@TagName1
		end
		if(@TagName2!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName2
		end
		if(@TagName3!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName3
		end
		if(@TagName4!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName4
		end
		if(@TagName5!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName5
		end
		set @DynamicSQL=@DynamicSQL+' From #TempFinal where id='+CONVERT(varchar(max),@i)
		Insert into #FinalStringTable
		Execute(@DynamicSQL)		
		set @i=@i+1
	end
	Declare @FinalString nvarchar(max)
	select @FinalString=coalesce(@FinalString+',',' ')+isnull(FinalString,'') from #FinalStringTable
	--select @FinalString
	if(@FinalString!='')
	begin
		select Message+@FinalString as Message,@FinalString as ExceptionEmployees,@TemplateName as TemplateName
		from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName and Status=1	
	end
	else
	begin
		select '' Message,'' ExceptionEmployees,@TemplateName as TemplateName
	end
	select E.Employee_FirstName+' '+E.Employee_LastName as Receivers,E.SwipeCardNo,E.Mobile_Number from TA_Tbl_Employee E
	 where UserGroup_Id in(
	select Usergroupid from Ta_Tbl_SMSReceivers SR
	inner join Ta_Tbl_SMSTemplates ST on SR.TemplateId=ST.id
	where TemplateName=@TemplateName and ST.Status=1) and E.Isdeleted=0 and E.Employee_Status=1
	and E.SwipeCardNo!='18000000'
    -- Insert statements for procedure here
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingResponseStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Manikandan.R
-- Create date: 14-03-2014
-- Description:	GettingResponseStatus
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingResponseStatus]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_LicenseRequestDetail 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting all companies shift details
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForService]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Shift_Id,Level_Id,Shift_StartTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_GraceInTime,Shift_EndTime,Shift_GraceOutTime,DefaultShift,ShiftType,[24HrsShift] FROM TA_Tbl_Shift WHERE IsDeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForSMS]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForSMS]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Shift where Isdeleted=0 and (Shift_Name!='No Shift' or Shift_ShortName!='NOS')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 29-12-2015
-- Description:	Getting Shift Details using Employee Swipe card Number
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]
@EmployeeCodeId varchar(50)
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	Declare @levelId int	
	set @levelId=
	(
		SELECT top 1 EL.LEVELID FROM 
		(
			SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EMPLOYEEID,EMP.Employee_Code_Id FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 	
			WHERE EMP.ISDELETED=0 and Employee_Code_Id=@EmployeeCodeId
			group by EmployeeId,Employee_Code_Id
		) ELEVEL
		INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID	
		AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(getdate() AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
	)
	while((select parentId from Ta_Tbl_levelDetails where id=@levelId)!=0)
	begin
		select @levelId=parentId from Ta_Tbl_levelDetails where id=@levelId
	end
	Declare @ShiftPatternExist int
	Declare @ShiftRosterExist int
	select @ShiftPatternExist=Pattern,@ShiftRosterExist=Roster from TA_Tbl_ApprovalSettings where CompanyId=@levelId
	Select Employee_Id,Employee_FirstName + ' ' + Employee_LastName AS 'EmployeeName',@ShiftPatternExist as pattern,@ShiftRosterExist as Roaster
	from TA_Tbl_Employee Where Isdeleted=0 and Employee_Code_Id=@EmployeeCodeId
	select Shift_Id,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName from TA_Tbl_Shift where Level_Id=@levelId and Isdeleted=0
	select * from TA_Tbl_ShiftPattern where Level_Id=@levelId and Isdeleted=0
	select * from TA_Tbl_ShiftRoaster where Level_Id=@levelId and Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_ShiftSettings where CompanyId=-1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Shift Setting Details of All companies>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT	SHIFTSETTINGID,COMPANYID,MAXHOURSBEFORESHIFT,MAXHOURSAFTERSHIFT,SHIFTBREAK,SHIFTMAXBREAKHOURS,
			MONTHLYWORKINGHOURS,WEEKLYWORKINGHOURS,EMPID,HOLIDAYOT,WEEKOFFOT,OTOPTION,
			CONVERT(VARCHAR(25),DEFAULTMONTHCLOSUREDATE,120) AS MONTHCLOSURE_ENDDATE,ISFLEXIBLE,FLEXIBLEFLAG,
			OTROUNDOFFENABLE,FULLDAYATTENDANCEHRS,HALFDAYATTENDANCEHRS,HALFDAYATTENDANCE,FULLDAYATTENDANCE, WEEKLYOFFSTARTHOURS, 
			IGNOREDUPLICATEPUNCH,PUNCHINTERVAL,AFTERSHIFTTIME,BEFORESHIFTTIME,DEFINEDWORKHRS,NOOFSUCCESSIVEDAYSINYEAR,
			COMPENSATIONVALITITYDAYS,VAILDITYCOMPOFFDAYS,HALFDAYCOMPOFF, FULLDAYCOMPOFF,LATEENTRY,EARLYENTRY, 
			EARLYEXIT,LATEEXIT, TIMESTAMP,TIMESTAMP1,ISLUNCHDEDUCTION,LUNCHDEDUCTIONHOURS,FLEXI_AFTERSHIFTTIME,
			FLEXI_BEFORESHIFTTIME,FLEXI_DEFINEDWORKHRS,DefaultLunchHours, MaxLunchHours, MaxWorkPlaceInHours, 
			MaxHoursBeforeShift_24HrsShift, WeeklyOffStartHours_24HrsShift, CumulativeWeekStartDay, CumulativeWeekEndDay, MonthStartDay, MonthEndDay
	FROM TA_TBL_SHIFTSETTINGS
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingSMSScheduleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-09-2016>
-- Description:	<Getting Schedule Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingSMSScheduleDetails]
	-- Add the parameters for the stored procedure here	
	@TemplateName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here    
	select count(*) from Ta_Tbl_SMSTemplates ST 
	inner join Ta_Tbl_SMSReceivers SR on ST.id=SR.TemplateId
	where TemplateName=@TemplateName and Status=1	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting Terminal Data type database details
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]
	-- Add the parameters for the stored procedure here
	@FileType varchar(30),
	@TerminalDatatypeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select	ConnectionString,TableName,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_DateTime,DateTimeFormat,RDBMS_Date,DateFormat,
			RDBMS_Time,TimeFormat,RDBMS_Type,RDBMS_MDB_Flag,RDBMS_TransactionIdentifier,TransactionIdentifierBit,TransactionIdentifierValue,
			IsEncrypted from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDatatypeID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedData]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT P.Process_Rec_ID,P.Employee_Code_Id,P.Date,P.InTime,P.OutTime,P.Attendance,P.Status,E.Employee_Id,E.OT_Eligible,
	E.CompOff_Eligible,E.IsFlexible,EL.LevelId FROM TA_Tbl_ProcessedData P  INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id  
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId=E.Employee_Id INNER JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId  
	WHERE P.ProcessFlag = 0 and E.IsDeleted = 0 and P.Date<getdate() ORDER BY P.Employee_Code_Id,P.Date 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedDataForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Un processed data details
-- drop procedure [dbo].[Proc_Ta_GettingUnProcessedData]
-- exec Proc_Ta_GettingUnProcessedDataForService 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedDataForService]
 @CompanyId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT P.Process_Rec_ID,P.Employee_Code_Id,
	convert(varchar(25), P.Date,120) as Date,P.InTime,P.OutTime,P.Attendance,P.Status,E.Employee_Id,E.OT_Eligible,
	E.CompOff_Eligible,E.IsFlexible,
	Case when (select Top 1 Emp_LevelID From TA_Tbl_LevelChanges where (Cast(Convert(date,p.Date) as varchar(20)) between Transfer_FromDate and Transfer_ToDate) and EmployeeId=E.Employee_Id)=EL.LevelId then EL.LevelId Else  isNull((Select Top 1 Emp_LevelId From TA_Tbl_LevelChanges where (p.Date between Transfer_FromDate and isNull(Transfer_ToDate,Transfer_FromDate)) and EmployeeId=E.Employee_Id) ,EL.LevelId)  End as LevelId
	FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId=E.Employee_Id 
	Left JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId 
	WHERE P.ProcessFlag = 0 and E.IsDeleted = 0 and [dbo].[Func_TA_GetParentIds](EL.LevelId)=@companyId
	ORDER BY P.Employee_Code_Id,P.Date
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingVersionNumber]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		Manikandan.R
-- Create date: 14-03-2014
-- Description:	For Online licensing, To get the version number
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingVersionNumber]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select substring(RIGHT(ApplicationVersionName,charindex('_',reverse(ApplicationVersionName))-1),1,LEN(ApplicationVersionName))as versionNumber from TA_Tbl_Version 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--	Proc_TA_GetTitleDetails 'SuperAdmin',''
--Modified By		:  Manjula.P  
--Modified On		:  06-Jan-2014
--Descriptions		:  Adding LD.name for displaying levels details

CREATE    Proc [dbo].[Proc_TA_GetTitleDetails] 
(
   @UserGroupName	nVarchar(250), 
   @Designation		nVarchar(100) 
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	SELECT	distinct T.TitleId,
			T.TitleName,
			T.TitleDescription,
			LD.name as LevelName,
			P.PolicyName,
			G.Grade_Name,
			T.IsDeleted,
			G.Grade_Level,
			flag=case when isnull(ED.DesignationID,0)=0 then 0 else 1 end
	FROM TA_Tbl_Title T  
	Left JOIN TA_Tbl_LevelDetails LD ON LD.Id = T.LevelID  
	Left JOIN #LevelRights ON #LevelRights.LevelId = T.LevelID 
	LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID 
	LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID 
	LEFT OUTER join TA_tbl_EmployeeDesignation ED on T.TitleId=ED.DesignationID
	where (isnull(@Designation,'')='' or T.TitleName like @Designation+'%') and(@UserGroupName='Superadmin' or T.IsDeleted=0)
	order by T.TitleName
	drop table #LevelRights
END

Select * From TA_tbl_EmployeeDesignation
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleFirstDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_GetTitleFirstDetailsById]  
(   
	@TitleId int,
	@UserGroupName nVarchar(250)  
)   
As   
BEGIN  
	DECLARE @Isdel int  
	SET @Isdel=0  
	IF(@UserGroupName = 'SuperAdmin')
	BEGIN
		SELECT T.TitleId,T.TitleName,T.TitleDescription,T.levelID,L.Name,T.LeavePolicyId,P.PolicyName,T.GradeID,G.Grade_Name,T.IsDeleted FROM TA_Tbl_Title T  
		LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=T.LevelID  
		LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID  
		LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID  
		WHERE TitleId=@TitleId  
	END
	ELSE
	BEGIN
		SELECT T.TitleId,T.TitleName,T.TitleDescription,T.levelID,L.Name,T.LeavePolicyId,P.PolicyName,T.GradeID,G.Grade_Name,T.IsDeleted FROM TA_Tbl_Title T  
		LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=T.LevelID  
		LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID  
		LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID  
		WHERE T.IsDeleted=@Isdel AND TitleId=@TitleId  
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Proc_TA_GetTitleMappingDetails] as  
SELECT  C.Company_Name,R.Region_Name,B.Branch_Name,D.Department_Name,S.Section_Name,T.TitleName,T.TitleId,A.[id] FROM TA_Tbl_TitleMapping A  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id          
   join TA_Tbl_Region R ON R.Region_Id=A.Region_Id          
   join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id          
   JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id  
   JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id  
   JOIN TA_Tbl_Title T ON T.TitleId=A.TitleId  
WHERE A.IsDeleted=1  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_GetTitleMappingDetailsById]    
(     
 @id int   
)     
As    
 DECLARE @Isdel int    
 SET @Isdel=1    
BEGIN    
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,
		S.Section_Name,S.Section_Id,T.TitleName, T.TitleId FROM TA_Tbl_TitleMapping A    
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id            
   join TA_Tbl_Region R ON R.Region_Id=A.Region_Id            
   join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id            
   JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id    
   JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id    
   JOIN TA_Tbl_Title T ON T.TitleId=A.TitleId    
WHERE A.IsDeleted=1  AND A.id=@id    
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleNameById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_GetTitleNameById] as   
SELECT TitleId,TitleName FROM TA_Tbl_Title Where IsDeleted=1 
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Manikandan
-- Create date: 25-07-2017
-- Description:	Getting Present and Leave days for current month
-- [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays] 7588,'06/09/2020','06/09/2020'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]
	@EmployeeCodeID VARCHAR(50),
	@selectedDate VARCHAR(30),
	@selectedtodate VARCHAR(30)
AS
BEGIN
	DECLARE @fromDate DATETIME
	DECLARE @toDate DATETIME
	DECLARE @CurrentDate DATETIME
	DECLARE @ClockInTime VARCHAR(30)
	DECLARE @ClockOutTime VARCHAR(30)
	DECLARE @previousDayShift INT	
	DECLARE @Shift_StartTime VARCHAR(10)
	DECLARE @Shift_EndTime VARCHAR(10)
	DECLARE @previousDate DATETIME
	DECLARE @Final_LocationName varchar(500)
	Declare @isNightshift bit
	set @isNightshift=0
	
	SET @CurrentDate=DATEADD(d,0,DATEDIFF(d,0,GETDATE()))
	SET @fromDate=DATEADD(d,-DATEPART(d,CAST(CONVERT(VARCHAR(11),@selectedDate)as DATETIME))+1,CAST(CONVERT(VARCHAR(11),@selectedDate)as DATETIME))
	IF(@selectedtodate='' OR @selectedtodate IS NULL)
	BEGIN
		SET @todate=DATEADD(d,-DATEPART(d,@selectedDate),DATEADD(MONTH,1,@selectedDate))
	END
	ELSE 
	BEGIN
		SET @todate=CONVERT(DATETIME,@selectedtodate)
	END
	
	SELECT	@ClockInTime=	CASE WHEN (InTime IS not null and InTime<>'00:00' and InTime!='')	THEN @CurrentDate+InTime	END,
			@ClockOutTime=	CASE WHEN (OutTime IS not null and OutTime<>'00:00' and OutTime!='')THEN @CurrentDate+OutTime	END,
			@Final_LocationName=''
	FROM TA_Tbl_ProcessedData WHERE  Employee_Code_Id=@EmployeeCodeID and (Date=@CurrentDate)
	
	
	IF((@ClockInTime IS NULL OR @ClockInTime='' OR @ClockInTime='00:00') and (@ClockOutTime IS NULL OR @ClockOutTime='' OR @ClockOutTime='00:00'))
	BEGIN
		SET @previousDate=DATEADD(d,-1,@CurrentDate)
		SELECT @previousDayShift=Shift_Id FROM TA_Tbl_ProcessedData WHERE  Employee_Code_Id=@EmployeeCodeID and (Date=@previousDate)
		SELECT @Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@previousDayShift and Isdeleted=0
		IF(RIGHT(@Shift_StartTime,2)='PM' and RIGHT(@Shift_EndTime,2)='AM')
		BEGIN
			SELECT @ClockInTime=@previousDate+InTime,@ClockOutTime=@previousDate+OutTime FROM TA_Tbl_ProcessedData WHERE  Employee_Code_Id=@EmployeeCodeID and 
			(Date=@previousDate)
			set @CurrentDate=@previousDate
			set @isNightshift=1
		END
	END	
	DECLARE @Manual_ClockInTime VARCHAR(30)
	DECLARE @Manual_ClockOutTime VARCHAR(30)
	DECLARE @Manual_InLocationName varchar(500)
	DECLARE @InLatitude_value varchar(20)
	DECLARE @InLongitude_value varchar(20)
	
	DECLARE @Manual_OutLocationName varchar(500)
	DECLARE @OutLatitude_value varchar(20)
	DECLARE @OutLongitude_value varchar(20)
	
	
	SELECT @Manual_ClockInTime=MIN(ManualTimeEntry_InDate+' ' + ManualTimeEntry_InTime) ,
		   @Manual_InLocationName=Clock_Address,
		   @InLatitude_value=Latitude_value,
		   @InLongitude_value=Longitude_value 
	FROM TA_Tbl_ManualTimeEntry 
	WHERE ManualTimeEntry_Employee_Id=@EmployeeCodeID and (ManualTimeEntry_InDate=@CurrentDate) 
	and ManualTimeEntry_InPunchType='Shift In' and IsImported=2
	group by Latitude_value,Longitude_value,Clock_Address
	
	if(@isNightshift=1)
	begin
		set @CurrentDate=DATEADD(d,-1,@CurrentDate)
	end
	
	SELECT @Manual_ClockOutTime=max(ManualTimeEntry_OutDate+' '+ManualTimeEntry_OutTime) ,
			@Manual_OutLocationName =case when max(ManualTimeEntry_OutDate+' '+ManualTimeEntry_OutTime) Is not null then Clock_Address else '' end,
		   @OutLatitude_value=Latitude_value,
		   @OutLongitude_value=Longitude_value 
	FROM TA_Tbl_ManualTimeEntry 
	WHERE ManualTimeEntry_Employee_Id=@EmployeeCodeID and (ManualTimeEntry_OutDate=@CurrentDate)
	and ManualTimeEntry_OutPunchType='Shift Out' and IsImported=2
	group by Latitude_value,Longitude_value,Clock_Address
	
	IF(@ClockInTime is not null and @ClockInTime<>'' and @ClockInTime!='00:00')
	BEGIN
		IF(@Manual_ClockInTime is not null and @Manual_ClockInTime<>'' and @Manual_ClockInTime!='00:00')
		BEGIN
			IF(CONVERT(DATETIME,@Manual_ClockInTime)<CONVERT(DATETIME,@ClockInTime))
			BEGIN
				SET @ClockInTime=@Manual_ClockInTime
			END
		END
	END
	IF(@ClockOutTime is not null and @ClockOutTime<>'' and @ClockOutTime!='00:00')
	BEGIN
		IF(@Manual_ClockOutTime is not null and @Manual_ClockOutTime<>'' and @Manual_ClockOutTime!='00:00')
		BEGIN
			IF(CONVERT(DATETIME,@Manual_ClockOutTime)>CONVERT(DATETIME,@ClockOutTime))
			BEGIN
				SET @ClockOutTime=@Manual_ClockOutTime
			END
		END
	END
	
	if(@ClockInTime is null or @ClockInTime='')
	begin
		SET @ClockInTime=@Manual_ClockInTime
	end
	
	if(@ClockOutTime is null or @ClockOutTime='')
	begin
		SET @ClockOutTime=@Manual_ClockOutTime
	end
	
	
	SELECT PresentDays=ISNULL(SUM(CASE WHEN FNAttendanceCode='Present' THEN 0.5 ELSE 0 END),0)+
		   ISNULL(SUM(CASE WHEN ANAttendanceCode='Present' THEN 0.5 ELSE 0 END),0),
		   leaveDays=ISNULL(SUM(CASE WHEN FNAttendanceCode in('Present','Absent','Holiday','RH','Weekly Off') THEN 0 ELSE 0.5 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode in('Present','Absent','Holiday','RH','Weekly Off') THEN 0 ELSE 0.5 END),0),
		   AbsentDays=ISNULL(SUM(CASE WHEN FNAttendanceCode='Absent' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode='Absent' THEN 0.5 ELSE 0 END),0),
		   OffDays=ISNULL(SUM(CASE WHEN FNAttendanceCode='Weekly Off' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode='Weekly Off' THEN 0.5 ELSE 0 END),0),
		   HolidayDays=ISNULL(SUM(CASE WHEN FNAttendanceCode='Holiday' THEN 0.5 WHEN FNAttendanceCode='RH' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode='Holiday' THEN 0.5 WHEN ANAttendanceCode='RH' THEN 0.5 ELSE 0 END),0) ,
		   TotalWorkingDays=ISNULL(SUM(CASE WHEN FNAttendanceCode not in('Holiday','Weekly Off','RH') THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode not in('Holiday','Weekly Off','RH') THEN 0.5 ELSE 0 END),0),	   
		   ClockInTime=CASE WHEN @ClockInTime IS null THEN '-' ELSE ISNULL(SUBSTRING(@ClockInTime,13,5),'-')+ ' ' +ISNULL(SUBSTRING(@ClockInTime,18,2),'') END,
		   ClockOutTime=CASE WHEN @ClockOutTime IS null THEN '-' ELSE ISNULL(SUBSTRING(@ClockOutTime,13,5),'-')+ ' ' +ISNULL(SUBSTRING(@ClockOutTime,18,2),'') END,
		   ClkInLocName=@Manual_InLocationName,
		   ClkOutLocName=@Manual_OutLocationName,
		   ClkInLatValue=@InLatitude_value,
		   ClkInLongValue=@InLongitude_value,
		   ClkOutLatValue=@OutLatitude_value,
		   ClkOutLongValue=@OutLongitude_value
	FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id=@EmployeeCodeID and (Date>=@fromDate and Date<=@toDate)and ProcessFlag=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_MappingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Proc_TA_GetTransportation_MappingDetails] as          
SELECT  A.id,A.VehicleId,A.RouteId,B.VehicleNo,C.Route_Name        
FROM  TA_Tbl_Transportation_Mapping A        
INNER JOIN TA_Tbl_Transportation_Vehicle B ON B.VehicleId=A.VehicleId         
JOIN TA_Tbl_RouteMaster C ON C.[Id]=A.RouteId  
Where A.IsDeleted=1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name 	:	Proc_TA_GetTransportation_RouteDetails        
Description 	:	Get Transportation Route Details    
Tables Included :	TA_Tbl_RouteMaster and TA_Tbl_Transportation_Vehicle      
Created By 	:	        
Created On 	:	    
Modified By 	:	Prabakaran.P    
Modified On 	:	07-Feb-08   
*/  
CREATE  Proc [dbo].[Proc_TA_GetTransportation_RouteDetails] 
	@usergroupname nvarchar(50)
as     
Create table #TempTransportation(Id int,Route_Name nvarchar(100),Route_Description varchar(500),VehicleNo nvarchar(40),IsDeleted bit,flag int)
if(@usergroupname='SuperAdmin')
	BEGIN
		Insert into #TempTransportation
		SELECT R.Id as Id,R.Route_Name as Route_Name,R.Route_Description as Route_Description,tv.VehicleNo as VehicleNo,R.IsDeleted,0
		FROM TA_Tbl_RouteMaster R
		inner join TA_Tbl_Transportation_Vehicle tv on tv.VehicleId=R.VehicleID
	END
else
	BEGIN          
		Insert into #TempTransportation
		SELECT R.Id as Id,R.Route_Name as Route_Name,R.Route_Description as Route_Description,tv.VehicleNo as VehicleNo,R.IsDeleted,0
		FROM TA_Tbl_RouteMaster R
		inner join TA_Tbl_Transportation_Vehicle tv on tv.VehicleId=R.VehicleID
		Where R.IsDeleted= 0  and tv.Isdeleted=0
	END
	update #TempTransportation set flag =1 from #TempTransportation TT inner join
	ta_tbl_employee E on E.Bus_Id=TT.Id --where E.Isdeleted=0
	select * from #TempTransportation
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetailsByID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Proc [dbo].[Proc_TA_GetTransportation_RouteDetailsByID] (@ID int) as      
SELECT R.[Id],R.Level_Id,R.VehicleID,
V.VehicleNo,L.Name,R.Route_Name,R.Route_Description FROM TA_Tbl_RouteMaster R
LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle V ON V.VehicleId=R.VehicleID
LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=R.Level_Id
Where R.id=@ID
 --Where R.IsDeleted= 0 AND R.id=@ID
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_VehicleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified by	:	P.Prabakaran
Modified on	:	7-Feb-08
*/
CREATE  Proc [dbo].[Proc_TA_GetTransportation_VehicleDetails]
@UserGroupName nvarchar(250)
as
Create table #TempTransportation(VehicleId int,VehicleNo nvarchar(40),VehicleDescription nvarchar(500),Isdeleted bit,flag int)
if(@UserGroupName='SuperAdmin')	
	BEGIN
		insert into #TempTransportation
		SELECT VehicleId,VehicleNo,VehicleDescription,Isdeleted,0 FROM TA_Tbl_Transportation_Vehicle 
	END
else
	BEGIN
		insert into #TempTransportation
		SELECT VehicleId,VehicleNo,VehicleDescription,Isdeleted,0 FROM TA_Tbl_Transportation_Vehicle Where IsDeleted=0
	END
	Update #TempTransportation set flag=1 from #TempTransportation TT inner join TA_Tbl_RouteMaster Rm on TT.VehicleId=Rm.VehicleID 	where TT.Isdeleted =0
	Select * from #TempTransportation
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Proc [dbo].[Proc_TA_GetTransportationDetails] as
SELECT id,VehicleNo,RouteName FROM TA_Tbl_Transportation Where IsDeleted=1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Proc [dbo].[Proc_TA_GetTransportationDetailsById] (@id int) as
SELECT A.[id],A.VehicleNo,A.RouteName, B.Company_Name, C.Region_Name , D.Branch_Name
FROM TA_Tbl_Transportation A, TA_Tbl_CompanyDetails B, TA_Tbl_Region C ,TA_Tbl_Branch D
Where A.IsDeleted=1 AND A.Company_Id = B.Company_Id AND A.Region_Id = C.Region_Id AND A.Branch_Id = D.Branch_Id
And A.[id]=@id
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Proc [dbo].[Proc_TA_GetTransportationMappingDetails] as
SELECT id,VehicleId,RouteId,Company_Id,Region_Id,Branch_Id FROM TA_Tbl_Transportation_Mapping Where IsDeleted=1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_GetTransportationMappingDetailsById]
(	
	@id int
) 
As
	DECLARE @Isdel int
	SET @Isdel=1
BEGIN
	SELECT VehicleId,RouteId,Company_Id,Region_Id,Branch_Id FROM TA_Tbl_Transportation_Mapping WHERE IsDeleted=@Isdel AND id=@id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Procedure [dbo].[Proc_TA_GetTransportationRouteDetailsById]        
(         
 @RouteId int        
)         
As               
BEGIN        
-- SELECT Company_Id,Region_Id,Branch_Id,Route_Name,Route_Description FROM TA_Tbl_RouteMaster WHERE  IsDeleted=@Isdel AND [Id]=@RouteId        
SELECT C.Company_Name,R.Region_Name,B.Branch_Name,RO.Route_Name ,RO.Route_Description       
 FROM TA_Tbl_Transportation_Mapping A        
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id        
  join TA_Tbl_Region R ON R.Region_Id=A.Region_Id        
  join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id        
  --join TA_Tbl_RouteMaster V ON V.VehicleId=A.VehicleId        
  join TA_Tbl_RouteMaster RO ON RO.Id=A.RouteId         
 --Where A.RouteId=@RouteId AND RO.IsDeleted=1 -- AND RO.IsMapped=1  
  Where A.RouteId=@RouteId 
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
Procedure Name 	:	Proc_TA_GetTransportationRouteMasterDetailsById    
Description 	:	Get Transportation Route Details based on Route Id
Tables Included :	TA_Tbl_Leveldetails,TA_Tbl_RouteMaster and TA_Tbl_Transportation_Vehicle  
Created By 	:	    
Created On 	:	
Modified By 	:	Prabakaran.P
Modified On 	:	07-Feb-08    
*/
CREATE   Procedure [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]
(               
 @RouteId int              
)               
As                     
BEGIN              
SELECT V.VehicleNo,R.Level_Id,L.Name,R.Route_Name ,R.Route_Description,(CASE WHEN R.Isdeleted = 0 THEN 'False' ELSE 'True' END) Isdeleted
FROM TA_Tbl_RouteMaster R              
LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle V ON V.VehicleId=R.VehicleID     
LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=R.Level_Id  
Where R.Id =@RouteId   
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified by	:	P.prabakaran
Modified on	:	07-Feb-08
*/
CREATE   Procedure [dbo].[Proc_TA_GetTransportationVehicleDetailsById]
(	
	@VehicleId int
) 
As
	DECLARE @Isdel int
	--SET @Isdel=0
BEGIN
	--SELECT VehicleId,VehicleNo,VehicleDescription FROM TA_Tbl_Transportation_Vehicle WHERE IsDeleted=@Isdel AND VehicleId=@VehicleId
	SELECT VehicleId,VehicleNo,VehicleDescription,IsDeleted FROM TA_Tbl_Transportation_Vehicle WHERE VehicleId=@VehicleId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]                  
(                   
 @VehicleId int                  
)                   
As                  
BEGIN             
SELECT C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,RO.Route_Name , RO.ID,V.VehicleNo,V.VehicleId        
 FROM TA_Tbl_Transportation_Mapping A                  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                  
  join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                  
  join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id             
  join TA_Tbl_RouteMaster RO ON RO.Id=A.RouteId                   
  join TA_Tbl_Transportation_Vehicle V ON V.VehicleId=A.VehicleId             
 Where A.VehicleId=@VehicleId          
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTrnsfrrdEmpDtils]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetTrnsfrrdEmpDtils]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT TrnsfrID, Emp_AutoID, Trnsfr_frm, Trnsfr_To, Trnsfr_EtyDteTme, Trnsfr_Dte, Etry_RsdBy, NwDsgtonID, NwReprtngTo, NwApprvlAuthrty, Remarks, IsImprtd, Trnsfr_status FROM Ta_tbl_Transfer
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_GetUnProcessedData
Description : This Procedure is to get the Unprocesseddata from the ProcessedData Table
Tables Included : TA_Tbl_ProcessedData, TA_Tbl_Employee  
Created By : Kumuthini.L
Created On : 16-Sep-2008
Modified By :
Modified On :
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetUnProcessedData] 
(
	@Type nVarchar(5),
	@Employee_Code_Id nVarchar(25),
	@FromDate nVarchar(12),
	@ToDate nVarchar(12)
)
 AS
IF(@Type = 'All')
BEGIN
	SELECT P.Process_Rec_ID,P.[Date],P.InTime,P.OutTime,P.Attendance,E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.OT_Eligible 
	FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id 
	WHERE P.ProcessFlag = 0 AND P.[Date] BETWEEN @FromDate AND @ToDate
END
IF(@Type = 'P')
BEGIN
	SELECT P.Process_Rec_ID,P.[Date],P.InTime,P.OutTime,P.Attendance,E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.OT_Eligible 
	FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id 
	WHERE P.ProcessFlag = 0 AND E.Employee_Code_Id = @Employee_Code_Id AND P.[Date] BETWEEN @FromDate AND @ToDate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_GetUnProcessedDataCountMonthClsoure]70,'2012/01/01','2012/01/31','<NewDataSet />','SuperAdmin',70
CREATE    PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountMonthClsoure '1','2/1/2012','02/22/2012','<NewDataSet></NewDataSet>','SuperAdmin',1  
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds xml,
@UserGroupName varchar(250), 
@ParentId int 
as  
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	create table #ReprocessEmployees(EmployeeCodeId varchar(15))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	create table #tblProcessRaw(intCount bigint)
	create table #tblProcessProcessData(intCount bigint)
	create table #tblProcessLeave(intCount bigint)
	create table #tblProcessPermission(intCount bigint)
	create table #tblProcessManualEntry(intCount bigint)
	CREATE TABLE #TempProcessedData([Process_Rec_ID] bigint,[Employee_Code_Id] nvarchar(20),[Date] datetime,[Shift_Id] int,
	[InTime] nvarchar(25),[OutTime] nvarchar(25),[HrsWork] nvarchar(10),[HrsOT] nvarchar(10),[NormOT] nvarchar(10),[OffOT] nvarchar(10),[HolOT] nvarchar(10),[EarlyOut] nvarchar(10),
	[LateIn] nvarchar(10),[Attendance] nvarchar(20),[WorkHrs] nvarchar(10),[HrsLess] nvarchar(10),[HrsExtra] nvarchar(10),[LateInMins] float,[EarlyOutMins] float,[ExtraMins] float,
	[OtMins] float,[OvertimeStatus] nvarchar(50),[TotalDays] numeric(18, 1),[LeaveCode] nvarchar(20),[LateEntryReason] nvarchar(260),[EarlyOutReason] nvarchar(260),[ProcessFlag] bit,[Status] nvarchar(50),
	[FNAttendanceCode] nvarchar(15),[ANAttendanceCode] nvarchar(15))
	/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
	(
	[Employee_Code_Id] ASC
	) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData([CLK_ID] [bigint] NOT NULL,[CLK_CARDID] [nvarchar](20) NULL,[CLK_DEVICEID] [nvarchar](20) NULL,[CLK_DATE] [datetime] NULL,[CLK_TIME] [nvarchar](25) NULL,[CLK_TYPE] [nvarchar](15) NULL,[CLK_FLAG] [int] NULL,[CLK_PROCESS] [int] NULL,[TimecheckDateTime] [datetime] NULL,[TimeStamp] [datetime] NOT NULL)
	declare @gintRawCount bigint
	declare @gintProcessCount bigint
	declare @gintLeaveCount bigint
	declare @gintPermissionCount bigint
	declare @gintManualEntryCount bigint
	declare @sqlQuery as varchar(8000)  
	declare @sqlQuery1 as varchar(8000) 
	declare @sqlQuery2 as varchar(8000) 
	declare @sqlQuery3 as varchar(8000)
	declare @sqlQuery4 as varchar(8000) 
	declare @Result as varchar(1000) 
	Declare @Index int
	Set @Index = 0;
	EXEC sp_xml_preparedocument @Index OUTPUT, @EmployeeCodeIds
	insert into #ReprocessEmployees (EmployeeCodeId)select EmployeeId from OpenXML(@Index, '/NewDataSet/ReprocessEmployees') With (EmployeeId varchar(15) 'EmployeeId')
	Exec sp_xml_removedocument @Index		  
	insert into #TempProcessedData 
		select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
		[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
		[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
		where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
	insert into #Clk_RawData
		select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
		from TA_Tbl_CLK_RAWDATA
		where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
--select * from #Clk_RawData
--select * from #ReprocessEmployees
--select * from #TempProcessedData
	set @sqlQuery=''  
	set @sqlQuery = 'select Count(*) as Count from TA_TBL_Employee E '  
	set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id '  
	--set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
	--set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '    
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	--set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '    
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery = @sqlQuery + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
		end
	set @sqlQuery = @sqlQuery + ' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'  
	--set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
	set @sqlQuery = @sqlQuery + ' and (LA.Leave_FromDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
	set @sqlQuery = @sqlQuery + ' or LA.Leave_ToDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
	--set @sqlQuery = @sqlQuery + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
	set @sqlQuery = @sqlQuery + ' and (LA.Status IN ( ''Forwarded'',''Pending''))' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery = @sqlQuery + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
	insert into  #tblProcessLeave exec(@sqlQuery)
	set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
	--  set @sqlQuery = @sqlQuery + ' and Month(''' + cast( @dtClosingMonth as varchar(20)) + ''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))'  
	set @sqlQuery1=''  
	set @sqlQuery1 = 'select Count(*) as Count from TA_TBL_Employee E '  
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id '  
	--set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
	--set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id '    
	set @sqlQuery1 = @sqlQuery1 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	--set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery1 = @sqlQuery1 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
		end
	set @sqlQuery1 = @sqlQuery1 + ' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1'  
	--set @sqlQuery1 = @sqlQuery1 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
	set @sqlQuery1 = @sqlQuery1 + ' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
	set @sqlQuery1 = @sqlQuery1 + ' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
	--set @sqlQuery1 = @sqlQuery1 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
	set @sqlQuery1 = @sqlQuery1 + ' and (mt.Clk_Process = ''N'') and (mt.ManualTimeEntry_Status != ''Rejected'')' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
	insert into #tblProcessManualEntry exec(@sqlQuery1)
	set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
	set @sqlQuery2=''  
	set @sqlQuery2 = 'select Count(*) as Count from TA_TBL_Employee E '  
	set @sqlQuery2 = @sqlQuery2 + ' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id '  
	--set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
	--set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery2 = @sqlQuery2 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
		end
	set @sqlQuery2 = @sqlQuery2 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	--set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
	set @sqlQuery2 = @sqlQuery2 + ' AND E.Isdeleted=0'  
	--set @sqlQuery2 = @sqlQuery2 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
	set @sqlQuery2 = @sqlQuery2 + ' and pd.Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
	--set @sqlQuery2 = @sqlQuery2 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
	set @sqlQuery2 = @sqlQuery2 + ' and (pd.ProcessFlag =0 )' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
	insert into  #tblProcessProcessData exec(@sqlQuery2)
	set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
	--select * from #tblProcessProcessData
	set @sqlQuery3=''  
	set @sqlQuery3 = 'select Count(*) as Count from TA_TBL_Employee E '  
	set @sqlQuery3 = @sqlQuery3 + ' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId '  
	--set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
	--set @sqlQuery3 = @sqlQuery3 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery3 = @sqlQuery3 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
		end
	set @sqlQuery3 = @sqlQuery3 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	--set @sqlQuery3 = @sqlQuery3 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
	set @sqlQuery3 = @sqlQuery3 + ' AND E.Isdeleted=0'  
	--set @sqlQuery3 = @sqlQuery3 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
	set @sqlQuery3 = @sqlQuery3 + ' and crd.Clk_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
	--set @sqlQuery3 = @sqlQuery3 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
	set @sqlQuery3 = @sqlQuery3 + ' and (crd.Clk_Flag =0 or crd.Clk_Process =0)' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery3 = @sqlQuery3 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
	insert into  #tblProcessRaw exec(@sqlQuery3)
	set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
	--select * from #tblProcessRaw
	set @sqlQuery4=''  
	set @sqlQuery4 = 'select Count(*) as Count from TA_TBL_Employee E '  
	set @sqlQuery4 = @sqlQuery4 + ' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id '  
	--set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
	--set @sqlQuery4 = @sqlQuery4 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
	set @sqlQuery4 = @sqlQuery4 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id '
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery4 = @sqlQuery4 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
		end
	set @sqlQuery4 = @sqlQuery4 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	--set @sqlQuery4 = @sqlQuery4 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
	set @sqlQuery4 = @sqlQuery4 + ' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1'  
	--set @sqlQuery4 = @sqlQuery4 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
	set @sqlQuery4 = @sqlQuery4 + ' and pm.Permission_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
	--set @sqlQuery4 = @sqlQuery4 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
	set @sqlQuery4 = @sqlQuery4 + ' and (pm.Permission_Status IN ( ''Forwarded'',''Pending''))'  
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery4 = @sqlQuery4 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
	insert into  #tblProcessPermission exec(@sqlQuery4)
	set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
	--select * from #tblProcessPermission 
	set @Result='Non Processed '
	if(@gintRawCount>0)
		begin
			set @Result=@Result + ' Device '
		end 
	if(@gintProcessCount>0)
		begin
			if(@gintRawCount>0)
				begin
					set @Result=@Result + ','
				end
			set @Result=@Result + 'Data Process '
		end
	if(@gintLeaveCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0)
				begin
					set @Result=@Result + ','
				end
			set @Result=@Result + 'Leave'
		end
	if(@gintPermissionCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
				begin
					set @Result=@Result + ','
				end
			set @Result=@Result + 'Permission '
		end
	if(@gintManualEntryCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
				begin
					set @Result=@Result + ','
				end
			set @Result=@Result + 'Manual Entry '
		end
	set @Result=@Result + 'Data Exists'
	if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
		begin
			set @Result=@Result
		end
	else
		begin
			set @Result=''
		end
	drop table #LevelRights
	drop table #EmpLevel
	drop table #ReprocessEmployees
	drop table #tblProcessRaw
	drop table #tblProcessProcessData
	drop table #tblProcessLeave
	drop table #tblProcessPermission
	drop table #tblProcessManualEntry
	drop table #TempProcessedData
	drop table #Clk_RawData
	select @Result as Result
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountMonthClsoure '1,2,3,47,113,133,134,135,137,138,140,150','1/1/2009','05/08/2009',''['emp008','emp009']    
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds xml,
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
Declare @Index int
Set @Index = 0;
EXEC sp_xml_preparedocument @Index OUTPUT, @EmployeeCodeIds
insert into #ReprocessEmployees (EmployeeCodeId)
select EmployeeId
from OpenXML(@Index, '/NewDataSet/ReprocessEmployees')
With (EmployeeId varchar(15) 'EmployeeId')
Exec sp_xml_removedocument @Index		  
 insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''  
  set @sqlQuery = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id '  
  --set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '    
  set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery = @sqlQuery + ' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery = @sqlQuery + ' and (LA.Leave_FromDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery = @sqlQuery + ' or LA.Leave_ToDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery = @sqlQuery + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery = @sqlQuery + ' and (LA.Status IN ( ''Forwarded'',''Pending''))' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery = @sqlQuery + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + ' and Month(''' + cast( @dtClosingMonth as varchar(20)) + ''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))'  
  set @sqlQuery1=''  
  set @sqlQuery1 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id '  
  --set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id '    
   set @sqlQuery1 = @sqlQuery1 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery1 = @sqlQuery1 + ' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery1 = @sqlQuery1 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery1 = @sqlQuery1 + ' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery1 = @sqlQuery1 + ' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery1 = @sqlQuery1 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery1 = @sqlQuery1 + ' and (mt.Clk_Process = ''N'') and (mt.ManualTimeEntry_Status != ''Rejected'')' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''  
  set @sqlQuery2 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery2 = @sqlQuery2 + ' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id '  
  --set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery2 = @sqlQuery2 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
  set @sqlQuery2 = @sqlQuery2 + ' AND E.Isdeleted=0'  
  --set @sqlQuery2 = @sqlQuery2 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery2 = @sqlQuery2 + ' and pd.Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery2 = @sqlQuery2 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery2 = @sqlQuery2 + ' and (pd.ProcessFlag =0 )' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''  
  set @sqlQuery3 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery3 = @sqlQuery3 + ' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId '  
  --set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery3 = @sqlQuery3 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery3 = @sqlQuery3 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery3 = @sqlQuery3 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
  set @sqlQuery3 = @sqlQuery3 + ' AND E.Isdeleted=0'  
  --set @sqlQuery3 = @sqlQuery3 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery3 = @sqlQuery3 + ' and crd.Clk_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery3 = @sqlQuery3 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery3 = @sqlQuery3 + ' and (crd.Clk_Flag =0 or crd.Clk_Process =0)' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery3 = @sqlQuery3 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''  
  set @sqlQuery4 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id '  
  --set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery4 = @sqlQuery4 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id '
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
   set @sqlQuery4 = @sqlQuery4 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery4 = @sqlQuery4 + ' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ' 
  set @sqlQuery4 = @sqlQuery4 + ' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery4 = @sqlQuery4 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery4 = @sqlQuery4 + ' and pm.Permission_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery4 = @sqlQuery4 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery4 = @sqlQuery4 + ' and (pm.Permission_Status IN ( ''Forwarded'',''Pending''))'  
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery4 = @sqlQuery4 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=N'?? ??? ???????? '
if(@gintRawCount>0)
	begin
	set @Result=@Result + N' ?????? '
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + ','
	end
set @Result=@Result + N' ?????? ????? ' 
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + ','
			end
		set @Result=@Result + N' ?????? '
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + ','
					end
		set @Result=@Result + N' ?????  '
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + ','
							end
		set @Result=@Result + N' ????? ????? ?????? '
	end
set @Result=@Result + N' ???? ?????? '
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''
end
drop table #LevelRights
drop table #ReprocessEmployees
drop table #tblProcessRaw
drop table #tblProcessProcessData
drop table #tblProcessLeave
drop table #tblProcessPermission
drop table #tblProcessManualEntry
drop table #TempProcessedData
drop table #Clk_RawData
select @Result as Result
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure '323','1/1/2011','12/31/2011','','SuperAdmin',323
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds varchar(8000),
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''  
  set @sqlQuery = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id '  
  --set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '    
  set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery = @sqlQuery + ' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery = @sqlQuery + ' and (LA.Leave_FromDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery = @sqlQuery + ' or LA.Leave_ToDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery = @sqlQuery + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery = @sqlQuery + ' and (LA.Status IN ( ''Forwarded'',''Pending''))' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery = @sqlQuery + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + ' and Month(''' + cast( @dtClosingMonth as varchar(20)) + ''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))'  
  set @sqlQuery1=''  
  set @sqlQuery1 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id '  
  --set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id '    
  set @sqlQuery1 = @sqlQuery1 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery1 = @sqlQuery1 + ' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery1 = @sqlQuery1 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery1 = @sqlQuery1 + ' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery1 = @sqlQuery1 + ' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery1 = @sqlQuery1 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery1 = @sqlQuery1 + ' and (mt.Clk_Process = ''N'') and (mt.ManualTimeEntry_Status != ''Rejected'')' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''  
  set @sqlQuery2 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery2 = @sqlQuery2 + ' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id '  
  --set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery2 = @sqlQuery2 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery2 = @sqlQuery2 + ' AND E.Isdeleted=0'  
  --set @sqlQuery2 = @sqlQuery2 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery2 = @sqlQuery2 + ' and pd.Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery2 = @sqlQuery2 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery2 = @sqlQuery2 + ' and (pd.ProcessFlag =0 )' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''  
  set @sqlQuery3 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery3 = @sqlQuery3 + ' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId '  
  --set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery3 = @sqlQuery3 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery3 = @sqlQuery3 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery3 = @sqlQuery3 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery3 = @sqlQuery3 + ' AND E.Isdeleted=0'  
  --set @sqlQuery3 = @sqlQuery3 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery3 = @sqlQuery3 + ' and crd.Clk_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery3 = @sqlQuery3 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery3 = @sqlQuery3 + ' and (crd.Clk_Flag =0 or crd.Clk_Process =0)' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery3 = @sqlQuery3 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''  
  set @sqlQuery4 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id '  
  --set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery4 = @sqlQuery4 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id '
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery4 = @sqlQuery4 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery4 = @sqlQuery4 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery4 = @sqlQuery4 + ' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery4 = @sqlQuery4 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery4 = @sqlQuery4 + ' and pm.Permission_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery4 = @sqlQuery4 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery4 = @sqlQuery4 + ' and (pm.Permission_Status IN ( ''Forwarded'',''Pending''))'  
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery4 = @sqlQuery4 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result='Non Processed '
if(@gintRawCount>0)
	begin
	set @Result=@Result + ' Device '
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + ','
	end
set @Result=@Result + ' Data Process '
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + ','
			end
		set @Result=@Result + ' Leave '
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + ','
					end
		set @Result=@Result + ' Permission '
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + ','
							end
		set @Result=@Result + ' Manual Entry '
	end
set @Result=@Result + ' Data Exists'
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''
end
drop table #LevelRights
drop table #EmpLevel
drop table #ReprocessEmployees
drop table #tblProcessRaw
drop table #tblProcessProcessData
drop table #tblProcessLeave
drop table #tblProcessPermission
drop table #tblProcessManualEntry
drop table #TempProcessedData
drop table #Clk_RawData
select @Result as Result
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure '1,2,3,47,113,133,134,135,137,138,140,150','1/1/2009','05/08/2009','','',''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds varchar(8000),
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''  
  set @sqlQuery = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery = @sqlQuery + ' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id '  
  --set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id '    
  set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery = @sqlQuery + ' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery = @sqlQuery + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery = @sqlQuery + ' and (LA.Leave_FromDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery = @sqlQuery + ' or LA.Leave_ToDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery = @sqlQuery + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery = @sqlQuery + ' and (LA.Status IN ( ''Forwarded'',''Pending''))' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery = @sqlQuery + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + ' and Month(''' + cast( @dtClosingMonth as varchar(20)) + ''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))'  
  set @sqlQuery1=''  
  set @sqlQuery1 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id '  
  --set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id '    
  set @sqlQuery1 = @sqlQuery1 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery1 = @sqlQuery1 + ' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery1 = @sqlQuery1 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery1 = @sqlQuery1 + ' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery1 = @sqlQuery1 + ' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102)) '    
  --set @sqlQuery1 = @sqlQuery1 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery1 = @sqlQuery1 + ' and (mt.Clk_Process = ''N'') and (mt.ManualTimeEntry_Status != ''Rejected'')' 
	--if not(@EmployeeCodeIds='')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''  
  set @sqlQuery2 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery2 = @sqlQuery2 + ' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id '  
  --set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery2 = @sqlQuery2 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery2 = @sqlQuery2 + ' AND E.Isdeleted=0'  
  --set @sqlQuery2 = @sqlQuery2 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery2 = @sqlQuery2 + ' and pd.Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery2 = @sqlQuery2 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery2 = @sqlQuery2 + ' and (pd.ProcessFlag =0 )' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''  
  set @sqlQuery3 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery3 = @sqlQuery3 + ' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId '  
  --set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery3 = @sqlQuery3 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery3 = @sqlQuery3 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery3 = @sqlQuery3 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery3 = @sqlQuery3 + ' AND E.Isdeleted=0'  
  --set @sqlQuery3 = @sqlQuery3 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery3 = @sqlQuery3 + ' and crd.Clk_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery3 = @sqlQuery3 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery3 = @sqlQuery3 + ' and (crd.Clk_Flag =0 or crd.Clk_Process =0)' 
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery3 = @sqlQuery3 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''  
  set @sqlQuery4 = 'select Count(*) as Count from TA_TBL_Employee E '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id '  
  --set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
  --set @sqlQuery4 = @sqlQuery4 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
  set @sqlQuery4 = @sqlQuery4 + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id '
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + ' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id ' 
  end
  set @sqlQuery4 = @sqlQuery4 + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
  --set @sqlQuery4 = @sqlQuery4 + ' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
  set @sqlQuery4 = @sqlQuery4 + ' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1'  
  --set @sqlQuery4 = @sqlQuery4 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
  --set @sqlQuery4 = @sqlQuery4 + ' and pm.Permission_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
  --set @sqlQuery4 = @sqlQuery4 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
  set @sqlQuery4 = @sqlQuery4 + ' and (pm.Permission_Status IN ( ''Forwarded'',''Pending''))'  
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery4 = @sqlQuery4 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=N'?? ??? ???????? '
if(@gintRawCount>0)
	begin
	set @Result=@Result + N'?????? '
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + ','
	end
set @Result=@Result + N'?????? ????? '
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + ','
			end
		set @Result=@Result + N'?????? '
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + ','
					end
		set @Result=@Result + N'????? '
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + ','
							end
		set @Result=@Result + N'????? ????? ?????? '
	end
set @Result=@Result + N'???? ?????? '
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''
end
select @Result as Result
drop table #LevelRights
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUsergroupDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetUsergroupDetails]
AS
BEGIN
	SET NOCOUNT ON
	SELECT groupId,groupName FROM ta_tbl_usergroup WHERE IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroupName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
-- =============================================  
-- Author:  sashma  
-- Create date: 30-Jul-2010  
-- Description: Getting User group name  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_getUserGroupName]  
(  
@GroupId int   
)  
AS  
select groupName from ta_tbl_usergroup where groupId=@GroupId  
  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroups]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- Create date: 13-Aug-07
-- Description:	Getting User groups
-- =============================================
--Proc_TA_getUserGroups 'User's'
CREATE PROCEDURE [dbo].[Proc_TA_getUserGroups]
(
@GroupName nvarchar(50) 
)
AS
if(@GroupName = '' or @GroupName is null)
BEGIN
	select * from ta_tbl_usergroup where isdeleted=0 order by groupName
END
else
BEGIN
 select * from ta_tbl_usergroup where groupName like cast('%'+@GroupName+'%' as nvarchar(50)) and isdeleted=0 order by groupName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenu]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <26/jul/07>    
-- Description: Getting Left Menu>    
-- [dbo].[Proc_TA_GetUserMenu]  0,1,''  
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_GetUserMenu]   
(    
	@parentId int,    
	@groupId int,  
	@strType varchar(20)     
)    
AS    
BEGIN 
	SET NOCOUNT ON; 
	declare @Express varchar(800)  
	declare @values varchar(800)  
	if(@strType='Express')   
	begin  
		if (@parentId=0)    
		begin  
			set @values=' and pageID not in(20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,36,37,38,39,43,45,48,49,53,60,65,67,72,75,77,78,79,80,93,99,100,102,103,105,107,106,108,116,118,127,127,130,12,117,172,173,174,175,171) '  
			set @Express='select * from ta_tbl_page where parentID='+ CONVERT(varchar(20), @parentId)  
			set @Express=@Express + ' and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId='+convert(varchar(20),@groupId)+' and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) '  
			if((select COUNT(*) from TA_Tbl_LIC_Details)>0)  
			begin  
				exec(@Express)  
			end  
			else
			begin  
				set @Express= @Express + @values +' order by orderby'  
				exec(@Express)
			end  
		end  
		else  
		begin  
			set @values=' and pageID not in(20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,36,37,38,39,43,45,48,49,53,60,65,67,72,75,77,78,79,80,93,99,100,102,103,105,107,106,108,116,118,127,127,130,12,117,172,173,174,175,171) '  
			set @Express='select * from ta_tbl_page where parentID='+ CONVERT(varchar(20), @parentId)  
			set @Express=@Express + ' and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId='+ CONVERT(varchar(20), @groupId ) +' and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) '  
			if((select COUNT(*) from TA_Tbl_LIC_Details)>0)  
			begin  
				set @Express= @Express +' order by orderby'  
				exec(@Express)  
			end  
			else  
			begin  
				set @Express= @Express + @values +' order by orderby'  
				exec(@Express)  
			end  
		end  
	End  
	else if(@strType!='Standard')  
	BEGIN  
		if (@parentId=0)    
		Begin    
			select * from ta_tbl_page where parentID=0 and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby 
		End    
		Else    
		Begin    
			select * from ta_tbl_page where parentID=@parentId and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby    
		End  
	END  
	else  
	BEGIN
		if (@parentId=0)    
		Begin
			select * from ta_tbl_page where parentID=0 and pageID not in (20,24,25,69,96,97,98,110,133,93,116,127,130,179,228,174)   
			and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby    
		End   
		Else   
		Begin
			select * from ta_tbl_page where parentID=@parentId and pageID not in (20,24,25,69,96,97,98,110,133,93,116,127,130,179,228,174)    
			and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby    
		End
	END
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <26/jul/07>    
-- Description: Getting Left Menu>    
-- =============================================    
--Proc_TA_GetUserMenus 2,1,''
CREATE PROCEDURE [dbo].[Proc_TA_GetUserMenus]
(    
 @parentId int,    
 @groupId int,  
 @strType varchar(20)     
)    
AS    
BEGIN    
if(@strType!='Standard')  
	BEGIN
		if (@parentId=0)    
			Begin    			
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex('/',ta.path))+'/'+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID in (select						pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1))order by				orderby
			End    
		Else    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex('/',ta.path))+'/'+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page	ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID in (select pageID from					ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby
			End  
		END  
else   
	BEGIN  
		if (@parentId=0)    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex('/',ta.path))+'/'+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID not in (20,24,25,				69,96,97,98,108,110)and ts.pageID in (select pageGroupID from	ta_tbl_userRights where groupId=@groupId and (addPrv=1 or					modifyPrv=1 or deletePrv=1 or viewPrv=1))order by orderby
			End    
		Else    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex('/',ta.path))+'/'+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID not in (20,24,25,				69,96,97,98,108,110)and ts.pageID in (select pageID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=				1 or deletePrv=1 or viewPrv=1))order by orderby
			End  
	END      
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetUserRights]
(
	@groupId int
)
AS
BEGIN
	select * from ta_tbl_userrights where groupID=@groupId  and isdeleted=0 and pageid in (select pageID from ta_tbl_page where parentID!=999)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUTCCountryDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetUTCCountryDetails]
AS
BEGIN
	
	Select TimeZoneID,'('+TimezoneValue+')'+' '+TimeZoneDesc as CountryName  From TA_Tbl_UTCTimeZonesCountryDetails order by HoursToBeAdded

	Declare @isfalg int

	Select @isfalg=isNull(isTimezoneEnable,0) From TA_tbl_YearSetting where isActive=1

	if(@isfalg=0)
	begin
		 Select @isfalg As TimezoneEnable,TimezoneID,'('+TimezoneValue+')'+' '+TimeZoneDesc as CountryName From TA_Tbl_UTCTimeZonesCountryDetails where ServerDefault=1
	End
	else
	begin
		Select @isfalg As TimezoneEnable,0 As TimezoneID
	End

END




--Select * From Ta_Tbl_levelDetails
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetVehicleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE Proc [dbo].[Proc_TA_GetVehicleDetails] as      
 SELECT VehicleId,VehicleNo FROM TA_Tbl_Transportation_Vehicle Where IsDeleted=1
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration 3,'Sunday','Saturday',1,31
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]
	-- Add the parameters for the stored procedure here
	@Frequency int,
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateFrom int,
	@DateTo int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Current_WeekStartDay datetime
	declare @Current_WeekEndDay datetime
	declare @Prev_WeekStartDay datetime
	declare @Prev_WeekStartDayFinal datetime
	declare @Prev_WeekEndDay datetime
	Declare @DayFromWeek varchar(10)
	Declare @DayToWeek varchar(10)
	Declare @CurrentMonth_StartDate datetime
	Declare @PreviousMonth_StartDate datetime
	Declare @PreviousMonth_EndDate datetime
	declare @GetmonthNumer int
    -- Insert statements for procedure here
	if(@Frequency=2)
	begin		
		select @Current_WeekStartDay= DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()),@Current_WeekEndDay=DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate())
		select @Prev_WeekStartDay= DATEADD(day, -7, @Current_WeekStartDay)
		Declare @i int 
		if(ISNUMERIC(@DayFrom)=0)
		begin
			select @Prev_WeekStartDay=case when @DayFrom='Sunday' then  @Prev_WeekStartDay
									when @DayFrom='Monday' then  DATEADD(d,1,@Prev_WeekStartDay)
									when @DayFrom='Tuesday' then  DATEADD(d,2,@Prev_WeekStartDay)
									when @DayFrom='Wednesday' then  DATEADD(d,3,@Prev_WeekStartDay)
									when @DayFrom='Thursday' then  DATEADD(d,4,@Prev_WeekStartDay)
									when @DayFrom='Friday' then  DATEADD(d,5,@Prev_WeekStartDay)
									when @DayFrom='Saturday' then  DATEADD(d,6,@Prev_WeekStartDay)
						 end
			set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
			set @i=1
			while @i>0
			begin
				set @DayFromWeek=DATENAME(DW,@Prev_WeekStartDay)
				if(@DayFromWeek=@DayTo)
				begin
					set @Prev_WeekEndDay=@Prev_WeekStartDay
					set @i=0
				end
				else
				begin
					set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
					set @i=@i+1
				end			
			end
			select 	2 as frequency,replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),' ','-') as Fromdate,
			replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),' ','-') as Todate
		end
		else
		begin
			select @Prev_WeekStartDay=case when @DayFrom='1' then  @Prev_WeekStartDay
									when @DayFrom='2' then  DATEADD(d,1,@Prev_WeekStartDay)
									when @DayFrom='3' then  DATEADD(d,2,@Prev_WeekStartDay)
									when @DayFrom='4' then  DATEADD(d,3,@Prev_WeekStartDay)
									when @DayFrom='5' then  DATEADD(d,4,@Prev_WeekStartDay)
									when @DayFrom='6' then  DATEADD(d,5,@Prev_WeekStartDay)
									when @DayFrom='7' then  DATEADD(d,6,@Prev_WeekStartDay)
						 end
			set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
			set @i=1
			while @i>0
			begin
				set @DayFromWeek=case when DATENAME(DW,@Prev_WeekStartDay)='Sunday' then 1
										when DATENAME(DW,@Prev_WeekStartDay)='Monday' then 2
										when DATENAME(DW,@Prev_WeekStartDay)='Tuesday' then 3
										when DATENAME(DW,@Prev_WeekStartDay)='Wednesday' then 4
										when DATENAME(DW,@Prev_WeekStartDay)='Thursday' then 5
										when DATENAME(DW,@Prev_WeekStartDay)='Friday' then 6
										else 7 end
				if(@DayFromWeek=@DayTo)
				begin
					set @Prev_WeekEndDay=@Prev_WeekStartDay
					set @i=0
				end
				else
				begin
					set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
					set @i=@i+1
				end			
			end
			select 	2 as frequency,replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),' ','-') as Fromdate,
			replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),' ','-') as Todate
		end
	end
	if @Frequency=3
	begin		
		set @CurrentMonth_StartDate=DATEADD(d,-datepart(d,getdate())+1,getdate())
		set @PreviousMonth_StartDate=DATEADD(MONTH,-1,@CurrentMonth_StartDate)
		if(DATEPART(d,@PreviousMonth_StartDate)=@DateFrom)
		begin			
			set @PreviousMonth_StartDate=@PreviousMonth_StartDate
		end
		else
		begin
			set @PreviousMonth_StartDate=DATEADD(d,@DateFrom-1,@PreviousMonth_StartDate)
		end		
		set @i=1
		while @i>0
		begin
			set @PreviousMonth_EndDate=DATEADD(d,@i,@PreviousMonth_StartDate)
			set @GetmonthNumer=DATEPART(MONTH,@PreviousMonth_StartDate)
			if @GetmonthNumer in(2)
			begin
				if @DateFrom=1 and (@DateTo=31 or @DateTo=30 or @DateTo=29)
				begin
					if(DATEPART(year,@PreviousMonth_EndDate)%4=0)
					begin
						set @DateTo=29
					end
					else
					begin
						set @DateTo=28
					end
				end				
			end
			else if @GetmonthNumer in(4,6,9,11)
			begin
				if @DateFrom=1 and @DateTo=31
				begin
					set @DateTo=30
				end
			end
			else if @GetmonthNumer in(1,3,5,7,8,10,12)
			begin
				if @DateFrom=1 and @DateTo=31
				begin
					set @DateTo=31
				end
			end
			if(DATEPART(d,@PreviousMonth_EndDate)=@DateTo)
			begin
				set @PreviousMonth_EndDate=@PreviousMonth_EndDate
				set @i=0
			end
			else
			begin
				set @i=@i+1
			end
		end
		--select @PreviousMonth_StartDate,@PreviousMonth_EndDate
		select 		3 as frequency,
		replace(CONVERT(varchar(20),@PreviousMonth_StartDate,106),' ','-') as Fromdate,
		replace(CONVERT(varchar(20),@PreviousMonth_EndDate,106),' ','-') as Todate
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration 2,'Friday','Thursday',15,10
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]
	-- Add the parameters for the stored procedure here
	@Frequency int,
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateFrom int,
	@DateTo int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Current_WeekStartDay datetime
	declare @Current_WeekEndDay datetime
	declare @Prev_WeekStartDay datetime
	declare @Prev_WeekStartDayFinal datetime
	declare @Prev_WeekEndDay datetime
	Declare @DayFromWeek varchar(10)
	Declare @DayToWeek varchar(10)
    -- Insert statements for procedure here
	if(@Frequency=2)
	begin		
		select @Current_WeekStartDay= DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()),@Current_WeekEndDay=DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate())
		select @Prev_WeekStartDay= DATEADD(day, -7, @Current_WeekStartDay)
		select @Prev_WeekStartDay=case when @DayFrom='Sunday' then  @Prev_WeekStartDay
								when @DayFrom='Monday' then  DATEADD(d,1,@Prev_WeekStartDay)
								when @DayFrom='Tuesday' then  DATEADD(d,2,@Prev_WeekStartDay)
								when @DayFrom='Wednesday' then  DATEADD(d,3,@Prev_WeekStartDay)
								when @DayFrom='Thursday' then  DATEADD(d,4,@Prev_WeekStartDay)
								when @DayFrom='Friday' then  DATEADD(d,5,@Prev_WeekStartDay)
								when @DayFrom='Saturday' then  DATEADD(d,6,@Prev_WeekStartDay)
					 end
		set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
		Declare @i int 
		set @i=1
		while @i>0
		begin
			set @DayFromWeek=DATENAME(DW,@Prev_WeekStartDay)
			if(@DayFromWeek=@DayTo)
			begin
				set @Prev_WeekEndDay=@Prev_WeekStartDay
				set @i=0
			end
			else
			begin
				set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
				set @i=@i+1
			end			
		end
		select 		
		replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),' ','-') as Frodate,
		replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),' ','-') as Todate
	end
	if @Frequency=3
	begin
		Declare @CurrentMonth_StartDate datetime
		Declare @PreviousMonth_StartDate datetime
		set @CurrentMonth_StartDate=DATEADD(d,-datepart(d,getdate())+1,getdate())
		set @PreviousMonth_StartDate=DATEADD(MONTH,-1,@CurrentMonth_StartDate)
		select  @CurrentMonth_StartDate,@PreviousMonth_StartDate
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetWhatsAppConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_GetWhatsAppConfiguration] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	select WhatsApp_authToken,WhatsAPP_SID,WhatsApp_SenderNumber from TA_Tbl_APIConfig

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetWhatsAppSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetWhatsAppSchedule 'Weekly'
-- exec Proc_TA_GetWhatsAppSchedule @Frequency=N'WhatsAppScheduleWeekly'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetWhatsAppSchedule] 
	-- Add the parameters for the stored procedure here
	 @Frequency varchar(20)

AS
BEGIN

	create table #TempWhatsAppSchedule(ScheduleId int)
	if(@Frequency = 'Daily')
	BEGIN
			insert into #TempWhatsAppSchedule 
			select ES.ScheduleId from TA_tbl_WhatsAppScheduleStatus ESS
			inner join TA_Tbl_WhatsAppSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Daily' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 

			select ScheduleId from TA_Tbl_WhatsAppSchedule
			where Frequency = 'Daily'
			and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
			and ScheduleId not in (select scheduleId from #TempWhatsAppSchedule)
			and IsDeleted = 0 and Enabled = 1
	END	
	else if(@Frequency = 'Weekly')
	BEGIN
			insert into #TempWhatsAppSchedule select ES.ScheduleId from TA_tbl_WhatsAppScheduleStatus ESS
			inner join TA_Tbl_WhatsAppSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Weekly' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			
			declare @WeekDay varchar(10)
			set @WeekDay = (select DATEname(DW,GETDATE()))

			select ScheduleId from TA_Tbl_WhatsAppSchedule
			where Frequency = 'Weekly'
			and DayToSend = @WeekDay
			and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
			and ScheduleId not in (select scheduleId from #TempWhatsAppSchedule)
			and IsDeleted = 0 and Enabled = 1
	END
	else if(@Frequency = 'Monthly')
	BEGIN
			insert into #TempWhatsAppSchedule select ES.ScheduleId from TA_tbl_WhatsAppScheduleStatus ESS
			inner join TA_Tbl_WhatsAppSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = 'Monthly' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			declare @CurrentDate int
			set @CurrentDate = (select DATEPART(D,GETDATE()))
			declare @LastDateOfCurrentMonth int
			set @LastDateOfCurrentMonth = (SELECT DATEPART ( D , DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),
            DATEADD(MONTH, 1, GETDATE()))))
			if(@CurrentDate = @LastDateOfCurrentMonth)
			BEGIN
				select ScheduleId from TA_Tbl_WhatsAppSchedule
				where Frequency = 'Monthly'
				and DateToSend >= @CurrentDate
				and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
				and ScheduleId not in (select scheduleId from #TempWhatsAppSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
			ELSE
			BEGIN
				select ScheduleId from TA_Tbl_WhatsAppSchedule
				where Frequency = 'Monthly'
				and DateToSend = @CurrentDate
				and cast((CONVERT(varchar(10),getdate(),101) + ' '  + TimeToSend) as datetime) <= GETDATE()
				and ScheduleId not in (select scheduleId from #TempWhatsAppSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
	END
	drop table #TempWhatsAppSchedule
END


----Select * From TA_tbl_WhatsAppScheduleStatus

--Delete From TA_tbl_WhatsAppScheduleStatus
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetWhatsAppScheduleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_GetScheduleDetails 1,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_GetWhatsAppScheduleDetails]	
(
 @EmployeeId int,
 @UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	if(@UserGroupName = 'SuperAdmin')
	BEGIN
		select ES.ScheduleId as WhatsAppScheduleID,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + ' ' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then 'Enabled' else 'Disabled' end as Enabled,TimeToSend
		from TA_Tbl_WhatsAppSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Isdeleted=0 and E.Employee_Status=1 and ES.IsDeleted=0
		order by ScheduleId
	END
	else
	BEGIN
		select ES.ScheduleId as WhatsAppScheduleID,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + ' ' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then 'Enabled' else 'Disabled' end as Enabled,TimeToSend
		from TA_Tbl_WhatsAppSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Employee_Id = @EmployeeId and ES.IsDeleted=0
		order by ScheduleId
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWhatsAppScheduler_FilterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetWhatsAppScheduler_FilterDetails 4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetWhatsAppScheduler_FilterDetails] 
	-- Add the parameters for the stored procedure here
	@scheduleId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	Declare @Filters varchar(max)
	Declare @Count int
	Declare @start int
	Declare @TempTable varchar(max)
	Declare @TempTableInsert varchar(max)
	Declare @TempFiltersvalue varchar(max)
	Declare @TempFiltersvalues varchar(max)

	set @TempTable='Create Table TempFinalFilters('
	set @TempTableInsert='Insert into TempFinalFilters values('
	set @start=1
	select @Filters=Filters  from TA_Tbl_WhatsAppScheduleFilters where ScheduleId=@scheduleId
	select @Count=COUNT(*) from dbo.Split(@Filters,',')
	Create table #TempFilters(id int identity(1,1),Filters varchar(max))
	insert into #TempFilters select Value from dbo.Split(@Filters,',')
	--select * from #TempFilters
	while @start<=@Count 
	begin
		select @TempFiltersvalue=replace(substring(Filters,0,charindex('=',Filters)),'@',''),
		@TempFiltersvalues=replace(substring(Filters,charindex('=',Filters)+1,LEN(Filters)),'~',',')
		from #TempFilters where id=@start 
		if(@start!=@Count)
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max),'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''','
		end
	else
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max)'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''''
		end			
		set @start=@start+1
	end
	set @TempTable=@TempTable+')'
	set @TempTableInsert=@TempTableInsert+')'	
	Execute(@TempTable)
	Execute(@TempTableInsert)
	select * from TempFinalFilters
	Select ReportType From TA_Tbl_WhatsAppScheduleFilters Where ScheduleId=@scheduleId
	drop table TempFinalFilters
END


--Select * From TA_Tbl_Preferences

--Select * From TA_Tbl_ShiftSettings
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearAvailedLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_employee where employee_Code_id='787'
-- =============================================
-- Author:		Manikandan
-- Create date: 25-07-2017
-- Description:	Getting Current Year Leave Details
-- [dbo].[Proc_TA_GetYearAvailedLeaveDetails] 48,787787
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetYearAvailedLeaveDetails]
	@EmployeeId INT = NULL,
	@EmployeeCode VARCHAR(60) = NULL
AS
BEGIN
	SET NOCOUNT ON;
	Declare @CurrentYearAvailedLeaves decimal(18,1)
	Declare @CurrentMonthAvailedLeaves decimal(18,1)
	Declare @CurrentYearPendingLeaves decimal(18,1)
	set @CurrentYearPendingLeaves =0
	set @CurrentMonthAvailedLeaves =0
	set @CurrentYearAvailedLeaves =0
	SELECT @CurrentYearAvailedLeaves=isnull(sum(LA.NumberOfDays),0) FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '') OR E.Employee_Code_Id = @EmployeeCode) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN ('Rejected', 'Canceled')
	SELECT @CurrentMonthAvailedLeaves=isnull(sum(LA.NumberOfDays),0)FROM TA_Tbl_LeaveApplication LA
		LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
		INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
	WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
		((@EmployeeCode IS NULL OR @EmployeeCode = '') OR E.Employee_Code_Id = @EmployeeCode) AND
		DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
		LA.IsDeleted = 0 AND LA.[Status] NOT IN ('Rejected', 'Canceled')
	SELECT @CurrentYearPendingLeaves=isnull(sum(LA.NumberOfDays),0)FROM TA_Tbl_LeaveApplication LA
		LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
		INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
	WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
		((@EmployeeCode IS NULL OR @EmployeeCode = '') OR E.Employee_Code_Id = @EmployeeCode) AND
		DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
		LA.IsDeleted = 0 AND LA.[Status] IN ('Pending')
	select @CurrentYearAvailedLeaves as currentYear,@CurrentMonthAvailedLeaves as currentMonthAvailed,@CurrentYearPendingLeaves as currentmonthPending
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--select * from ta_tbl_yearSetting
-- Proc_TA_GetYearSettingId '2011/03/30','2011/03/31' 
CREATE PROCEDURE [dbo].[Proc_TA_GetYearSettingId] 
	-- Add the parameters for the stored procedure here
	@FromDate datetime,
	@ToDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	if exists(select yearsettings_Id from ta_tbl_yearSetting where ToDate = @FromDate)
		begin
			if exists(select yearsettings_Id from ta_tbl_yearSetting where FromDate=@ToDate)
				begin
					select 'Apply Induvial records'
				end
			else
				begin
					select YearSettings_Id from ta_tbl_yearSetting where (@FromDate between FromDate and ToDate) AND
					(@ToDate between FromDate and ToDate)
				end
		end
	else
		begin
			select YearSettings_Id from ta_tbl_yearSetting where (@FromDate between FromDate and ToDate) AND
					(@ToDate between FromDate and ToDate)
		end
 --   if not exists((select yearsettings_Id from ta_tbl_yearSetting where ToDate = '2011/03/30') union all (select yearsettings_Id from ta_tbl_yearSetting where FromDate = '2011/03/30'))
 --   --where dateadd(day,(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=1),ToDate) = @FromDate and 
 -- -- dateadd(day,(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=1),FromDate) = @ToDate)
	--	begin
	--	end
	--else
	--	begin
	--	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetYearSettingIdForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GetYearSettingIdForService]
	-- Add the parameters for the stored procedure here
	@date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT YearSettings_Id FROM TA_Tbl_YearSetting WHERE FromDate <=@date and ToDate>= @date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingIdForWin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetYearSettingIdForWin]
	-- Add the parameters for the stored procedure here
	@ShiftDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @YearSettingsId int
	SELECT @YearSettingsId=YearSettings_Id FROM TA_Tbl_YearSetting WHERE FromDate <= @ShiftDate AND ToDate >= @ShiftDate
	if @YearSettingsId=''
		begin
			set @YearSettingsId=0
		end
	select @YearSettingsId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GroupManualEntryEmployees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select * from TA_Tbl_TemporaryShiftAllocation
-- select * from TA_Tbl_PermanentShiftAllocation where year=2010 and Month=12
-- =============================================
-- Author:		senthil Proc_TA_RptTemporaryShift '2010/10/05','5','','',0,0,'SuperAdmin','0','','2',0
-- ALTER  date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_GroupManualEntryEmployees]  
(
	@fromDate datetime,	
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@EmployeeName varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ShiftId varchar(10),
	@EmpAutoId bigint   		          
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Basic Pay Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
	(
		[PayId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--Employee Pay insert in Temporary table
	insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
	select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
	inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpBpay
	inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
	AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EPay.PayId is not null
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + ' SELECT dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,dbo.TA_Tbl_Shift.Shift_Name,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''&amp;'',''&'') as Shift_ShortName,dbo.TA_Tbl_Shift.Shift_StartTime,dbo.TA_Tbl_Shift.Shift_EndTime,dbo.TA_Tbl_Employee.Employee_FirstName + Space(1) + '      
    set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee.Employee_LastName as empname, dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName,isnull(TA_Tbl_ProcessedData.InTime,'''') as InTime,TA_Tbl_ProcessedData.Attendance' 
    set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation LEFT OUTER JOIN'  
        		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN'
        		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
   			set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'      
			set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner JOIN dbo.TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' left outer join dbo.TA_Tbl_ProcessedData ON dbo.TA_Tbl_Employee.SwipeCardNo = dbo.TA_Tbl_ProcessedData.Employee_Code_Id'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
        set @sqlQuery = @sqlQuery + ' WHERE (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'
		set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0'
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
	if not(@EmployeeId='')  
		begin  
			set @sqlQuery = @sqlQuery + 'and (ta_tbl_Employee.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
		end 
	if not(@EmployeeName='')  
		begin  
			set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end  
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
		end
    if(@EmpAutoId = 0)
    BEGIN
	if not(@LevelID='' or @LevelID='0')
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ') ' 
		end	
	END
	ELSE
		BEGIN
		   set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if not(@ShiftId='' or @ShiftId='0' or @ShiftId='All')  
	begin  
		set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Shift.Shift_Id = ''' + @ShiftId + ''')'  
	end 
		set @sqlQuery = @sqlQuery + ' order by TA_Tbl_Employee.Employee_Code_Id' 
exec (@sqlQuery)
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_HolidayInsert_YearCreation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gopinath.K
-- Description:	For Auto insert of Global holiday during new year creation
-- Proc_Ta_HolidayInsert_YearCreation 1,58
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_HolidayInsert_YearCreation]
@OldYearSettingsID int,
@NewYearSettingsID int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @TopHolidayID as int
	Declare @YearDifference as int
	SET @TopHolidayID = ((SELECT IDENT_CURRENT('ta_tbl_holiday'))+1)
	Select @StartDate = Fromdate, @EndDate = Todate from ta_tbl_yearsetting where YearSettings_ID = @NewYearSettingsID
	SET @YearDifference = (select Datediff(Year,(select Fromdate from ta_tbl_yearsetting where yearsettings_id=@OldYearSettingsID),
						  (select Fromdate from ta_tbl_yearsetting where yearsettings_id=@NewYearSettingsID)))
	CREATE Table #TempHolidayInsert(OLDHoliday_ID int,NewHoliday_ID int identity(1,1) not null,Holiday_Type varchar(5),
	Holiday_FromDate datetime,Holiday_ToDate datetime,Holiday_Description nvarchar(500),
	YearSettings_Id int,OldYearSettings_Id int,Isdeleted int,Emp_Id int,LevelId int)
	DBCC CHECKIDENT (#TempHolidayInsert, RESEED, @TopHolidayID)
	DELETE ta_tbl_holidaysettings where YearSettingID = @NewYearSettingsID
	Delete TA_Tbl_HolidayChildTable where holiday_id in 
	(Select Holiday_ID from ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate)
	Delete ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate
	insert into ta_tbl_holidaysettings (Global_Maxdays,Yearly_Maxdays,YearSettingID)
	Select Global_Maxdays,Yearly_Maxdays,@NewYearSettingsID From ta_tbl_holidaysettings where YearSettingID = @OldYearSettingsID
	insert into ta_tbl_holiday (Holiday_Type,Holiday_FromDate,Holiday_ToDate,Holiday_Description,YearSettings_Id,Isdeleted,Emp_Id,LevelId)
	select Holiday_Type,DATEADD(year,@YearDifference,Holiday_FromDate),DATEADD(year,@YearDifference,Holiday_ToDate),Holiday_Description,@NewYearSettingsID,Isdeleted,Emp_Id,LevelId
	from ta_tbl_holiday where Holiday_Type='G' and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID
    Insert into #TempHolidayInsert
	select Holiday_ID,Holiday_Type,DATEADD(year,@YearDifference,Holiday_FromDate),DATEADD(year,@YearDifference,Holiday_ToDate),Holiday_Description,
	@NewYearSettingsID,@OldYearSettingsID,Isdeleted,Emp_Id,LevelId from ta_tbl_holiday where Holiday_Type='G' 
	and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID 
    insert into TA_Tbl_HolidayChildTable (Levelid,Holiday_ID)
 	select TA_Tbl_HolidayChildTable.Levelid, #TempHolidayInsert.NewHoliday_ID
	from TA_Tbl_HolidayChildTable 
	inner join #TempHolidayInsert on #TempHolidayInsert.OLDHoliday_ID=TA_Tbl_HolidayChildTable.Holiday_ID
	where TA_Tbl_HolidayChildTable.holiday_id in 
	(Select Holiday_ID from ta_tbl_holiday where Holiday_Type='G' and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID)
	and #TempHolidayInsert.YearSettings_Id=@NewYearSettingsID
    Drop Table #TempHolidayInsert
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidayRecursion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
					Proc_TA_HolidayRecursion '03/16/2013'
Created By		:	Manjula.P
Created Date	:	23-May-2013
Descriptons		:	Creating proc for recursing to check local holiday by date by date.
*/
CREATE procedure [dbo].[Proc_TA_HolidayRecursion]
(
@date datetime
)
as
begin
	select * from TA_Tbl_Holiday where @date between Holiday_FromDate and Holiday_ToDate and Isdeleted=0
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidaySettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created by	:	Prabakaran.P
Description	:	Insert and update Holiday Settings based on YearSetting Id
Modified on	:	21-Feb-08
*/
CREATE PROCEDURE [dbo].[Proc_TA_HolidaySettings]  
(
	@GlobalHoliday_Maxno int,
	@YearlyHoliday_Maxno int,
	@YearSettingId int
)
AS  
BEGIN
	DECLARE @HolidayCount INT
	SELECT @HolidayCount=Count(*)FROM TA_Tbl_HolidaySettings WHERE YearSettingId=@YearSettingId
	IF @HolidayCount=0  
	BEGIN  
		INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)  
	END  
	ELSE  
	BEGIN  
		UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno WHERE YearSettingId=@YearSettingId
	END   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_IgnoreDuplicatePunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_Ta_IgnoreDuplicatePunches]
(
   @ClkIds AS Varchar(4000)
)
AS
BEGIN
 DECLARE @SQL AS Varchar(4000)
 SET @SQL = 'UPDATE TA_Tbl_ClockDetails SET IsVoid = 1 WHERE Clk_Id IN (' + @ClkIds + ')'
 EXEC (@SQL)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportDataLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ImportDataLevel]
	-- Add the parameters for the stored procedure here
	@department varchar(50)=null,
	@levelName varchar(200)=null

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	SET NOCOUNT ON;
	
	declare @logID bigint=0,@LevelID bigint=0,@Designation nvarchar(250)='',@OrgName varchar(200)='',@ParentId bigint=0,@branchname varchar(200)
	
	if((Select name From TA_Tbl_LevelDetails where name=@levelName and parentId=0 and levelId=1)!='' and @department!='')
	begin
			
			select top 1 @logID=LogID from ta_tbl_EmployeeAPILog order by AutoID desc
			Select @LevelName=name,@LevelID=id from Ta_Tbl_levelDetails where name=@levelName and parentId=0 and levelId=1
			
			print @LevelName

			Select Top 1 @ParentId=parentId From Ta_Tbl_levelDetails where name=@department and levelId=3

			 print @parentId

			Select Top 1 @branchname=name From  Ta_Tbl_levelDetails where parentId=@ParentId and levelId=2

			select Top 1 @Designation=TitleName from TA_Tbl_Title where LevelID=@LevelID order by GradeID desc

			Select @logID as LogID,@LevelName as LevelName,@branchname as Branchname,@Designation as Designation,'No Error' as Error

	End
	Else if(@department='')
	Begin
			Select 'Missing the Biostar Add User Module Department Field is Empty' as Error
	End
	Else if(@levelName='')
	Begin
		Select 'Missing the Biostar Add User Module Department Field Organization Name is Missing' as Error
	End
	else
	begin
		
			Select 'Biostar Add User Module Department Field Organization as Miss Match the Timecheck' as Error
	End

End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportEmployeeMaster_Samsung]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.rr>
-- Create date: <11-nov-2021 09:53 pm>
-- Description:	<This procedure read data FROM csv file for include in employee master for abraj client>
-- 
/*

*/

-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ImportEmployeeMaster_Samsung]
	@Data XML = NULL
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @XMLParams INT	
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @Data
	delete from Ta_Tbl_Error_ImportData_Samsung
	delete from Ta_tbl_EmployeeApprovedData_Samsung
	INSERT INTO Ta_tbl_EmployeeApprovedData_Samsung
	SELECT ROW_NUMBER()OVER(ORDER BY A.[Employee ID]),* FROM(
	SELECT  
		[Employee ID],
		[Name] ,
		[Organization] ,
		[CL	Name] ,
		Gender	,
		[Work Group] ,
		[Work Type] ,
		[Work Date] ,
		[Day Type],
		[After Approve IN]=case when [After Approve IN] IS not null and [After Approve IN]!='' then dbo.Fn_ConvertDateAndTimeFromString([After Approve IN])else null end,
		[After Approve OUT]=case when [After Approve OUT] is not null and [After Approve OUT]!='' then dbo.Fn_ConvertDateAndTimeFromString([After Approve OUT]) else null end,
		[Over Time Actual],
		CASE	WHEN [Employee ID] IS NULL OR Tbl.[Employee ID]='' THEN 1
				WHEN Tbl.[Work Type] IS NULL OR Tbl.[Work Type]='' THEN 2
				WHEN Tbl.[Work Date] IS NULL OR Tbl.[Work Date]='' THEN 3
				WHEN Tbl.[Day Type] IS NULL OR Tbl.[Day Type]='' THEN 4
				WHEN (Tbl.[After Approve IN] IS NULL OR Tbl.[After Approve IN] ='') and  (Tbl.[After Approve OUT] IS NULL OR Tbl.[After Approve OUT] ='')  THEN 6
				ELSE 0
		END AS ERRORNO
	FROM OPENXML (@XMLParams, '/EmployeeDs/Employeetbl', 2)
	WITH 
	(	
		[Employee ID] varchar(50),
		[Name] varchar(250),
		[Organization] varchar(500),
		[CL	Name] varchar(20),
		Gender	varchar(20),
		[Work Group] varchar(100),
		[Work Type] varchar(100),
		[Work Date] varchar(20),
		[Day Type] varchar(100),
		[After Approve IN] varchar(100),
		[After Approve OUT] varchar(100),
		[Over Time Actual] varchar(100)
	) Tbl 
	where (gender='Male' or gender='Female')
	and CHARINDEX('E',[After Approve IN])=0
	and CHARINDEX('E',[After Approve OUT])=0
	UNION ALL
	SELECT  
		[Employee ID],
		[Name] ,
		[Organization] ,
		[CL	Name] ,
		Gender	,
		[Work Group] ,
		[Work Type] ,
		[Work Date] ,
		[Day Type],
		NULL,NULL,
		[Over Time Actual],
		6 AS ERRORNO
	FROM OPENXML (@XMLParams, '/EmployeeDs/Employeetbl', 2)
	WITH 
	(	
		[Employee ID] varchar(50),
		[Name] varchar(250),
		[Organization] varchar(500),
		[CL	Name] varchar(20),
		Gender	varchar(20),
		[Work Group] varchar(100),
		[Work Type] varchar(100),
		[Work Date] varchar(20),
		[Day Type] varchar(100),
		[After Approve IN] varchar(100),
		[After Approve OUT] varchar(100),
		[Over Time Actual] varchar(100)
	) Tbl 
	where (gender!='Male' AND gender!='Female') or
	(
		CHARINDEX('E',[After Approve IN])!=0
		and CHARINDEX('E',[After Approve OUT])!=0
	)
	) AS A
	EXEC SP_XML_RemoveDocument @XMLParams
	DECLARE @Totalrecordcount int
	DECLARE @start int
	SET @Totalrecordcount = 0
	SET @start = 1 
	SELECT @Totalrecordcount = COUNT(*) FROM Ta_tbl_EmployeeApprovedData_Samsung		
	--select distinct rtrim(ltrim([work type])) from Ta_tbl_EmployeeApprovedData_Samsung	
	--select @Totalrecordcount
	--Checking whether the employee is available in timecheck or not. if not then it will update the flag value as 6 for skipping theprocess.
	update Ta_tbl_EmployeeApprovedData_Samsung set Error_Message=7
	from Ta_tbl_EmployeeApprovedData_Samsung EAD
	left outer join TA_Tbl_Employee e on EAD.[Employee ID]=e.Employee_Code_Id
	where e.Employee_Id is null
	--select * from Ta_tbl_EmployeeApprovedData_Samsung
	--return;
	/* Insert Shift Details into Timecheck*/
	delete from Ta_tbl_DummyShiftDetails
	
	insert into Ta_tbl_DummyShiftDetails
	select [New work type],ROW_NUMBER()over(order by [New work type]),[Work Type] from(
	select  distinct
	--(select value from split(replace(SUBSTRING(rtrim(ltrim([work type])),charindex('(',rtrim(ltrim([work type])))+1,len(rtrim(ltrim([work type])))),')',''),'-')),
	[New work type]=rtrim(ltrim([work type])),[work type] from Ta_tbl_EmployeeApprovedData_Samsung where Error_Message=0
	and rtrim(ltrim([work type])) not in(select Shift_Name from TA_Tbl_Shift)
	) as shifts
	
	Declare @TotalShift int
	Declare @startShift int
	Set @startShift=1
	select @TotalShift= COUNT(*) from Ta_tbl_DummyShiftDetails
	while @startShift<=@TotalShift
	begin
		Declare @ShiftName varchar(100)
		Declare @FullShiftName varchar(100)
		select @ShiftName= ShiftName,@FullShiftName=FullShiftName
		from Ta_tbl_DummyShiftDetails where recordid=@startShift
		
		if not exists(select * from TA_Tbl_Shift where Shift_Name=@FullShiftName)
		begin
			Declare @starttime varchar(20)
			Declare @EndTime varchar(20)
			
			select @starttime=starttime from(
			select row=ROW_NUMBER()over(order by @shiftname),starttime= right('00'+ltrim(substring(convert(varchar(50),convert(datetime,Value),109),13,5)),5)+' ' +
	right(convert(varchar(50),convert(datetime,Value),109),2) from split(replace(SUBSTRING(rtrim(ltrim(@ShiftName)),charindex('(',rtrim(ltrim(@ShiftName)))+1,len(rtrim(ltrim(@ShiftName)))),')',''),'-')
			)as sub where row=1
			
			select @EndTime=endTime from(
			select row=ROW_NUMBER()over(order by @shiftname),			
			endTime= 
			right('00'+ltrim(substring(convert(varchar(50),convert(datetime,Value),109),13,5)),5)+' ' +
	right(convert(varchar(50),convert(datetime,Value),109),2) from split(replace(SUBSTRING(rtrim(ltrim(@ShiftName)),charindex('(',rtrim(ltrim(@ShiftName)))+1,len(rtrim(ltrim(@ShiftName)))),')',''),'-')
			)as sub where row=2
			--select @starttime,@EndTime,@FullShiftName
			Declare @levelid bigint
			select top 1 @levelid=levelId  from Ta_Tbl_levelDetails where parentId=0 order by levelId
			Declare @maxID bigint
			select @maxID=max(shift_id)from TA_Tbl_Shift
			set @maxID=@maxID+1
			
			insert into TA_Tbl_Shift(Level_Id,Shift_Name,Shift_ShortName,Shift_StartTime,Shift_EndTime,Shift_FirstHalf_StartTime,
			Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_MinTimeOT,Shift_MaxTimeOT,Shift_WorkingDay_OverTime,
			Shift_TotalWorkingHours,Isdeleted,Emp_ID,Shift_FirstHalfWorkingHours,DefaultShift,ShiftType,CreatedDate,[24HrsShift],isStraightShift,StraightPresentTime,empCategory,specialOvertime_start1,specialOvertime_start2,MaxShiftWorkHours,Shift_GraceInTime,Shift_GraceOutTime )
			values
			(
				@levelid,@FullShiftName,'S'+convert(varchar(10),@maxID),@starttime,@EndTime,@starttime,@EndTime,@starttime,@EndTime,'00:45','04:00',1,
								case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
					 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
					 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
				end,
				0,1,
								case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
					 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
					 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
				end,
				0,
				1,getdate(),0,1,
								case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
					 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
					 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
				end,
				0,0,0,'00:00','',''
			)
			--select @levelid,@FullShiftName,'A'+SUBSTRING(@FullShiftName,1,2),@starttime,@EndTime,@starttime,@EndTime,@starttime,@EndTime,'00:45','04:00',1,
			--	case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--		 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
			--		 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--	end
			--	,0,1,
			--	case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--		 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
			--		 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--	end,
			--	0,
			--	1,getdate(),0,1,
			--	case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--		 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
			--		 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
			--	end,
			--	0,0,0,'00:00','',''
		end
		
		set @startShift=@startShift+1
	end
	
	--select * from TA_Tbl_Shift 
	--return;
	/* End of Shift Details Insertion*/
	
	--select * from Ta_tbl_EmployeeApprovedData_Samsung
	
	Declare @Employee_ID varchar(50)
	Declare @Name varchar(250)
	Declare @Organization varchar(500)
	Declare @CL_Name varchar(20)
	Declare @Gender	varchar(20)
	Declare @Work_Group varchar(100)
	Declare @Work_Type varchar(100)
	Declare @Work_Date varchar(20)
	Declare @Day_Type varchar(100)
	Declare @After_Approve_IN varchar(100)
	Declare @After_Approve_OUT varchar(100)
	Declare @Over_Time_Actual varchar(100)
	Declare @ErrorNumber int
	CREATE TABLE #TEMP (SHIFTID INT)	
	WHILE (@start<= @Totalrecordcount)
	BEGIN
		SELECT 
			@Employee_ID=[Employee ID],
			@Name=[Name],
			@Organization= [Organization] ,
			@CL_Name=[CL	Name] ,
			@Gender=Gender	,
			@Work_Group=[Work Group] ,
			@Work_Type=[Work Type] ,
			@Work_Date=[Work Date] ,
			@Day_Type=[Day Type] ,
			@After_Approve_IN=[After Approve IN] ,
			@After_Approve_OUT=[After Approve OUT] ,
			@Over_Time_Actual=[Over Time Actual],
			@ErrorNumber=[Error_Message] 
		FROM Ta_tbl_EmployeeApprovedData_Samsung WHERE RecordID = @start
		IF(@ErrorNumber=0)
		BEGIN
			--select @Work_Type,@Day_Type
			Declare @Shift_Id int
			set @Shift_Id=0
			if(@Day_Type!='Weekday')
			begin
				print 'manikandan'
				set @Shift_Id=-1
			end
			DECLARE @QUERY VARCHAR(max)  
			Declare @ShiftDate datetime
			
			Declare @AllocatedShiftID bigint			
			Declare @updateQuery varchar(max)			
			Declare @EMPLOYEEAUTOID bigint
			select @EMPLOYEEAUTOID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employee_ID
			if(@Shift_Id!=-1)
			begin
				print 'not equal -1'
				if (@EMPLOYEEAUTOID='')
				begin
					select 'Employee is not available in Timecheck'
					print 'Employee is not available in Timecheck'
					continue;
				end
				if not Exists(select Shift_Id from TA_Tbl_Shift where Shift_Name=@Work_Type)
				begin
					select 'Shift is not available'
					continue;
				end
				else
				begin
					
					select @Shift_Id=Shift_Id from TA_Tbl_Shift where Shift_Name=@Work_Type					
					set @ShiftDate=CONVERT(datetime,@Work_Date)
					SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  PSA.[MONTH]= ' + convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' +CONVERT(varchar(20), @EMPLOYEEAUTOID)
					--print (@QUERY )
					INSERT INTO #TEMP EXEC(@QUERY)
					SELECT @AllocatedShiftID =ISNULL(SHIFTID,0) FROM #TEMP	
					
					set @updateQuery=''
					if((select COUNT(*) from #TEMP)>0)
					begin
						if(@AllocatedShiftID=0 or @AllocatedShiftID!=@Shift_Id)
						begin							
							set @updateQuery=@updateQuery+ ' update TA_TBL_PERMANENTSHIFTALLOCATION set DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT='+CONVERT(varchar(20),@Shift_Id)
							set @updateQuery=@updateQuery+ ' WHERE [YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  [MONTH]= ' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = '  + CONVERT(varchar(20), @EMPLOYEEAUTOID )
							 execute(@updateQuery)
						end
						else
						begin
							select 'shift updation skipped due to same shift'
						end
					end
					else
					begin
						set @updateQuery=@updateQuery+ ' Insert into TA_TBL_PERMANENTSHIFTALLOCATION(DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT,year,month,Employeeid,Emp_Id,DateShift)'
						set @updateQuery=@updateQuery+ ' values('+Convert(varchar(20),@Shift_Id)+','+ convert(varchar(20), DATEPART(year,@ShiftDate)) + ',' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ','+convert(varchar(20),@EMPLOYEEAUTOID )
						set @updateQuery=@updateQuery+ ',1,'''+CONVERT(varchar(20),getdate())+''')'
						execute(@updateQuery)
					end
					set @updateQuery=''
					DELETE FROM #TEMP
				end
			end
			else
			begin				
				set @ShiftDate=CONVERT(datetime,@Work_Date)
				
				SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
						WHERE PSA.[YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  PSA.[MONTH]= ' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' + CONVERT(varchar(20), @EMPLOYEEAUTOID)
				INSERT INTO #TEMP EXEC(@QUERY)
				SELECT @AllocatedShiftID =ISNULL(SHIFTID,0) FROM #TEMP	
				print (@QUERY)
				set @updateQuery=''
				
				if((select COUNT(*) from #TEMP)>0)
				begin
					if(@AllocatedShiftID=0 or @AllocatedShiftID!=-1)
					begin						
						
						set @updateQuery=@updateQuery+ ' update TA_TBL_PERMANENTSHIFTALLOCATION set DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT='+CONVERT(varchar(20),@Shift_Id)
						set @updateQuery=@updateQuery+ ' WHERE [YEAR]= ' + convert(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  [MONTH]= ' + convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' + CONVERT(varchar(20), @EMPLOYEEAUTOID)
						print(@updateQuery)
						execute(@updateQuery)
					end
				end
				else
				begin
					set @updateQuery=@updateQuery+ ' Insert into TA_TBL_PERMANENTSHIFTALLOCATION(DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT,year,month,Employeeid,Emp_Id,DateShift)'
						set @updateQuery=@updateQuery+ ' values('+Convert(varchar(20),@Shift_Id)+','+ convert(varchar(20), DATEPART(year,@ShiftDate)) + ',' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ','+convert(varchar(20),@EMPLOYEEAUTOID )
						set @updateQuery=@updateQuery+ ',1,'''+CONVERT(varchar(20),getdate())+''')'
					execute(@updateQuery)
				end
				set @updateQuery=''
				DELETE FROM #TEMP
			end
			--Insert manual Time entry Table		
			
			if((@After_Approve_IN is not null and @After_Approve_IN!='') or (@After_Approve_OUT is not null or @After_Approve_OUT!=''))
			begin
				Declare @InReader_Id INT
				Declare @OutReader_Id INT
				set @InReader_Id=787
				set @OutReader_Id=788
				if(@InReader_Id=787 or @InReader_Id=0)
				BEGIN
					SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID='787'
					Declare @CountReader int
					select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReader_Id
					if(@CountReader>1)
					begin			
						set @OutReader_Id=@InReader_Id
					end	
				END
				IF(@OutReader_Id=788 or @OutReader_Id=0)
				BEGIN
					SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID='788'
				END
				Declare @YearSettings_Id  bigint
				select @YearSettings_Id= YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
				--print'Manual Time Entry'
				--select @After_Approve_OUT,@After_Approve_IN
				--return;
				IF((@After_Approve_IN = ' ' or @After_Approve_IN is null) and @After_Approve_OUT!='')
				BEGIN   
					if not exists(select * from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id=@Employee_ID and ManualTimeEntry_OutDate=convert(varchar(11),@After_Approve_OUT) and ManualTimeEntry_OutTime=right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),13,8)),8)+' ' +
		right(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),2))
					begin
						INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,
						ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,
						Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
						VALUES(@Employee_ID,cast(@Work_Date as nvarchar(20)),convert(varchar(11),@After_Approve_OUT),
						right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),13,8)),8)+' ' +
			right(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),2),
						'Shift out',@OutReader_Id,
						'Automatic Update','Approved',0,'N',0,getdate(),1
						,cast(@YearSettings_Id as nvarchar(10)),0,6) 
					end
					--select convert(varchar(11),@After_Approve_OUT)
				END
				ELSE IF((@After_Approve_OUT = ' ' or @After_Approve_OUT is null) and @After_Approve_IN!='')  
				BEGIN
					if not exists(select * from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id=@Employee_ID and ManualTimeEntry_InDate=convert(varchar(11),@After_Approve_IN) and ManualTimeEntry_InTime=right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_IN),109),13,8)),8)+' ' +
		right(convert(varchar(50),convert(datetime,@After_Approve_IN),109),2))
					begin
						INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
						VALUES(@Employee_ID,cast(@Work_Date as nvarchar(20)),
						
						convert(varchar(11),@After_Approve_IN),
						right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_IN),109),13,8)),8)+' ' +
			right(convert(varchar(50),convert(datetime,@After_Approve_IN),109),2),
						'Shift In',@InReader_Id,
						'Automatic update','Approved',0,'N',0,GETDATE(),1,cast(@YearSettings_Id as nvarchar(10)),0,6) 
					end
				ENd
				ELSE
				BEGIN
					if not exists(select * from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id=@Employee_ID and ManualTimeEntry_InDate=convert(varchar(11),@After_Approve_IN) and ManualTimeEntry_InTime=right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_IN),109),13,8)),8)+' ' +
					right(convert(varchar(50),convert(datetime,@After_Approve_IN),109),2) and ManualTimeEntry_OutDate=convert(varchar(11),@After_Approve_OUT) and ManualTimeEntry_OutTime=right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),13,8)),8)+' ' +
		right(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),2))
					begin
						INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
						VALUES(@Employee_ID,cast(@Work_Date as nvarchar(20)),convert(varchar(11),@After_Approve_IN),
						right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_IN),109),13,8)),8)+' ' +
			right(convert(varchar(50),convert(datetime,@After_Approve_IN),109),2),
						'Shift In',convert(varchar(11),@After_Approve_OUT),
						right('00'+ltrim(substring(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),13,8)),8)+' ' +
			right(convert(varchar(50),convert(datetime,@After_Approve_OUT),109),2),
						'Shift Out',@InReader_Id,@OutReader_Id,
						'Automatic Update','Approved',0,'N',0,GETDATE(),1,cast(@YearSettings_Id as nvarchar(10)),0,6) 
					end
				END
			end			
			--select @Shift_Id
		END
		ELSE
		BEGIN
			Declare @EmployeemasterFile varchar(25)
			set @EmployeemasterFile='Employee master File - ' 
			
			INSERT INTO Ta_Tbl_Error_ImportData_Samsung VALUES(@Employee_ID,
			@EmployeemasterFile+
			case when @Employee_ID is null then 'Employee Id IS Missing;' else '' end+
			case when @Work_Type is null or @Work_Type='' then ' work type was missing;' else '' end+
			case when @Work_Date is null or @Work_Date='' then ' work date was Missing;' else '' end+
			case when @Day_Type is null or @Day_Type='' then ' day type was Missing;' else '' end+
			case when (@After_Approve_IN is null or @After_Approve_IN='') and (@After_Approve_OUT is null or @After_Approve_OUT='')  then ' approved in or approved out should not be empty and check the date and time format is correct' else '' end+
			case when @ErrorNumber=6 then ' Comma was mentioned into some field, please remove it and then update the file' 
				 when @ErrorNumber=7 then 'Employee is not available in Timecheck' 
			else '' end
			,GETDATE())
		END		
		SET @start=@start+1	
	END	
	--select * from Ta_Tbl_Error_ImportData_Samsung
	--select * from Ta_tbl_EmployeeApprovedData_Samsung where Error_Message!=0
	Delete FROM 	Ta_tbl_EmployeeApprovedData_Samsung		
	drop table #temp
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ImportLeaveData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: 02-July-2019 02:46 PM
-- Description:	Import Leave Data using csv file
/*
Proc_Ta_ImportLeaveData
'<dsLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>01-Jul-2019</FromDate>
    <ToDate>01-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>02-Jul-2019</FromDate>
    <ToDate>02-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>03-Jul-2019</FromDate>
    <ToDate>03-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>04-Jul-2019</FromDate>
    <ToDate>04-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>05-Jul-2019</FromDate>
    <ToDate>05-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>06-Jul-2019</FromDate>
    <ToDate>06-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>07-Jul-2019</FromDate>
    <ToDate>07-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>08-Jul-2019</FromDate>
    <ToDate>08-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>09-Jul-2019</FromDate>
    <ToDate>09-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>10-Jul-2019</FromDate>
    <ToDate>10-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>11-Jul-2019</FromDate>
    <ToDate>11-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>12-Jul-2019</FromDate>
    <ToDate>12-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
</dsLeave>',1,'Superadmin'
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ImportLeaveData]
	@LeaveData XML = NULL,
	@EmpAutoID bigInt,
	@UserGroup VARCHAR(max)
AS
BEGIN
	Declare @local_LeaveData XML = @LeaveData
	Declare	@local_EmpAutoID bigInt=@EmpAutoID
	Declare @local_UserGroup VARCHAR(max)=@UserGroup
	
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)	
	BEGIN TRY
		BEGIN TRAN ImportLeaveData
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LeaveData	
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_UserGroup,0) AS LEVELID
				
			
			INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 
				GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
			
			create table #TempLeaveApp
			(
				autoid int identity(1,1),
				[Sl.no] NVARCHAR(20), 
				Employee_Code_Id NVARCHAR(20), 
				Fromdate NVARCHAR(20), 
				Todate NVARCHAR(20),
				LeaveType NVARCHAR(3),
				NumberOfDays float,
				Reason NVARCHAR(max),
				EmpAutoID bigint
			)	
					
			INSERT INTO #TempLeaveApp
			SELECT Tbl.*,E.Employee_Id FROM OPENXML (@XMLParams, '/dsLeave/dtLeave', 2) WITH 
			(
				[Sl.no] NVARCHAR(20), 
				Employee_Code_Id NVARCHAR(20), 
				FromDate NVARCHAR(20), 
				ToDate NVARCHAR(20), 
				LeaveType NVARCHAR(3),
				NumberOfDays float,				
				Reason NVARCHAR(max) 
			) Tbl			
			LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			AND E.IsDeleted = 0 AND E.Employee_Status = 1
			
			INSERT INTO @ErrorMsg
			SELECT autoid,Employee_Code_Id,'',1,Fromdate FROM #TempLeaveApp
			
			--select * from #TempLeaveApp
			
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp)
			BEGIN
				SET @ErrMsg = 'There is no record in the file'
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END
			IF EXISTS(SELECT EmpAutoID FROM #TempLeaveApp WHERE ISNULL(EmpAutoID, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'This employee is not created in timecheck, please remove it and then try import;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.EmpAutoID, '') = ''
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Employee_Code_Id, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Employee Id is missing;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Employee_Code_Id, '') = ''
			END			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Fromdate, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'From Date is missing;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(Fromdate,'')= ''
			END	
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Todate, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'To Date is missing;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Todate, '') = ''
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(LeaveType, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Leave Type is missing;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.LeaveType, '') = ''
			END	
			
			IF EXISTS(SELECT TLA.LeaveType FROM #TempLeaveApp TLA
			Left Outer Join TA_Tbl_LeaveType  LT on TLA.LeaveType=LT.LeaveType
			where LT.LeaveType is null and TLA.LeaveType is not null)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Leave Type is not available. Create the leave type in leave type master;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 				
				Left Outer Join TA_Tbl_LeaveType  LT on tot.LeaveType=LT.LeaveType
				where LT.LeaveType is null and tot.LeaveType is not null
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE LEN(Reason)>1000)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Reason field filled more than 1000 characters;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE LEN(Reason)>1000
			END		
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE Fromdate is not null and Todate is not null and Fromdate!='' and Todate!='' and Todate<Fromdate)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Todate should be greater than from date;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Fromdate is not null and Todate is not null and Fromdate!='' and Todate!='' and Todate<Fromdate
			END		
			
			IF Exists(
			SELECT autoid FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,fromdate ORDER BY Employee_Code_Id ASC)AS duplicate,
						autoid FROM #TempLeaveApp
			)AS A WHERE duplicate>1)
			BEGIN
				set @alertMsg='Duplication Record Found;Please find and remove duplicate record in excel file;<br />'				
				UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,fromdate ORDER BY Employee_Code_Id ASC)AS duplicate,
					Employee_Code_Id,autoid FROM #TempLeaveApp
				)AS A on EM.RecordID=a.autoid WHERE a.duplicate>1
				and ISNULL(a.Employee_Code_Id, '') != ''
			END
			IF EXISTS(SELECT t.Employee_Code_Id FROM #TempLeaveApp t INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
			LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID=''))
			BEGIN
				set @alertMsg='Employee is not available or you are not having an previlege to import leave data for this employee;<br />'				
				UPDATE @ErrorMsg SET Error_Msg=CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN #TempLeaveApp t on EM.RecordID=t.autoid				
				INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID='')
				and ISNULL(t.Employee_Code_Id, '') != ''
			END
			
			IF EXISTS(SELECT Fromdate FROM #TempLeaveApp where Fromdate>(select Todate from TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Apply Leave on available Year settings Days;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Fromdate>(select Todate from TA_Tbl_YearSetting where IsActive=1)
			END			
			
			IF EXISTS(SELECT Fromdate FROM #TempLeaveApp where Todate>(select Todate from TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Apply Leave on available Year settings Days;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Todate>(select Todate from TA_Tbl_YearSetting where IsActive=1)
			END
			
			IF EXISTS(SELECT LAE.LeaveApplicationId from #TempLeaveApp TLA 
			Inner join TA_Tbl_LeaveApplicationExists LAE on (TLA.EmpAutoID=LAE.Employee_Id and TLA.Fromdate=LAE.Leave_FromDate and TLA.Todate=LAE.Leave_ToDate)
			Inner join TA_Tbl_LeaveApplication LA on (LAE.LeaveApplicationId=LA.LeaveApplication_Id)
			where LA.IsDeleted=0 and LA.Status!='Rejected')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Leave is already updated into system for this date;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp TLA on TLA.autoid=EM.RecordID 
				Inner join TA_Tbl_LeaveApplicationExists LAE on (TLA.EmpAutoID=LAE.Employee_Id and TLA.Fromdate=LAE.Leave_FromDate and TLA.Todate=LAE.Leave_ToDate)
				Inner join TA_Tbl_LeaveApplication LA on (LAE.LeaveApplicationId=LA.LeaveApplication_Id)
				where LA.IsDeleted=0 and LA.Status!='Rejected'
			END			
			IF NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg WHERE flag=0)
			BEGIN								
				Declare @TotLeaveRecord int
				select @TotLeaveRecord=COUNT(*) from #TempLeaveApp				
				Declare @start int
				set @start=1				
				while @TotLeaveRecord>=@start
				begin					
					Declare @EmployeeID INT
					Declare @Leave_ApplicationDate DATETIME=null
					set @Leave_ApplicationDate=dbo.DateOnly(getdate())
					Declare @LeaveType_id INT
					
					Declare @Type NVARCHAR(20)
					set @Type='Leave'
					Declare @Leave_FromDate DATETIME
					Declare @Leave_ToDate DATETIME
					Declare @Leave_SessionFrom NVARCHAR(20)
					set @Leave_SessionFrom='First half'
					Declare @Leave_SessionTo NVARCHAR(20)
					set @Leave_SessionTo='Second half'
					Declare @NumberOfDays DECIMAL(8,2)
					--set @NumberOfDays =1
					Declare @Reason NVARCHAR(250)
					Declare @IsBorrow INT
					set @IsBorrow=0
					Declare @auEmpId NVARCHAR(50)
					set @auEmpId=@EmpAutoID
					Declare @YearSettings_Id NVARCHAR(20)
					select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
					Declare @LeaveStatus NVARCHAR(30)
					set @LeaveStatus='Approved'
					Declare @SuccessiveYear INT
					set @SuccessiveYear=0
					Declare @Intervening char(5)				
					set @Intervening=''
					declare @Employee_Code_Id varchar(20)
					
					Declare @leaveTypeName varchar(20)
					
					select @NumberOfDays=case when (DATEDIFF(d,Fromdate,Todate)+1)>=NumberOfDays then DATEDIFF(d,Fromdate,Todate)+1 else NumberOfDays end,
						@leaveTypeName=LeaveType,@Employee_Code_Id=Employee_Code_Id,@EmployeeID=EmpAutoID,@Leave_FromDate=Fromdate,@Leave_ToDate=Todate,@Reason=Reason 
						from #TempLeaveApp where autoid=@start
					select @LeaveType_id=LeaveType_Id from TA_Tbl_LeaveType where LeaveType=@leaveTypeName

					
					Declare @SwipCardNo varchar(20)
					select @SwipCardNo =SwipeCardNo from TA_Tbl_Employee where Employee_Code_Id=@Employee_Code_Id and Isdeleted=0
					--select @EmployeeID,@Leave_ApplicationDate,
					--@LeaveType_id,@Type,@Leave_FromDate,@Leave_ToDate,@Leave_SessionFrom ,@Leave_SessionTo ,
					--@NumberOfDays ,@Reason ,@IsBorrow,@auEmpId,@YearSettings_Id,@LeaveStatus ,@SuccessiveYear ,@Intervening
					
					Execute [Proc_TA_InsertLeaveApplication] @EmployeeID,@Leave_ApplicationDate,
					@LeaveType_id,@Type,@Leave_FromDate,@Leave_ToDate,@Leave_SessionFrom ,@Leave_SessionTo ,
					@NumberOfDays ,@Reason ,@IsBorrow,@auEmpId,@YearSettings_Id,@LeaveStatus ,@SuccessiveYear ,@Intervening
					
					delete from TA_Tbl_ProcessedData
					--update TA_Tbl_ProcessedData set ProcessFlag=0 
					where Employee_Code_Id=@SwipCardNo
					and (Date>=@Leave_FromDate and Date<=@Leave_ToDate)
					
					set @start=@start+1
				end
			END
			ELSE 
			BEGIN
				SELECT	RecordID=RecordID+1,
						Employee_Id, 
						Error_Msg,
						date
				FROM @ErrorMsg where flag=0
			END
		COMMIT TRAN ImportLeaveData
			SELECT 'Msg:DataImportedSuccessfully' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportLeaveData
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
	END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportMasterData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		< Karthikeyan.R >
-- Create date: < 09-Apr-2017 >
-- Description:	< Import master data from the XML >
/*
Proc_TA_ImportMasterData '
<NewDataSet>
  <TheData>
    <Sl_x0023_No>1</Sl_x0023_No>
    <EmployeeFirstName>a</EmployeeFirstName>
    <EmployeeMiddleName>b</EmployeeMiddleName>
    <EmployeeLastName>c</EmployeeLastName>
    <FatherName>d</FatherName>
    <MotherName>e</MotherName>
    <DateOfBirth>1990-06-02T00:00:00+05:30</DateOfBirth>
    <DateOfBirthInRecord>1990-06-02T00:00:00+05:30</DateOfBirthInRecord>
    <BloodGroup>B-ve</BloodGroup>
    <OfficialMailID>manikandan.rr@angleritech.com</OfficialMailID>
    <ContactAddress>f</ContactAddress>
    <PermanentAddress>g</PermanentAddress>
    <PhoneNumber>h</PhoneNumber>
    <MobileNumber>i</MobileNumber>
    <Gender>Female</Gender>
    <MaritalStatus>Single</MaritalStatus>
    <Nationality>j</Nationality>
    <ReligionName>k</ReligionName>
    <PersonalMailID>manikandan.rr@angleritech.com</PersonalMailID>
    <PassportNo>l</PassportNo>
    <PassportExpiryDate>2020-09-01T00:00:00+05:30</PassportExpiryDate>
    <VisaNo>m</VisaNo>
    <VisaExpiryDate>2020-09-01T00:00:00+05:30</VisaExpiryDate>
    <EmployeeID>o123</EmployeeID>
    <SwipeCardNo>o123</SwipeCardNo>
    <DateOfJoining>2011-03-05T00:00:00+05:30</DateOfJoining>
    <QualificationonJoiningTime>p</QualificationonJoiningTime>
    <QualificationDuringEmployement>q</QualificationDuringEmployement>
    <CompOffEligible>0</CompOffEligible>
    <OTEligible>0</OTEligible>
    <Hostel>r</Hostel>
    <Designation>s</Designation>
    <GradeName>Grade2</GradeName>
    <GradeNo>2</GradeNo>
    <EmployeeType>t</EmployeeType>
    <EmployeeCategory>u</EmployeeCategory>
    <BasicSalary>500</BasicSalary>
    <Company>v</Company>
    <Region>w</Region>
    <Level1>x</Level1>
    <Level2>y</Level2>
  </TheData>
</NewDataSet>','Enterprise','False',1
select * from TA_Tbl_Employee
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ImportMasterData]
	-- Add the parameters for the stored procedure here
	@Xml XML,
	@Version nvarchar(50),
	@ApplnMode BIT,
	@FromXL int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Index INT 
	set @Index= 0
	declare @Error nvarchar(Max)
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	create table #ImportMaster 
	(
		id bigint identity(1,1),
		Sl_x0023_No bigint,
		Emp_FirstName nvarchar(50),
		Emp_MiddleName  nvarchar(50),
		Emp_LastName nvarchar(50),
		Father_Name nvarchar(50),
		Mother_Name nvarchar(50),
		DateOfBirth nvarchar(20),
		DateOfBirth_Record nvarchar(20),
		Blood_Group nvarchar(5),
		Email_Id nvarchar(100) ,
		Contact_Address nvarchar(250),
		Permanent_Address nvarchar(250),
		Phone_Number nvarchar(50),
		Mobile_Number nvarchar(50),
		Gender nvarchar(50),
		Marital_Status nvarchar(50),
		Nationality nvarchar(50),
		Religion nvarchar(50),
		Personal_EmailID nvarchar(100),
		Passport_No nvarchar(100),
		Passport_ExpiryDate nvarchar(20),
		Visa_No nvarchar(100),
		Visa_ExpiryDate nvarchar(20),
		Employee_Code nvarchar(25),
		SwipeCardNo nvarchar(25),
		DateOfJoining nvarchar(20),
		Qualification_joiningtime nvarchar(25),
		Qualification_Employement nvarchar(25),
		CompOff_Eligible nvarchar(1),
		OT_Eligible nvarchar(1),
		Hostel nvarchar(1),
		Designation nvarchar(50),
		Grade nvarchar(50),
		GradeNo nvarchar(50),
		Employee_Type nvarchar(50),
		Employee_Category nvarchar(50),
		BasicSalary nvarchar(10),
		Level1 nvarchar(50),
		Level2 nvarchar(50),
		Level3 nvarchar(50) ,
		Level4 nvarchar(50),
		Level5 nvarchar(50),
		Level6 nvarchar(50),
		Level7 nvarchar(50),
		Level8 nvarchar(50),
		Level9 nvarchar(50),
		Level10 nvarchar(50),
		IsValid int,
		Error Nvarchar(Max)
	)
	insert into  #ImportMaster
	select 
		Sl#No,
		rtrim(ltrim(EmployeeFirstName)),
		rtrim(ltrim(EmployeeMiddleName)),
		rtrim(ltrim(EmployeeLastName)),
		rtrim(ltrim(FatherName)),
		rtrim(ltrim(MotherName)),
		rtrim(ltrim(DateOfBirth)),
		rtrim(ltrim(DateOfBirthInRecord)),
		rtrim(ltrim(BloodGroup)),
		rtrim(ltrim(OfficialMailID)),
		rtrim(ltrim(ContactAddress)),
		rtrim(ltrim(PermanentAddress)),
		rtrim(ltrim(PhoneNumber)),
		rtrim(ltrim(MobileNumber)),
		rtrim(ltrim(Gender)),
		rtrim(ltrim(MaritalStatus)),
		rtrim(ltrim(Nationality)),
		rtrim(ltrim(ReligionName)),
		rtrim(ltrim(PersonalMailID)),
		rtrim(ltrim(PassportNo)),
		rtrim(ltrim(PassportExpiryDate)),
		rtrim(ltrim(VisaNo)),
		rtrim(ltrim(VisaExpiryDate)),
		rtrim(ltrim(EmployeeID)),
		rtrim(ltrim(SwipeCardNo)),
		rtrim(ltrim(DateOfJoining)),
		rtrim(ltrim(QualificationonJoiningTime)),
		rtrim(ltrim(QualificationDuringEmployement)),
		rtrim(ltrim(CompOffEligible)),
		rtrim(ltrim(OTEligible)),
		rtrim(ltrim(Hostel)),
		rtrim(ltrim(Designation)),
		rtrim(ltrim(GradeName)),
		rtrim(ltrim(GradeNo)),
		rtrim(ltrim(EmployeeType)),
		rtrim(ltrim(EmployeeCategory)),
		rtrim(ltrim(BasicSalary)),
		rtrim(ltrim(Level1)),
		rtrim(ltrim(Level2)),
		rtrim(ltrim(Level3)),
		rtrim(ltrim(Level4)),
		rtrim(ltrim(Level5)),
		rtrim(ltrim(Level6)),
		rtrim(ltrim(Level7)),
		rtrim(ltrim(Level8)),
		rtrim(ltrim(Level9)),
		rtrim(ltrim(Level10)),
		0,'' from OPENXML(@Index, '/NewDataSet/TheData',2)
	WITH(
			Sl#No nvarchar(50),
			EmployeeFirstName  nvarchar(50),
			EmployeeMiddleName   nvarchar(50),
			EmployeeLastName  nvarchar(50),
			FatherName nvarchar(50),
			MotherName nvarchar(50),
			DateOfBirth nvarchar(11),
			DateOfBirthInRecord nvarchar(11),
			BloodGroup nvarchar(5),
			OfficialMailID nvarchar(100),
			ContactAddress nvarchar(250),
			PermanentAddress nvarchar(250),
			PhoneNumber nvarchar(50),
			MobileNumber nvarchar(50),
			Gender nvarchar(50),
			MaritalStatus nvarchar(50),
			Nationality nvarchar(50),
			ReligionName nvarchar(50),
			PersonalMailID nvarchar(100),
			PassportNo nvarchar(100),
			PassportExpiryDate nvarchar(11),
			VisaNo nvarchar(100),
			VisaExpiryDate nvarchar(11),
			EmployeeID nvarchar(25),
			SwipeCardNo nvarchar(25),
			DateOfJoining nvarchar(11),
			QualificationonJoiningTime nvarchar(25),
			QualificationDuringEmployement nvarchar(25),
			CompOffEligible nvarchar(1),
			OTEligible nvarchar(1),
			Hostel nvarchar(1),
			Designation nvarchar(50),
			GradeName nvarchar(50),
			GradeNo nvarchar(50),
			EmployeeType nvarchar(50),
			EmployeeCategory nvarchar(50),
			BasicSalary nvarchar(10),
			Level1 nvarchar(50) 'Level1',
			Level2 nvarchar(50) 'Level2',
			Level3 nvarchar(50) 'Level3',
			Level4 nvarchar(50) 'Level4',
			Level5 nvarchar(50) 'Level5',
			Level6 nvarchar(50) 'Level6',
			Level7 nvarchar(50) 'Level7',
			Level8 nvarchar(50) 'Level8',
			Level9 nvarchar(50) 'Level9',
			Level10 nvarchar(50) 'Level10'
		  ) AS OT 
		--select * from #ImportMaster
		declare @Count as int=0
		Declare @Start int
		select @Count=COUNT(*) from #ImportMaster
		set @Start=1
		declare @isDateValid int
		declare @RowCount int
		declare @isDate nvarchar(50)
		declare @DateLength int
		declare @EmployeeCodeID nvarchar(50)
		declare @ValidateEmail nvarchar(100)
		declare @ErrorCount int=0
		declare @GradeName nvarchar(50)
		declare @GradeLevel nvarchar(50)
		declare @ImportGradeLevel nvarchar(50)
		declare @Designation as nvarchar(255)
		declare @Grade as nvarchar(255)
		declare @ImportGrade as nvarchar(255)
		declare @DateOfBirth as nvarchar(50)
		set @Error = ''
		if(@FromXL=1)
			begin
				update #ImportMaster set 
				
				DateOfBirth= case when DateOfBirth is not null and  DateOfBirth!='' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfBirth as nvarchar(10)) as datetime),106),' ','-')
				else '' end,
				DateOfBirth_Record=case when DateOfBirth_Record is not null and  DateOfBirth_Record!='' then
					REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfBirth_Record as nvarchar(10)) as datetime),106),' ','-')
				else '' end,
				Passport_ExpiryDate=
				case when Passport_ExpiryDate is not null and  Passport_ExpiryDate!='' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(Passport_ExpiryDate as nvarchar(10)) as datetime),106),' ','-')
				else '' end,
				Visa_ExpiryDate=
				case when Visa_ExpiryDate is not null and  Visa_ExpiryDate!='' then	
					REPLACE(CONVERT(NVARCHAR,CAST(CAST(Visa_ExpiryDate as nvarchar(10)) as datetime),106),' ','-')
					else '' end,
				DateOfJoining=case when DateOfJoining is not null and  DateOfJoining!='' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfJoining as nvarchar(10)) as datetime),106),' ','-')
				else '' end
			end
		while @Start<=@Count
			BEGIN
				--Check Employee First name is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Emp_FirstName IS NULL OR Emp_FirstName = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  '.Employee First Name is missing<br/>'
					end
				set @RowCount =0
				select @ValidateEmail=Email_Id from #ImportMaster where id=@Start 
				if(isnull(@ValidateEmail,'')!='')
					begin
						if(@ValidateEmail NOT LIKE '_%@__%.__%')
							BEGIN
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  '.Invalid Mail ID<br/>'
							END
					end
				--Reset all values
				set @RowCount =0
				select @ValidateEmail=Personal_EmailID from #ImportMaster where id=@Start
				if(isnull(@ValidateEmail,'')!='')
					begin
						if(@ValidateEmail NOT LIKE '_%@__%.__%')
							BEGIN
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  '.Invalid Mail ID<br/>'
							END
					end
				--Reset all values
				set @RowCount =0
				--Check Gender is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Gender IS NULL OR Gender = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Gender is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Code is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Code IS NULL OR Employee_Code = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Employee ID is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check DateOfJoining is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (DateOfJoining IS NULL OR DateOfJoining = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Date Of Joining is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check Designation is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Designation IS NULL OR Designation = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Designation is missing <br/>'
					end
				--Reset all values
				set @RowCount =0
				if(@Version='Enterprise')
					begin
						--Check Grade is null or empty
						select @RowCount=COUNT(*) from #ImportMaster where (Grade IS NULL OR Grade = '') and id=@Start
						if(isnull(@RowCount,0)>0)
							begin	
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Grade is missing<br/>'
							end
						--Reset all values
						set @RowCount =0
						--Check GradeNo is null or empty
						select @RowCount=COUNT(*) from #ImportMaster where (GradeNo IS NULL OR GradeNo = '') and id=@Start
						if(isnull(@RowCount,0)>0)
							begin	
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Grade No. is missing <br/>'
							end
							--Reset all values
							select top 1 @GradeName=grade_Name,@GradeLevel=Grade_Level,@ImportGradeLevel=GradeNo from
							(select  distinct ta_tbl_grade.grade_Name,ta_tbl_grade.Grade_Level,#ImportMaster.GradeNo from #ImportMaster 
							inner join ta_tbl_grade on ta_tbl_grade.grade_Name=#ImportMaster.grade and ta_tbl_grade.Grade_Level<>#ImportMaster.GradeNo 
							where ta_tbl_grade.isdeleted=0 and #ImportMaster.id=@Start) GradeTable
							declare @errMessage as nvarchar(4000)
							--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
							if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
								begin
									if(@GradeName<>'')
									BEGIN
										set @ErrorCount=@ErrorCount+1
										set @Error=@Error + CAST(@ErrorCount as nvarchar(10)) + '.Grade Name : ' + @GradeName +  ' has different GradeNo (' + @ImportGradeLevel + ') in the Employee Import file. Change the GradeNo as ' + @GradeLevel + ' <br/>'
									END
								end
							select top 1 @Designation=TitleName,@Grade=grade_Name,@ImportGrade=Grade from
								(select  distinct ta_tbl_title.TitleName,ta_tbl_grade.grade_Name,#ImportMaster.Grade from #ImportMaster
								inner join ta_tbl_title on  ta_tbl_title.TitleName=#ImportMaster.Designation 
								inner join ta_tbl_grade on ta_tbl_grade.Grade_Id=ta_tbl_title.GradeId and ta_tbl_grade.grade_Name<>#ImportMaster.grade
								where ta_tbl_grade.isdeleted=0 and #ImportMaster.id=@Start) GradeTable 
								if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
								begin
								if(@Designation<>'')
									BEGIN
										set @ErrorCount=@ErrorCount+1
										set @Error=@Error +  CAST(@ErrorCount as nvarchar(10)) + '.Designation : ' + @Designation +  ' has different Grade (' + @ImportGrade + ') in the Employee Import file. Change the Grade as ' + @Grade + ' <br/>'
									END
								END				
						set @RowCount =0
					END
				--Check Employee_Type is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Type IS NULL OR Employee_Type = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Employee Type is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Category is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Category IS NULL OR Employee_Category = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Employee Category is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check Level1 is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Level1 IS NULL OR Level1 = '') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Oraganization Level is missing<br/>'
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid Gender
				select @RowCount=COUNT(*) from #ImportMaster where Gender <> 'female' AND Gender <> 'male' and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Gender should be either Male or Female <br/>'
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid CompOff_Eligible
				select @RowCount=COUNT(*) from #ImportMaster where (CompOff_Eligible<>'0' AND CompOff_Eligible<>'1') AND (CompOff_Eligible<>'') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Comp Off Eligible should be either 0 or 1 <br/>'
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid OT_Eligible
				select @RowCount=COUNT(*) from #ImportMaster where (OT_Eligible<>'0' AND OT_Eligible<>'1') AND (OT_Eligible<>'') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.OT Eligible should be either 0 or 1 <br/>'
					end				
				--Reset all values
				set @RowCount =0
				--Enter the valid Hostel
				select @RowCount=COUNT(*) from #ImportMaster where (Hostel<>'0' AND Hostel<>'1') AND (Hostel<>'') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Hostel should be either 0 or 1 <br/>'
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Code
				select @EmployeeCodeID=Employee_Code from #ImportMaster where id=@Start
				select @RowCount=COUNT(*) from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeID
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Employee ID is already available.<br/>'
					end
				--Reset all values
				set @RowCount =0
				-- Check if DateOfBirth is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfBirth from #ImportMaster where (DateOfBirth IS Not NULL And DateOfBirth != '') and id=@Start group by DateOfBirth
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Birth Format is(dd-MMM-yyyy) <br/>'
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Birth Format is(dd-MMM-yyyy) <br/>'
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''
				set @DateLength=0
				-- Check if DateOfJoining is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfJoining from #ImportMaster where (DateOfJoining IS Not NULL And DateOfJoining != '') and id=@Start group by DateOfJoining
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Joining Format is(dd-MMM-yyyy) <br/>'
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Joining Format is(dd-MMM-yyyy) <br/>'
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''
				set @DateLength=0
				-- Check if DateOfBirth_Record is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfBirth_Record from #ImportMaster where (DateOfBirth_Record IS Not NULL And DateOfBirth_Record != '') and id=@Start group by DateOfBirth_Record
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Birth Record Format is (dd-MMM-yyyy) <br/>'
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Date Of Birth Record Format is(dd-MMM-yyyy) <br/>'
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''
				set @DateLength=0
				-- Check if Passport_ExpiryDate is valid or invalid
				select @RowCount=COUNT(*),@isDate=Passport_ExpiryDate from #ImportMaster where (Passport_ExpiryDate IS Not NULL And Passport_ExpiryDate != '') and id=@Start group by Passport_ExpiryDate
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)					
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Passport Expiry Date Format is (dd-MMM-yyyy) <br/>'
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Passport Expiry Date Format is(dd-MMM-yyyy) <br/>'
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''
				set @DateLength=0
				-- Check if Visa_ExpiryDate is valid or invalid
				select @RowCount=COUNT(*),@isDate=Visa_ExpiryDate from #ImportMaster where (Visa_ExpiryDate IS Not NULL And Visa_ExpiryDate != '') and id=@Start group by Visa_ExpiryDate
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate)
					select @DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Visa Expiry Date Format is (dd-MMM-yyyy) <br/>'
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +'.Please check the Visa Expiry Date Format is (dd-MMM-yyyy) <br/>'
					End
				end
				--select @Error
				if(@Error!='')
					begin
						--SELECT SUBSTRING(@Error,1, len(@Error)-2)
						update #ImportMaster set IsValid=2,Error=SUBSTRING(@Error,1, len(@Error)-2) where id=@Start
					end
					--adfadsf-
				--else
				--	begin
				--		update #ImportMaster set IsValid=1 where id=@Start
				--		INSERT INTO [Ta_Tbl_ImportMasterData]([Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],[OutDoorJob],[CompOff_Eligible],[OT_Eligible],[ESI_Eligible],[PF_Eligible],[Report_Exclude],[Employee_Status],[SwipeCardNo],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[EmployeeType],[EmployeeCategory],[BasicSalary],[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10])
				--		select [Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],0,[CompOff_Eligible],[OT_Eligible],0,0,[Report_Exclude],[Employee_Status],[Employee_Code],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[Employee_Type],[Employee_Category],case when ISNULL([BasicSalary],'')='' then 0  else [BasicSalary] end,[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10] from #ImportMaster where id=@Start
				--		exec Proc_TA_InsertMasterDataLevelsParent
				--		exec Proc_TA_UpdateMasterDataLevelsParent 
				--		exec Proc_TA_InsertMasterData @ApplnMode
				--		exec Proc_TA_CreateUpdateMasterDataLevelsChild @ApplnMode
				--		delete TA_Tbl_ImportMasterError where id=(select isnull(TableID,0) from  #ImportMaster  where id=@Start)
				--	end	
				set @Error=''
				set @ErrorCount=0
				set @Start=@Start+1
			END
		--Insert invalid data from temp table to TA_Tbl_ImportMasterError table
		if exists(select * from #ImportMaster where IsValid=2)
		begin
			insert into TA_Tbl_ImportMasterError  
			select Emp_FirstName ,Emp_MiddleName  ,Emp_LastName ,Father_Name ,Mother_Name ,DateOfBirth ,DateOfBirth_Record ,Blood_Group ,Email_Id,Contact_Address ,Permanent_Address ,Phone_Number ,Mobile_Number ,Gender ,Marital_Status ,Nationality ,Religion ,Personal_EmailID ,Passport_No ,Passport_ExpiryDate ,Visa_No ,Visa_ExpiryDate ,Employee_Code ,DateOfJoining ,Qualification_joiningtime ,Qualification_Employement ,CompOff_Eligible ,OT_Eligible ,0 ,0,0,Hostel ,Designation ,Grade ,GradeNo ,Employee_Type ,Employee_Category ,BasicSalary ,Level1 ,Level2 ,Level3 ,Level4 ,Level5 ,Level6 ,Level7 ,Level8 ,Level9 ,Level10 ,IsValid ,Error,id from  #ImportMaster where IsValid=2
		end
		else if not exists(select * from #ImportMaster where IsValid=2)
		begin
			set @Start=1
			while @Start<=@Count
			begin
				update #ImportMaster set IsValid=1 where id=@Start
				INSERT INTO [Ta_Tbl_ImportMasterData]([Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],[OutDoorJob],[CompOff_Eligible],[OT_Eligible],[ESI_Eligible],[PF_Eligible],[Report_Exclude],[Employee_Status],[SwipeCardNo],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[EmployeeType],[EmployeeCategory],[BasicSalary],[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10])
				select [Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],0,[CompOff_Eligible],[OT_Eligible],0,0,0,0,[SwipeCardNo],0,[Hostel],[Designation],[Grade],[GradeNo],[Employee_Type],[Employee_Category],case when ISNULL([BasicSalary],'')='' then 0  else [BasicSalary] end,[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10] from #ImportMaster where id=@Start
				exec Proc_TA_InsertMasterDataLevelsParent
				exec Proc_TA_UpdateMasterDataLevelsParent 
				exec Proc_TA_InsertMasterData @ApplnMode
				exec Proc_TA_CreateUpdateMasterDataLevelsChild @ApplnMode
				delete TA_Tbl_ImportMasterError 
				set @Start=@Start+1
			end
			delete TA_Tbl_ImportMasterError 
		end
		drop table #ImportMaster		
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportOndutyData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	21-Aug-2014
 EXEC [Proc_TA_ShiftAllcation_Import] @ShiftData = '<Dst_ShiftAlloc>
  <Tbl_ShiftAlloc>
  </Tbl_ShiftAlloc></Dst_ShiftAlloc>'
-- =============================================
*/
CREATE PROCEDURE [dbo].[Proc_TA_ImportOndutyData]
	@OndutyImportData XML = NULL,
	@EmpAutoID bigINT,
	@UserGroup VARCHAR(max)
AS
BEGIN
	SET  NOCOUNT ON
	--insert into TestingOndutyImport values(@OndutyImportData,@EmpAutoID,@UserGroup)
	DECLARE @XMLParams INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @local_OndutyData XML = @OndutyImportData
	Declare	@local_EmpAutoID bigINT=@EmpAutoID
	DECLARE @local_UserGroup VARCHAR(max)=@UserGroup
	BEGIN TRY
		BEGIN TRAN ImportOndutyData			
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_OndutyData
			CREATE TABLE #TempOndutyImportData
			(
				Employee_Id NVARCHAR(50) NULL,
				FROMDate NVARCHAR(11),
				FROMTime NVARCHAR(11),
				Todate NVARCHAR(11),
				Totime NVARCHAR(11),
				Reason  NVARCHAR(max),
				[ImportID] [INT] IDENTITY(1,1),
				ErrorNo INT default(0),
				Approve_status varchar(20)
			)
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			DECLARE @ErrorMsg TABLE
			(
				RecordID INT,
				Employee_Id VARCHAR(100), 
				Error_Msg VARCHAR(MAX),
				flag bit default(1)--1 is fine 0 means not fine.
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_UserGroup,0) AS LEVELID
			INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 
				GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
			INSERT INTO #TempOndutyImportData
			SELECT EmployeeId, FROMdate,FROMtime,todate,totime,reason,
			CASE WHEN EmployeeID IS null or Employeeid='' then 1 
				 When (tbl.FROMdate is null or tbl.FROMdate='') and (tbl.ToDate is null or tbl.ToDate='') then 2
				 When (tbl.FROMTime is null or tbl.FROMTime='') and (tbl.ToTime is null or tbl.ToTime='') then 3
				 When (len(tbl.FROMdate)>11 or LEN(tbl.ToDate)>11) then 4				 
			END,
			Status
			FROM OPENXML (@XMLParams, '/DocumentElement/Data', 2) WITH 
			(
				EmployeeId NVARCHAR(50), 
				FromDate NVARCHAR(11), 
				FromTime NVARCHAR(11), 
				ToDate NVARCHAR(11),
				ToTime NVARCHAR(11), 
				Reason NVARCHAR(500),
				Status NVARCHAR(20)
			) Tbl
			LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.EmployeeId
			AND E.IsDeleted = 0 AND E.Employee_Status = 1
			EXEC SP_XML_RemoveDocument @XMLParams
			INSERT INTO @ErrorMsg
			SELECT ImportID,Employee_Id,
			case when ErrorNo=1 then 'Employee ID is missing;' else '' end+
			case when ErrorNo=2 then 'FROM and Todate is missing;' else '' end+
			case when ErrorNo=3 then 'FROM and To time is missing;' else '' end+
			case when ErrorNo=4 then 'FROM or Todate format is wrong;' else '' end
			,case when isnull(ErrorNo,0)!=0 then 0 else 1 end FROM #TempOndutyImportData
			IF NOT EXISTS(SELECT Employee_Id FROM @ErrorMsg)
			BEGIN
				SET  @ErrMsg = 'There is no record in the file'
				SET  @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END
			IF EXISTS(SELECT Employee_Id FROM #TempOndutyImportData WHERE LEN(Reason)>500)
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Reason field filled more than 1000 characters;<br />',flag=0
				FROM #TempOndutyImportData TOD
				inner join @ErrorMsg EM on EM.Employee_Id=TOD.Employee_Id
				WHERE LEN(Reason)>500
			END	
			IF EXISTS(SELECT Employee_Id FROM #TempOndutyImportData WHERE FROMdate is not null and Todate is not null and FROMdate!='' and Todate!='' and Todate<FROMdate)
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Todate should be greater than FROM date;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempOndutyImportData TOD on EM.Employee_Id=TOD.Employee_Id
				WHERE FROMdate is not null and Todate is not null and FROMdate!='' and Todate!='' and Todate<FROMdate
			END		
			--print 's11'
			DECLARE @alertMsg varchar(500)
			IF Exists(
			SELECT ImportID FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,FROMdate ORDER BY Employee_Id ASC)AS duplicate,
						[ImportID] FROM #TempOndutyImportData
			)AS A WHERE duplicate>1)
			BEGIN
				SET  @alertMsg='Duplication Record Found;Please find and remove duplicate record in excel file;<br />'				
				UPDATE @ErrorMsg SET  Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,FROMdate ORDER BY Employee_Id ASC)AS duplicate,
					Employee_Id,[ImportID] FROM #TempOndutyImportData
				)AS A on EM.RecordID=a.[ImportID] WHERE a.duplicate>1
				and ISNULL(a.Employee_Id, '') != ''
			END
			IF Exists(
			SELECT ImportID FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Todate ORDER BY Employee_Id ASC)AS duplicate,
						[ImportID] FROM #TempOndutyImportData
			)AS A WHERE duplicate>1)
			BEGIN
				SET  @alertMsg='Duplication Record Found;Please find and remove duplicate record in excel file;<br />'				
				UPDATE @ErrorMsg SET  Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 
				FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Todate ORDER BY Employee_Id ASC)AS duplicate,
					Employee_Id,[ImportID] FROM #TempOndutyImportData
				)AS A on EM.RecordID=a.[ImportID] WHERE a.duplicate>1
				and ISNULL(a.Employee_Id, '') != ''
			END
			IF EXISTS(SELECT t.Employee_Id FROM #TempOndutyImportData t INNER JOIN ta_tbl_employee e on t.Employee_Id=e.Employee_Code_Id
			LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID=''))
			BEGIN
				SET  @alertMsg='Employee is not available or you are not having an previlege to import onduty data for this employee;<br />'				
				UPDATE @ErrorMsg SET  Error_Msg=CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN #TempOndutyImportData t on EM.Employee_Id=t.Employee_Id				
				INNER JOIN ta_tbl_employee e on t.Employee_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID='')
				and ISNULL(t.Employee_Id, '') != ''
			END
			IF EXISTS(SELECT FROMdate FROM #TempOndutyImportData where FROMdate>(SELECT Todate FROM TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Apply onduty on available Year Settings Days;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempOndutyImportData tot on tot.ImportID=EM.RecordID 
				WHERE FROMdate>(SELECT Todate FROM TA_Tbl_YearSetting where IsActive=1)
			END
			IF EXISTS(SELECT Todate FROM #TempOndutyImportData where Todate>(SELECT Todate FROM TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Apply onduty on available Year Settings Days;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempOndutyImportData tot on tot.ImportID=EM.RecordID 
				WHERE Todate>(SELECT Todate FROM TA_Tbl_YearSetting where IsActive=1)
			END			
			IF EXISTS(SELECT TOD.Employee_Id FROM #TempOndutyImportData TOD 
			Inner join TA_Tbl_OndutyEntry Od on TOD.Employee_Id=Od.Onduty_EmployeeID and((Od.Onduty_FROMDate between TOD.FROMDate and TOD.Todate) or (Od.Onduty_ToDate between TOD.FROMDate and TOD.Todate))
			where Od.Isdeleted=0 and Od.Onduty_Status!='Rejected')
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Onduty Entry is already updated in to system for this date separately / combined, please check and remove;<br />',flag=0 
				--select * 
				FROM @ErrorMsg EM
				inner join #TempOndutyImportData TOD on TOD.ImportID=EM.RecordID 
				Inner join TA_Tbl_OndutyEntry Od on TOD.Employee_Id=Od.Onduty_EmployeeID and((TOD.FROMDate between Od.Onduty_FromDate and Od.Onduty_ToDate) or (TOD.Todate between OD.Onduty_FromDate and OD.Onduty_ToDate))
				where Od.Isdeleted=0 and Od.Onduty_Status!='Rejected'
			END
			IF EXISTS(SELECT TOD.Employee_Id FROM #TempOndutyImportData TOD 
			Inner join TA_Tbl_OndutyEntry Od on TOD.Employee_Id=Od.Onduty_EmployeeID and((Od.Onduty_FROMDate between TOD.FROMDate and TOD.Todate) or (Od.Onduty_ToDate between TOD.FROMDate and TOD.Todate))
			where Od.Isdeleted=0 and Od.Onduty_Status!='Rejected')
			BEGIN
				UPDATE @ErrorMsg SET  Error_Msg=isnull(Error_Msg,'')+'Onduty Entry is already updated in to system for this date separately / combined, please check and remove;<br />',flag=0 
				--select * 
				FROM @ErrorMsg EM
				inner join #TempOndutyImportData TOD on TOD.ImportID=EM.RecordID 
				Inner join TA_Tbl_OndutyEntry Od on TOD.Employee_Id=Od.Onduty_EmployeeID and((Od.Onduty_FROMDate between TOD.FROMDate and TOD.Todate) or (Od.Onduty_ToDate between TOD.FROMDate and TOD.Todate))
				where Od.Isdeleted=0 and Od.Onduty_Status!='Rejected' and flag=1
			END
			IF NOT EXISTS(select RecordID from @ErrorMsg where ISNULL(flag,0)=0)
			BEGIN
				DECLARE @TotLeaveRecord INT
				SELECT @TotLeaveRecord=COUNT(*) FROM #TempOndutyImportData				
				DECLARE @start INT
				DECLARE @type NVARCHAR(2)
				DECLARE @Onduty_ID INT
				DECLARE @Onduty_EmployeeID NVARCHAR(20)
				DECLARE @Onduty_EntryDate	DATETIME
				DECLARE @Onduty_Type INT
				DECLARE @IncludeweekOff INT
				DECLARE @Onduty_FROMDate DATETIME
				DECLARE @Onduty_FROMTime NVARCHAR(50)
				DECLARE @Onduty_ToDate DATETIME
				DECLARE @Onduty_ToTime NVARCHAR(50)
				DECLARE @Onduty_Reason NVARCHAR(Max)
				DECLARE @Onduty_Status NVARCHAR(25)
				DECLARE @Emp_Id INT
				DECLARE @FROM_Session NVARCHAR(25)
				DECLARE @To_Session NVARCHAR(25)
				DECLARE @INPUNCHTYPE NVARCHAR(25)
				DECLARE @OUTPUNCHTYPE NVARCHAR(25)
				SET  @INPUNCHTYPE='IN'
				SET  @OUTPUNCHTYPE='OUT'
				
				DECLARE @OUTREADER_ID INT
				DECLARE @INREADER_ID INT
				DECLARE @YEARSETTINGID INT
				SELECT @YEARSETTINGID = YearSettings_Id FROM TA_Tbl_YearSetting WHERE [ISACTIVE] = 1 
				DECLARE	@RETURN_VALUE bigINT
				DECLARE @Diff INT
				DECLARE @Reasonvalue varchar(500)
				SET  @start=1
				--IN READER ID
				BEGIN
					SELECT @INREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='787'
				END
				--OUT READER ID
				BEGIN
					SELECT @OUTREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='788'
					IF(isnull(@OUTREADER_ID,'')='')
					BEGIN
						SELECT @OUTREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID='787'	
					END					
				END	
				--select @OUTREADER_ID as outerreader
				IF NOT EXISTS(SELECT PunchType_Id FROM TA_Tbl_PunchTypes where Terminal_Id=@INREADER_ID and PunchType=@INPUNCHTYPE)
				BEGIN
					SELECT @INPUNCHTYPE=PunchType FROM TA_Tbl_PunchTypes where Terminal_Id=@INREADER_ID and PunchType='Shift In'
				END
				IF NOT EXISTS(select PunchType_Id from TA_Tbl_PunchTypes where Terminal_Id=@OUTREADER_ID and PunchType=@OUTPUNCHTYPE)
				BEGIN
					SELECT @OUTPUNCHTYPE=PunchType FROM TA_Tbl_PunchTypes where Terminal_Id=@OUTREADER_ID and PunchType='Shift Out'
				END
				WHILE @TotLeaveRecord>=@start
				BEGIN
					SELECT @Onduty_EmployeeID=Employee_Id,@Onduty_EntryDate=convert(varchar(11),GETDATE()),@Onduty_FROMDate=FROMDate,@Onduty_FROMTime=FROMTime,
					@Onduty_ToDate=Todate,@Onduty_ToTime=Totime,@Onduty_Reason=Reason,@Onduty_Status=Approve_status FROM #TempOndutyImportData WHERE ImportID=@start								
					set @Onduty_Status =case when @Onduty_Status IS null or @Onduty_Status='' then 'Forwarded' else @Onduty_Status end
					BEGIN
						SET  @Reasonvalue =case when isnull(@Onduty_Reason,'')='' then 'Onduty Import' else @Onduty_Reason end
						INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FROMDate,Onduty_FROMTime,Onduty_ToDate
						,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,FROM_Session,To_Session,isImported,YearSettings_Id) 
						VALUES (@Onduty_EmployeeID,@Onduty_EntryDate,1,0,@Onduty_FROMDate,@Onduty_FROMTime,@Onduty_ToDate,
						@Onduty_ToTime,@Reasonvalue,@Onduty_Status,0,GETDATE(),@local_EmpAutoID,null,null,1,@YEARSETTINGID)
						SELECT @RETURN_VALUE=MAX(Onduty_ID) FROM TA_Tbl_OndutyEntry
						WHERE Onduty_FromDate=@Onduty_FROMDate and Onduty_FromTime=@Onduty_FROMTime
						and Onduty_ToDate=@Onduty_ToDate and Onduty_ToTime=@Onduty_ToTime
						and Onduty_EmployeeID=@Onduty_EmployeeID and Isdeleted=0 and Onduty_Status!='Rejected'
						SET  @Diff=DATEDIFF(D,@Onduty_FROMDate,@Onduty_ToDate)
						IF(@Diff>1)
						BEGIN
							While @Onduty_FROMDate>=@Onduty_ToDate
							BEGIN
								IF (@RETURN_VALUE IS NOT NULL AND @RETURN_VALUE<>'')
								BEGIN
									EXEC [DBO].[PROC_TA_INSERTONDUTYENTRY] @Onduty_EmployeeID,@Onduty_EntryDate,@Onduty_FROMDate,
									@Onduty_FROMTime,@INPUNCHTYPE,@Onduty_FROMDate,@Onduty_ToTime,@OUTPUNCHTYPE,@INREADER_ID,@OUTREADER_ID,
									@Reasonvalue,0,@Onduty_Status,@local_EmpAutoID,@YEARSETTINGID,1,0,@Onduty_FROMDate,@RETURN_VALUE;
								END
								SET  @Onduty_FROMDate=DATEADD(d,1,@Onduty_FROMDate)
							END
						END
						ELSE
						BEGIN
							IF (@RETURN_VALUE IS NOT NULL AND @RETURN_VALUE<>'')
							BEGIN
								EXEC [DBO].[PROC_TA_INSERTONDUTYENTRY] @Onduty_EmployeeID,@Onduty_EntryDate,@Onduty_FROMDate,
								@Onduty_FROMTime,@INPUNCHTYPE,@Onduty_ToDate,@Onduty_ToTime,@OUTPUNCHTYPE,@INREADER_ID,@OUTREADER_ID,
								@Reasonvalue,0,@Onduty_Status,@local_EmpAutoID,@YEARSETTINGID,1,0,@Onduty_FROMDate,@RETURN_VALUE;
							END
						END
					END
					SET  @start=@start+1
				END				
			END
			ELSE 
			BEGIN
				SELECT	recordNumber=RecordID+1,
						EmployeeId=Employee_Id, 
						Errormessage=Error_Msg
				FROM @ErrorMsg where flag=0
			END
		COMMIT TRAN ImportOndutyData
			SELECT 'Msg:OndutyDataImportSuccessfully' [Message]
	END TRY		
	BEGIN CATCH
		SET  @ErrMsg = (CASE WHEN ERROR_MESSAGE() LIKE 'Conversion failed%' THEN 'Kindly Check date Format' ELSE ERROR_MESSAGE() END )
		SET  @ErrIds = @@ERROR
		ROLLBACK TRAN ImportOndutyData
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InserAuditTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_InserAuditTable  
Description : insert into TA_Tbl_AuditTable with required information
Tables Included : TA_Tbl_AuditTable
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InserAuditTable] 
	-- Add the parameters for the stored procedure here
	@tableName nvarchar(100),
	@tableDescription nvarchar(100),
    @tableStatus bit
AS
DECLARE @tableId as decimal
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @recCount as int
set @recCount = (select count(*) from TA_Tbl_AuditTable where TableName=@tableName)
if(@recCount>0)
	Begin
		update TA_Tbl_AuditTable set status=@tableStatus where TableName=@tableName
		SELECT tableId = (select TableId from ta_Tbl_auditTable where TableName=@tableName)
	End
Else
	Begin
		INSERT INTO TA_Tbl_AuditTable(TableName, TableDescription, Status) VALUES(@tableName, @tableDescription, @tableStatus)
		SELECT tableId = (select @@identity)
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_AddlWeekOffDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [dbo].[Proc_TA_Insert_AddlWeekOffDetails]  
(        
 @TYPE CHAR(1)='',
 @AddlWeekoffID INT,
 @LevelId INT,         
 @AddlWeekoffDay NVARCHAR(50)='',     
 @AddlWeekOffWeek NVARCHAR(50)='',
 @auditEmpId int     
)        
AS 
declare @sql as nvarchar(3000)      
DECLARE @Isdeleted INT
SET @Isdeleted= 0
SET NOCOUNT ON        
BEGIN
IF (@TYPE='I')
	 BEGIN        
		 set @sql ='INSERT INTO TA_Tbl_Additional_WeeklyOff    (LevelId_Id,Addl_WeekOff_Day,Addl_WeekOff_Week,IsDeleted,Emp_Id )        
	               VALUES       (''' + cast(@LevelId as nvarchar(25)) + ''',N''' + @AddlWeekoffDay + ''',N''' + @AddlWeekOffWeek + ''' ,''' + cast(@Isdeleted as nvarchar(10)) + ''',''' + cast(@auditEmpId as nvarchar(10)) + ''')'
		exec(@sql) 
	 END
ELSE IF (@TYPE='U')
	BEGIN
		  set @sql ='UPDATE TA_Tbl_Additional_WeeklyOff   SET  LevelId_Id=''' + cast(@LevelId as nvarchar(25))+ ''',Addl_WeekOff_Day=N''' + @AddlWeekoffDay + ''',Addl_WeekOff_Week=N''' + @AddlWeekOffWeek + ''',Emp_Id=''' + cast(@auditEmpId as nvarchar(25))+ '''
	               WHERE Addl_WeeklyOff_Id=''' + cast(@AddlWeekoffID as nvarchar(25)) + ''' '
			exec(@sql)
	END    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_EntranceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec Proc_TA_Insert_EntranceDetails 'U',6,'Testing Entrance Insert','Testing Entrance Insert',1,4,4,'9','9',1
CREATE PROCEDURE [dbo].[Proc_TA_Insert_EntranceDetails]
(        
	@TYPE CHAR(1)='',
	@EntranceID INT=0,    
	@EntranceName NVARCHAR(50)='',     
	@EntranceDesc NVARCHAR(255)='',
	@OrgLevelId INT=0,    
	@NoOfInTerminals INT=0,
	@NoOfOutTerminals INT=0,
	@InTerminals NVARCHAR(max),
	@OutTerminals NVARCHAR(max),
	@EmpAutoID int=0        
)        
AS   
BEGIN
	SET NOCOUNT ON
	DECLARE @sql nvarchar(2000)	
	IF (@TYPE='I')
	BEGIN        
		-- Query to insert the Details into Entrance Table                           
		SET @sql = 'INSERT INTO TA_Tbl_Entrance(Entrance_Name, Entrance_Description, OrgLevel_Id,NoOfInTerminals,NoOfOutTerminals,IsDeleted,Emp_ID)        
	              VALUES(N''' + @EntranceName + ''',N''' + @EntranceDesc + ''',' + cast(@OrgLevelId as nvarchar(20)) + ',' + cast(@NoOfInTerminals as nvarchar(20)) + ',' + cast(@NoOfOutTerminals as nvarchar(20)) + ',0,'+cast(@EmpAutoID  as nvarchar(20))+')'   
		EXEC(@sql)	
		SELECT @EntranceID = Entrance_Id FROM TA_Tbl_Entrance WHERE Entrance_Name=@EntranceName 
		AND Entrance_Description=@EntranceDesc AND OrgLevel_Id=@OrgLevelId AND NoOfInTerminals=@NoOfInTerminals AND NoOfOutTerminals=@NoOfOutTerminals
	END
	ELSE IF (@TYPE='U')
	BEGIN
 		-- Query to update the Details in the Entrance Table for a particular Entrance Id                        
		SET @sql = 'UPDATE TA_Tbl_Entrance SET Entrance_Name=N''' + @EntranceName + ''', Entrance_Description=N''' + @EntranceDesc + ''' ,OrgLevel_Id=' + cast(@OrgLevelId as nvarchar(20)) + ', NoOfInTerminals=' + cast(@NoOfInTerminals as nvarchar(20)) + ', NoOfOutTerminals=' + cast(@NoOfOutTerminals as nvarchar(20)) + ',Time_Stamp=''' + cast(getdate() as nvarchar(20)) + ''',Emp_ID='+cast(@EmpAutoID  as nvarchar(20))+'
	              WHERE Entrance_Id=' + cast(@EntranceID as nvarchar(20)) + ''
		EXEC(@sql)		
		-- Delete the IN/OUT Details from the Entrance INOUT Details Table  for a particular Entrance Id                    
		DELETE FROM TA_Tbl_Entrance_INOUTDetails WHERE Entrance_Id = @EntranceID
	END
	-- Split the Comma seperated IN Terminals and insert the Terminal Id and Type into the Entrance INOUT Details Table		
	INSERT INTO TA_Tbl_Entrance_INOUTDetails(Entrance_Id,Reader_Id,Type) 
	select @EntranceID,[Value],'In' from [dbo].[Split](@InTerminals,',')
	INSERT INTO TA_Tbl_Entrance_INOUTDetails(Entrance_Id,Reader_Id,Type) 
	select @EntranceID,[Value],'Out' from [dbo].[Split](@OutTerminals,',')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveMasterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveMasterDetails]      
(        
 @CompanyId INT,         
 @RegionId INT,        
 @BranchId INT,        
 @DepartmentId INT,        
 @SectionId INT,        
 @TitleId INT,      
 @LeaveType_Id INT,      
 @LOP Varchar(20)    
)        
AS        
SET NOCOUNT ON        
 BEGIN        
  INSERT INTO TA_Tbl_LeaveMaster      
  (        
    Company_Id,Region_Id,Branch_Id,Department_Id,Section_Id,Title_Id,LeaveType_Id,LOP       
  )        
         VALUES         
  (         
   @CompanyId,@RegionId,@BranchId,@DepartmentId,@SectionId,@TitleId,@LeaveType_Id,@LOP            
 )      
 END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveType]
(
	@LeaveId INT,
	@LeaveType VARCHAR(25) ,
	@LeaveDescription NVARCHAR(25)	
)
AS
SET NOCOUNT ON
DECLARE @CountLeaveID INT
SELECT @CountLeaveID=COUNT(@LeaveId) FROM tbl_TA_LeaveType WHERE LeaveId=@LeaveId
IF (@CountLeaveID=0) 
	BEGIN
		INSERT INTO tbl_TA_LeaveType
		(
		   LeaveId,LeaveType,LeaveDescription,IsDeleted
		)
       		VALUES 
		(	
		   @LeaveId, @LeaveType,@LeaveDescription,0
		)
	END
ELSE
	BEGIN
		UPDATE  tbl_TA_LeaveType
		SET
			  LeaveId=@LeaveId,   	
			 LeaveDescription=@LeaveDescription
  		WHERE LeaveId=@LeaveId
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[Proc_TA_Insert_LeaveTypeDetails] 'ctc','common',1,0,1,1,0,0
--select*from TA_Tbl_LeaveType 
CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveTypeDetails]    
(    
	@LeaveType NVARCHAR(50),
	@LeaveDescription NVARCHAR(250),	
	@Emp_Id NVARCHAR(50),  
	@CountFactor int,
	@EmployeeCategory int,
	@EmployeeType int,
	@Gender varchar(10),
	@Religion int,
	@IsProrataRequired int,
	@IsDocProofRequired int,
	@TypeId INT
)    
AS    
BEGIN 
	SET NOCOUNT ON       
	IF(@TypeId=0)
	BEGIN
		insert into TA_Tbl_LeaveType(LeaveType,LeaveDescription,IsDeleted,Emp_ID,CountFactor,EmployeeCategory,EmployeeType,Gender,Religion,Time_Stamp,IsProrataRequired,IsDocProofRequired)
		VAlues(@LeaveType,@LeaveDescription,0,@Emp_Id,@CountFactor,@EmployeeCategory,@EmployeeType,@Gender,@Religion,GETDATE(),@IsProrataRequired,@IsDocProofRequired)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_LeaveType SET LeaveType =@LeaveType,LeaveDescription= @LeaveDescription, 
		Emp_ID=@Emp_Id,CountFactor=@CountFactor,EmployeeCategory=@EmployeeCategory,EmployeeType=@EmployeeType,Gender=@Gender,Religion=@Religion,
		IsDocProofRequired=@IsDocProofRequired,IsProrataRequired=@IsProrataRequired
		WHERE LeaveType_Id=@TypeId
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_MonthClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_MonthClosure]
(
	@Type CHAR(1)='',
    @MonthClosureID INT,
    @OrgLevel_Id INT,
	@Month NVARCHAR(15)='',
	@Year INT=0,
	@FromDate NVARCHAR(15)='',
	@ToDate NVARCHAR(15)='',
	@ClosedDate NVARCHAR(15)='',
    @UserId int,
    @EntryDate NVARCHAR(15),
	@YearSettingId INT	
)
AS
DECLARE @Isdeleted INT
SET @Isdeleted=0
    declare @offsetHours INT
	declare @offsetMinutes INT
	DECLARE @utcTime DATETIME
BEGIN


/* ** Hariharan J ******** 16-02-2024***** UTC Convertion Selected Contry DateTime **********************************/

	Select @offsetHours=HoursToBeAdded,@offsetMinutes=MinToBeAdded 
	from Ta_Tbl_levelDetails
	Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
	Where Ta_Tbl_levelDetails.id =@OrgLevel_Id

	SET @utcTime = DATEADD(MINUTE,Convert(int,@offsetMinutes),DateADD(Hour,Convert(int, @offsetHours), GETUTCDATE()))
/*****************************************************************************************************************/
IF (@Type='I')
	BEGIN
		INSERT INTO TA_Tbl_MonthClosure (OrgLevel_Id,MonthClosure_Month,MonthClosure_Year,MonthClosure_StartDate,MonthClosure_EndDate,MonthClosure_ClosingDate,[Emp_Id],Process,[TimeStamp],Isdeleted,YearSettings_Id)
		VALUES (@OrgLevel_Id,@Month,@Year,@FromDate,@ToDate,@ClosedDate,@UserId,'N',@utcTime,@Isdeleted, @YearSettingId)
	END
ELSE IF (@Type='U')
	BEGIN
		UPDATE TA_Tbl_MonthClosure SET Process = 'P'  WHERE MonthClosure_Id=@MonthClosureID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_PayrollProcessDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_PayrollProcessDetails]
(
   @MonthClosure_Id int,
   @EmpId Varchar(20),
   @HrsWork Varchar(20),
   @HrsOT Varchar(20),
   @NormOT Varchar(20),
   @OffOT Varchar(20),
   @HolOT Varchar(20),
   @EarlyOut Varchar(20),
   @LateIn Varchar(20),
   @WorkHrs Varchar(20),
   @HrsLess Varchar(20),
   @HrsExtra Varchar(20),
   @LeaveDays numeric(18,1),
   @AbsentDays numeric(18,1),
   @PresentDays numeric(18,1),
   @Holidays numeric(18,1),
   @LOPDays numeric(18,1),
   @UserId numeric(18,1),
   @ProcessDateTime Varchar(20)
)
AS
BEGIN
           DELETE FROM TA_Tbl_PayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
           INSERT INTO TA_Tbl_PayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut,LateIn,WorkHrs,HrsLess,HrsExtra,LeaveDays,AbsentDays,PresentDays,Holidays,LOPDays,[Emp_Id],[TimeStamp]) 
           VALUES (@MonthClosure_Id,@EmpId,@HrsWork,@HrsOT,@NormOT,@OffOT,@HolOT,@EarlyOut,@LateIn,@WorkHrs,@HrsLess,@HrsExtra,@LeaveDays,@AbsentDays,@PresentDays,@Holidays,@LOPDays,@UserId,
           @ProcessDateTime)
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]
AS
BEGIN
	SET NOCOUNT ON
	--CREATE TABLE #tempProcessDataService
	--(
	--	Employee_Code_Id VARCHAR(20),
	--	ProcessDate DATETIME,
	--	InsertedFlag INT
	--)	
	--INSERT INTO #tempProcessDataService
	--SELECT DISTINCT T1.Employee_Code_Id,T1.ProcessDate,0 
	--FROM 
	--(
	--	SELECT E.SwipeCardNo AS Employee_Code_Id,CONVERT(DATETIME,CONVERT(VARCHAR(11),T.ProcessDate)) as ProcessDate,E.Employee_Id 
	--	FROM TA_Tbl_Employee E INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	--	INNER JOIN Ta_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id  
	--	INNER JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId 
	--	WHERE E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	--	IS NOT NULL AND E.Employee_Code_Id <> '18000000'
	--)AS T1  
	
	--UPDATE #tempProcessDataService set InsertedFlag=1 FROM TA_Tbl_ProcessedData P
	--INNER JOIN #tempProcessDataService T1  ON T1.Employee_Code_Id  = P.Employee_Code_Id and T1.ProcessDate = P.[Date]  
	
	--INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag)  
	--SELECT Employee_Code_Id,ProcessDate as [Date],'0' AS ProcessFlag from #tempProcessDataService 
	--WHERE InsertedFlag=0 ORDER BY Employee_Code_Id, ProcessDate
	
	--DROP TABLE #tempProcessDataService
	--Inserting current date first for all employees
	INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag,Level_Id) 
	select E.SwipeCardNo,T.ProcessDate as [Date],'0' ,dbo.Fun_TA_GetLevelForEmployeeTransfer(pd.Date,E.Employee_Id)
	FROM TA_Tbl_Employee E

	INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	Left outer join TA_Tbl_ProcessedData pd on(pd.Employee_Code_Id=E.SwipeCardNo and pd.Date=T.ProcessDate)
	where T.ProcessDate=dbo.DateOnly(getdate()) and pd.Date is null 
	and E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	IS NOT NULL AND E.Employee_Code_Id <> '18000000'	
	--order by E.SwipeCardNo,T.ProcessDate

	
	--balance dates
	INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag,Level_Id)  
	select E.SwipeCardNo,T.ProcessDate as [Date],'0',dbo.Fun_TA_GetLevelForEmployeeTransfer(pd.Date,E.Employee_Id) 
	FROM TA_Tbl_Employee E 
	INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	Left outer join TA_Tbl_ProcessedData pd on(pd.Employee_Code_Id=E.SwipeCardNo and pd.Date=T.ProcessDate)
	where pd.Date is null --order by E.SwipeCardNo,T.ProcessDate
	and E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	IS NOT NULL AND E.Employee_Code_Id <> '18000000'	
	--order by E.SwipeCardNo,T.ProcessDate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_ReligionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_ReligionDetails]   
(    
 @Name nvarchar(50),    
 @Description NVARCHAR(250) 
)    
AS    
SET NOCOUNT ON    
 BEGIN    
  declare @sql nvarchar(2000)  
  set @sql='INSERT INTO TA_Tbl_Religion(Name,Description,IsDeleted) VALUES (N'''+ @Name + ''',N'''+ @Description + ''',0)'  
  exec(@sql)  
  select * from TA_Tbl_Religion
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Title_MappingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_Title_MappingDetails]
(
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT,
	@DepartmentId INT,
	@SectionId INT,
	@TitleId INT
)
AS
SET NOCOUNT ON
	BEGIN
		INSERT INTO TA_Tbl_TitleMapping
		(
		  Company_Id,Region_Id,Branch_Id,Department_Id,Section_Id,TitleId
		)
       		VALUES 
		(	
			@CompanyId,@RegionId, @BranchId,@DepartmentId,@SectionId,@TitleId		   
		)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TitleFirstDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	06-Jan-2014
Descriptions	:	Adding @LevelId parameter for getting organization based designation
*/
CREATE PROCEDURE [dbo].[Proc_TA_Insert_TitleFirstDetails]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(250),
	@LevelID INT,	
	@PolicyID INT,
	@GradeID INT,
	@EmpID INT
)
AS
BEGIN
	declare @sql as nvarchar(3000)
	SET NOCOUNT ON
	--Commenting below line and adding above line for Adding @LevelId parameter for getting organization based designation
	set @sql = 'INSERT INTO TA_Tbl_Title(TitleName,TitleDescription,LevelID,LeavePolicyID,GradeID,Emp_Id,IsDeleted) VALUES(N'''+@TitleName+''',N'''+@TitleDescription+''','+cast(@LevelID as nvarchar(25))+','+cast(@PolicyID as nvarchar(25))+','+cast(@GradeID as nvarchar(25))+','+cast(@EmpID as nvarchar(25))+',0)'
	--set @sql = 'INSERT INTO TA_Tbl_Title(TitleName,TitleDescription,LeavePolicyID,GradeID,Emp_Id,IsDeleted) VALUES(N'''+@TitleName+''',N'''+@TitleDescription+''','+cast(@PolicyID as nvarchar(25))+','+cast(@GradeID as nvarchar(25))+','+cast(@EmpID as nvarchar(25))+',0)'
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation]
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
DECLARE @CountVehicleNo INT
SELECT @CountVehicleNo = COUNT(@VehicleNo) FROM TA_Tbl_Transportation WHERE VehicleNo=@VehicleNo
IF (@CountVehicleNo=0) 
	BEGIN
		INSERT INTO TA_Tbl_Transportation
		(
		   VehicleNo,RouteName,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleNo, @RouteName,@CompanyId ,@RegionId, @BranchId
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_Transportation
		SET
			 VehicleNo = @VehicleNo,   	
			 RouteName = @RouteName,
			 Company_Id = @CompanyId,
			 Region_id = @RegionId,
			 Branch_Id = @BranchId	 
  		WHERE VehicleNo=@VehicleNo
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_MappingDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation_MappingDetails]
(
	@VehicleId INT,
	@RouteId INT,
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
	BEGIN
		INSERT INTO TA_Tbl_Transportation_Mapping
		(
		   VehicleId,RouteId,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleId, @RouteId,@CompanyId,@RegionId, @BranchId		   
		)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_RouteDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation_RouteDetails]  
(  
	@LevelId INT,
	@VehicleID INT,
	@RouteName NVARCHAR(50),  
	@RouteDescription NVARCHAR(250),
	@EmpID INT
)  
AS  
declare @sql as nvarchar(3000)
DECLARE @Isdeleted BIT
SET @Isdeleted=0
SET NOCOUNT ON  
 BEGIN  
  --INSERT INTO TA_Tbl_RouteMaster(Level_Id,VehicleID,Route_Name,Route_Description,Emp_ID,Isdeleted)  VALUES(@LevelId,@VehicleID,@RouteName,@RouteDescription,@EmpID,@Isdeleted)  
  set @sql = 'INSERT INTO TA_Tbl_RouteMaster(Level_Id,VehicleID,Route_Name,Route_Description,Emp_ID,Isdeleted)  VALUES('+cast(@LevelId as nvarchar(25))+','+cast(@VehicleID as nvarchar(25))+',N'''+@RouteName+''',N'''+@RouteDescription+''','+cast(@EmpID as nvarchar(25))+','+cast(@Isdeleted as nvarchar(25))+')'
  exec(@sql)
 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_TransportationDetails]
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
--DECLARE @CountVehicleID INT
--SELECT @CountVehicleID=COUNT(@VehicleNo) FROM TA_Tbl_Transportation WHERE VehicleNo=@VehicleNo
--IF (@CountVehicleID=0) 
	BEGIN
		INSERT INTO TA_Tbl_Transportation
		(
		   VehicleNo,RouteName,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleNo, @RouteName,@CompanyId,@RegionId, @BranchId		   
		)
	END
--ELSE
	--BEGIN
		--UPDATE TA_Tbl_Transportation
		--SET
			--VehicleNo = @VehicleNo, 
			--RouteName = @RouteName,
			--Company_Id =@CompanyId,
			--Region_Id = @RegionId,
			--Branch_Id = @BranchId
--  		WHERE VehicleNo=@VehicleNo
	--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationVehicleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Insert_TransportationVehicleDetails]
(
	@VehicleNo NVARCHAR(50),
	@VehicleDescription NVARCHAR(250),
	@EmpID INT 
)
AS
declare @sql as nvarchar(3000)
DECLARE @Isdeleted BIT
SET @Isdeleted=0
SET NOCOUNT ON
	BEGIN
		--INSERT INTO TA_Tbl_Transportation_Vehicle(VehicleNo,VehicleDescription,Emp_ID,IsDeleted) VALUES(@VehicleNo,@VehicleDescription,@EmpID,@Isdeleted)
        set @sql = 'INSERT INTO TA_Tbl_Transportation_Vehicle(VehicleNo,VehicleDescription,Emp_ID,IsDeleted) VALUES(N'''+@VehicleNo+''',N'''+@VehicleDescription+''','+cast(@EmpID as nvarchar(25))+','+cast(@Isdeleted as nvarchar(25))+')'
        exec(@sql)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Update_PunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--[Proc_TA_Insert_Update_PunchTypes]'I',0,12,'Out Duty',34,1
--Select * from ta_tbl_punchtypes
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Update_PunchTypes] 
(
	@type CHAR,
	@PunchType_Id INT,
    @Terminal_Id INT,
	@PunchType  NVARCHAR(25),
	@Value NVARCHAR(25),
	@Emp_Id INT
)
AS
BEGIN
	DECLARE @sql as nvarchar(3000)
	DECLARE @Isdeleted BIT
	DECLARE @count INT
	DECLARE @result INT
	DECLARE @InOrOutEntry nvarchar(1)
	SET @Isdeleted=0
	SET @result=0
	IF(@PunchType = 'In' OR @PunchType = 'Shift In' OR @PunchType = 'Break In' OR @PunchType = 'Lunch In' OR @PunchType = 'Out Duty' OR @PunchType = 'Official In')
		BEGIN
			 SET @InOrOutEntry =  'I'
		END
	ELSE IF(@PunchType = 'Out' OR @PunchType = 'Shift Out' OR @PunchType = 'Break Out' OR @PunchType = 'Lunch Out' OR @PunchType = 'In Duty' OR @PunchType = 'Official Out')
		BEGIN
			 SET @InOrOutEntry =  'O'
		END
	--Insert
	IF (@type='I')
		BEGIN
			SET @count=(SELECT count(*) FROM TA_Tbl_PunchTypes WHERE ((Terminal_Id = @Terminal_Id AND PunchType = @PunchType)  OR (Terminal_Id = @Terminal_Id AND [Value] = @Value))  AND @Isdeleted=0)
			IF (@count=0)
				BEGIN
					INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(cast(@Terminal_Id as nvarchar(25)),@PunchType,@Value,cast(@Isdeleted as nvarchar(25)),cast(@Emp_Id as nvarchar(25)),cast(getdate() as nvarchar(25)),'A')
					Declare @TerminalAutoID int
					if(@InOrOutEntry='I')
						begin
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID='787' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),'A')
										end
								end            
						end
					if(@InOrOutEntry='O')
						begin
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID='788' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),'A')
										end
								end
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID='787' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),'A')
										end
								end        
						end
				END
			ELSE
				BEGIN
					SET @result=1
				END
		END
	-- Update
	IF (@type='U')
		BEGIN
			SELECT @count=count(*) FROM TA_Tbl_PunchTypes where ((Terminal_Id = @Terminal_Id AND PunchType = @PunchType)  OR (Terminal_Id = @Terminal_Id AND [Value] = @Value))  AND PunchType_Id <> @PunchType_Id AND @Isdeleted=0
			IF (@count=0)
				BEGIN
					UPDATE TA_Tbl_PunchTypes SET Terminal_Id = cast(@Terminal_Id as nvarchar(25)),
					PunchType = @PunchType,[Value] = @Value,
					Emp_Id = cast(@Emp_Id as nvarchar(25)),
					Time_Stamp = cast(getdate() as nvarchar(25)) 
					WHERE PunchType_Id = cast(@PunchType_Id as nvarchar(25))					
				END
			ELSE
				BEGIN
					SET @result=1
				END
		END
	SELECT @result
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAccessDeniedSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name : Proc_TA_InsertAccessDeniedSettings
-- Author : Kumuthini.L
-- Created On : 12-Mar-2008
-- Modified On : 13-Mar-2008
-- Tables Used : TA_Tbl_AccessDeniedSettings
-- Purpose : Used to insert the Access Denied Setting Entries
CREATE PROCEDURE [dbo].[Proc_TA_InsertAccessDeniedSettings]
(
   @Terminal_ReaderId NVARCHAR(10),
   @Employee_Code_Id NVARCHAR(10),
   @AccessDeniedKey INT
)
AS
DECLARE @Count INT
SET @Count = 0
BEGIN
   SET @Count = (SELECT Count(*) FROM TA_Tbl_AccessDeniedSettings WHERE Terminal_ReaderID = @Terminal_ReaderId AND Employee_Code_Id = @Employee_Code_Id)
   IF(@Count = 0)
      BEGIN
        INSERT INTO TA_Tbl_AccessDeniedSettings(Terminal_ReaderID,Employee_Code_Id,AccessDeniedKey) VALUES (@Terminal_ReaderId,@Employee_Code_Id,@AccessDeniedKey)
      END
   ELSE 
      BEGIN
        UPDATE TA_Tbl_AccessDeniedSettings SET AccessDeniedKey = @AccessDeniedKey WHERE Terminal_ReaderID = @Terminal_ReaderId AND Employee_Code_Id = @Employee_Code_Id
      END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified BY : Manikandan.R
-- Modified Date: 15-Mar-2012
--	Modified By		:	Manjula.P
--	Modified On		:	05-Oct-2013
--	Descriptions	:	Checking additioanl weekly off already exit with levels and isdeleted
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels] 
-- Add the parameters for the stored procedure here
@AdditionalWeekOffDay nvarchar(50),
@AdditionalWeekOffWeek nvarchar(50),
@EmpId int,
@XMLdata xml,
@Addl_WeeklyOff_Id int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	declare @AddWeekId int
	--Added by MAnjula.P on 05-Oct-2013
	create table #TempXML
	(
	Addl_WeeklyOff_Id int,
	LevelId int
	)
	DECLARE @IndexTemp int
	set @IndexTemp = 0 
	set @AddWeekId=@Addl_WeeklyOff_Id
	EXEC sp_xml_preparedocument @IndexTemp OUTPUT, @XMLdata
	insert into #TempXML
	select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@IndexTemp, '/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels')
	with (Addl_WeeklyOff_Id int 'Addl_WeeklyOff_Id') as xm
	Exec sp_xml_removedocument @IndexTemp
	--*******************************************
	--select * from #TempXML
	if(@Addl_WeeklyOff_Id <>0)
		begin
		--Changing select with inner joins by Manjula.P on 05-Oct-2013
			if not exists(select * from TA_Tbl_Additional_WeeklyOff AW 
			inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
			inner join #TempXML on #TempXML.LevelId=AWL.LevelId 
			where Addl_WeekOff_Day=@AdditionalWeekOffDay and Addl_WeekOff_Week=@AdditionalWeekOffWeek and AW.Addl_WeeklyOff_Id<>@Addl_WeeklyOff_Id
			and IsDeleted=0 )
				begin
					update ta_tbl_Additional_weeklyoff set Addl_WeekOff_Day=@AdditionalWeekOffDay 
					, Addl_WeekOff_Week=@AdditionalWeekOffWeek where Addl_WeeklyOff_Id=@Addl_WeeklyOff_Id
					set @AddWeekId=@Addl_WeeklyOff_Id
					delete from TA_Tbl_Additional_WeeklyOff_Levels where Addl_WeeklyOff_Id=@Addl_WeeklyOff_Id
					DECLARE @Index1 int
					set @Index1 = 0 
					EXEC sp_xml_preparedocument @Index1 OUTPUT, @XMLdata
					insert into TA_Tbl_Additional_WeeklyOff_Levels
					select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@Index1, '/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels')
					with (Addl_WeeklyOff_Id int 'Addl_WeeklyOff_Id') as xm
					Exec sp_xml_removedocument @Index1
					select '1'
				end
			else
				begin
					select '0'
				end
		end
	else
		begin
		--Changing select with inner joins by Manjula.P on 05-Oct-2013
			if not exists(select * from TA_Tbl_Additional_WeeklyOff AW 
			inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
			inner join #TempXML on #TempXML.LevelId=AWL.LevelId 
			where Addl_WeekOff_Day=@AdditionalWeekOffDay and Addl_WeekOff_Week=@AdditionalWeekOffWeek and IsDeleted=0)
				begin
					Insert into ta_tbl_Additional_weeklyoff(Addl_WeekOff_Day,Addl_WeekOff_Week,Emp_Id,IsDeleted) 
					values(@AdditionalWeekOffDay,@AdditionalWeekOffWeek,@EmpId,0)
					set @AddWeekId= (select @@Identity)
					DECLARE @Index int
					set @Index = 0 
					EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
					insert into TA_Tbl_Additional_WeeklyOff_Levels
					select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@Index, '/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels')
					with (Addl_WeeklyOff_Id int 'Addl_WeeklyOff_Id') as xm
					Exec sp_xml_removedocument @Index
					select '1'
				end
			else
				begin
					select '0'
				end
		end
		drop table #TempXML
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationChild]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Abul:
this proc will insert the shift pattern transaction details in the TA_Tbl_ShiftAllocationDetails table
*/
Create Proc [dbo].[Proc_TA_InsertAllocationChild]
@ShiftAllocation_Id int,
@Employee_Id int,
@Starting_Day int
As
Insert Into TA_Tbl_ShiftAllocationDetails(ShiftAllocation_Id, Employee_Id, Starting_Day)
values(@ShiftAllocation_Id, @Employee_Id, @Starting_Day)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Abul:
this proc will insert the shift pattern master details in the TA_Tbl_ShiftAllocation table
*/
CREATE Proc [dbo].[Proc_TA_InsertAllocationMaster]
@ShiftPattern_Id int,
@From_Date datetime,
@To_Date datetime
As
Insert Into TA_Tbl_ShiftAllocation(ShiftPattern_Id, From_Date, To_Date) 
values(@ShiftPattern_Id, @From_Date, @To_Date);
Select @@IDENTITY as 'Identity'
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-Feb-2020 03:50 PM>
-- Description:	<update log details table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]
	@TblName varchar(50),
	@LastLogID bigint	
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT DeviceLog_TableName from Ta_Tbl_DeviceLogTableDetails where DeviceLog_TableName=@TblName)
	BEGIN
		UPDATE Ta_Tbl_DeviceLogTableDetails set LastLogID=@LastLogID,LogFetch_LastTime=getdate() where DeviceLog_TableName=@TblName
		and LastLogID<@LastLogID
	END
	ELSE
	BEGIN
		INSERT INTO Ta_Tbl_DeviceLogTableDetails values(@TblName,@LastLogID,GETDATE())
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertandUpdateGeofencting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertandUpdateGeofencting]
	-- Add the parameters for the stored procedure here
	@tag char(3),
	@fencingName varchar(20)=null,
	@company int =null,
	@landmarkId varchar(20)=null,
	@EmpId int =null,
	@FencingId int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	if (@tag='I')
	begin
		
		Insert Into TA_tbl_Fencing values(@fencingName,@landmarkId,@EmpId,GETDATE(),'',@company)
		
		select '0'
	End
	if(@tag='U')
	begin 
		update TA_tbl_Fencing set Fencing_Name=@fencingName,LandmarkId=@landmarkId,Createdby=@EmpId,ModifyDate=GETDATE(),CompanyId=@company where FencingId=@FencingId
	End
	if(@tag='SN')
	begin
		Select * From TA_tbl_Fencing where Fencing_Name=@fencingName
	End
END

-- 

--Select * From TA_Tbl_ManualTimeEntry

--Select * From Ta_tbl_LandMarks

--Select * From TA_tbl_Fencing

--Select * From TA_tbl_GeoFencingAllocation
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-April-2019 05:48 PM>
-- Description:	<Insert the employee details for email scheduler>
/*
Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler 7,
'<NewDataSet>
  <Table>
    <Employee_Id>2</Employee_Id>
    <Employee_Code_Id>659</Employee_Code_Id>
    <Employee_FirstName>اختبارات S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>34</RowNumber>
    <TitleName>PL (Project Leader)</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>3</Employee_Id>
    <Employee_Code_Id>956</Employee_Code_Id>
    <Employee_FirstName>Karthikeyan R</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>6</RowNumber>
    <TitleName>TL (Team Leader)</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>4</Employee_Id>
    <Employee_Code_Id>787</Employee_Code_Id>
    <Employee_FirstName>Manikandan RR</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>9</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>5</Employee_Id>
    <Employee_Code_Id>758</Employee_Code_Id>
    <Employee_FirstName>Sathishkumar S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>15</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>916</Employee_Code_Id>
    <Employee_FirstName>Gopinath K</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>5</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>7</Employee_Id>
    <Employee_Code_Id>1010</Employee_Code_Id>
    <Employee_FirstName>Sankar </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>14</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>8</Employee_Id>
    <Employee_Code_Id>976</Employee_Code_Id>
    <Employee_FirstName>Anbu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>1</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>9</Employee_Id>
    <Employee_Code_Id>8012</Employee_Code_Id>
    <Employee_FirstName>Manikandan V</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>10</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>10</Employee_Id>
    <Employee_Code_Id>8013</Employee_Code_Id>
    <Employee_FirstName>Manoj M</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>12</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>11</Employee_Id>
    <Employee_Code_Id>2500</Employee_Code_Id>
    <Employee_FirstName>mahi S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>8</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>12</Employee_Id>
    <Employee_Code_Id>1061</Employee_Code_Id>
    <Employee_FirstName>ANTANIJABARAJ </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>2</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>13</Employee_Id>
    <Employee_Code_Id>100101</Employee_Code_Id>
    <Employee_FirstName>ANTANIJABARAJ </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>3</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>14</Employee_Id>
    <Employee_Code_Id>100102</Employee_Code_Id>
    <Employee_FirstName>Antanijabaraj J</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>4</RowNumber>
    <TitleName>Jr Developer_Angler</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>17</Employee_Id>
    <Employee_Code_Id>100</Employee_Code_Id>
    <Employee_FirstName>TCS Jeffrin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>20</RowNumber>
    <TitleName>TCS Sr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>18</Employee_Id>
    <Employee_Code_Id>101</Employee_Code_Id>
    <Employee_FirstName>TCS Edwin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>18</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>19</Employee_Id>
    <Employee_Code_Id>102</Employee_Code_Id>
    <Employee_FirstName>TCS David </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>17</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>20</Employee_Id>
    <Employee_Code_Id>103</Employee_Code_Id>
    <Employee_FirstName>TCS Babu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>16</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>21</Employee_Id>
    <Employee_Code_Id>104</Employee_Code_Id>
    <Employee_FirstName>TCS Raja </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>24</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>22</Employee_Id>
    <Employee_Code_Id>105</Employee_Code_Id>
    <Employee_FirstName>TCS Kevin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>21</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>23</Employee_Id>
    <Employee_Code_Id>106</Employee_Code_Id>
    <Employee_FirstName>TCS Esther </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>19</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>24</Employee_Id>
    <Employee_Code_Id>107</Employee_Code_Id>
    <Employee_FirstName>TCS Suresh </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>26</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>25</Employee_Id>
    <Employee_Code_Id>108</Employee_Code_Id>
    <Employee_FirstName>TCS Peter </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>22</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>26</Employee_Id>
    <Employee_Code_Id>109</Employee_Code_Id>
    <Employee_FirstName>TCS Poorni </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>23</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>27</Employee_Id>
    <Employee_Code_Id>110</Employee_Code_Id>
    <Employee_FirstName>TCS Sindu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>25</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>28</Employee_Id>
    <Employee_Code_Id>1000</Employee_Code_Id>
    <Employee_FirstName>Kavin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>7</RowNumber>
    <TitleName>Jr Developer_Angler</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>29</Employee_Id>
    <Employee_Code_Id>2000</Employee_Code_Id>
    <Employee_FirstName>UserPM </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>33</RowNumber>
    <TitleName>Project Manager</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>30</Employee_Id>
    <Employee_Code_Id>2001</Employee_Code_Id>
    <Employee_FirstName>UserPL </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>32</RowNumber>
    <TitleName>Project Lead</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>31</Employee_Id>
    <Employee_Code_Id>2002</Employee_Code_Id>
    <Employee_FirstName>UserJrA </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>29</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>32</Employee_Id>
    <Employee_Code_Id>2003</Employee_Code_Id>
    <Employee_FirstName>UserJrB </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>30</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>33</Employee_Id>
    <Employee_Code_Id>2004</Employee_Code_Id>
    <Employee_FirstName>UserJrC </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>31</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>34</Employee_Id>
    <Employee_Code_Id>1478</Employee_Code_Id>
    <Employee_FirstName>Probation Period </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>13</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>35</Employee_Id>
    <Employee_Code_Id>1479</Employee_Code_Id>
    <Employee_FirstName>TEsting maximum entry </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>28</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>36</Employee_Id>
    <Employee_Code_Id>1592</Employee_Code_Id>
    <Employee_FirstName>Manikandan </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>11</RowNumber>
    <TitleName>PL (Project Leader)</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>37</Employee_Id>
    <Employee_Code_Id>7536</Employee_Code_Id>
    <Employee_FirstName>test </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>27</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
</NewDataSet>'
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]
	@InsertedId int,
	@ShiftData XML = NULL
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX))		
	DELETE FROM [TA_Tbl_ImportShiftAllocation]
	Create table #Temp_TA_Tbl_EmailScheduled_Employees(ScheduleId bigint,Employee_id bigint,flag int)
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
	Delete from TA_Tbl_EmailScheduled_Employees where ScheduleId=@InsertedId
	INSERT INTO TA_Tbl_EmailScheduled_Employees
				SELECT @InsertedId,Employee_Id
				FROM OPENXML (@XMLParams, 'NewDataSet/Table', 2) WITH (Employee_Id VARCHAR(50), emailScheduler_flag int) Tbl
				Where emailScheduler_flag=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_WhatsAppScheduler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_WhatsAppScheduler] 
	-- Add the parameters for the stored procedure here
	@InsertedId int,
	@ShiftData XML = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX))		
	DELETE FROM [TA_Tbl_ImportShiftAllocation]
	Create table #Temp_TA_Tbl_EmailScheduled_Employees(ScheduleId bigint,Employee_id bigint,flag int)
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
	print @XMLParams

	Delete from TA_Tbl_WhatsAppScheduled_Employees where ScheduleId=@InsertedId
	INSERT INTO TA_Tbl_WhatsAppScheduled_Employees
				SELECT @InsertedId,Employee_Id
				FROM OPENXML (@XMLParams, 'NewDataSet/Table', 2) WITH (Employee_Id VARCHAR(50), WhatsAppScheduler_flag int) Tbl
				Where WhatsAppScheduler_flag=1


END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <17-Jun-2019>
-- Description:	<Insert and Update penalty Percentage of the selected company>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]
	@CompanyID int,
	@categoryID int,
	@StartTime1 varchar(5),
	@EndTime1 varchar(5),
	@StartTime2 varchar(5),
	@EndTime2 varchar(5),
	@StartTime3 varchar(5),
	@EndTime3 varchar(5),
	@Day1 decimal(18,1),
	@Day2 decimal(18,1),
	@Day3 decimal(18,1),
	@Day4 decimal(18,1),
	@Day5 decimal(18,1),
	@Day6 decimal(18,1),
	@Day7 decimal(18,1),
	@Day8 decimal(18,1),
	@Day9 decimal(18,1),
	@Day10 decimal(18,1),
	@Day11 decimal(18,1),
	@Day12 decimal(18,1)
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT CompanyId FROM ta_tbl_PenaltyPercentage WHERE CompanyId=@CompanyID and categoryID=@categoryID)
	BEGIN
		UPDATE ta_tbl_PenaltyPercentage SET StartTime1=@StartTime1, 
											EndTime1=@EndTime1, 
											StartTime2=@StartTime2, 
											EndTime2=@EndTime2, 
											StartTime3=@StartTime3, 
											EndTime3=@EndTime3, 
											Day1=@Day1, 
											Day2=@Day2, 
											Day3=@Day3, 
											Day4=@Day4, 
											Day5=@Day5, 
											Day6=@Day6, 
											Day7=@Day7, 
											Day8=@Day8, 
											Day9=@Day9, 
											Day10=@Day10, 
											Day11=@Day11, 
											Day12=@Day12
		WHERE CompanyId=@CompanyID and categoryID=@categoryID
	END
	ELSE
	BEGIN
		INSERT INTO ta_tbl_PenaltyPercentage(CompanyId, categoryID, StartTime1, EndTime1, StartTime2, EndTime2, StartTime3, EndTime3, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12)
		VALUES(@CompanyId, @categoryID, @StartTime1, @EndTime1, @StartTime2, @EndTime2, @StartTime3, @EndTime3, @Day1, @Day2, @Day3, @Day4, @Day5, @Day6, @Day7, @Day8, @Day9, @Day10, @Day11, @Day12)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdateProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-10-2016>
-- Description:	<Insert / Update data into processed data table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAndUpdateProcessedData]
	-- Add the parameters for the stored procedure here
	@Employee_Code_Id varchar(50),
	@Date varchar(20),
	@Shift_Id int,
	@Intime varchar(15),
	@Attendance varchar(20),
	@InNotation char(2),
	@LateIn varchar(6),
	@LateInMins int,
	@Type char(2),
	@ClockAddress varchar(500)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@Type='I')
	begin
		INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id, Date, Shift_Id, InTime, Attendance, ProcessFlag,InNotation,LateIn,LateInMins,InLocation) 
		VALUES(@Employee_Code_Id,convert(datetime,convert(varchar(11),@Date)),@Shift_Id,@Intime,@Attendance,0,@InNotation,@LateIn,@LateInMins,@ClockAddress)
	end
	else if(@Type='U')
	begin
		if(@Intime='' and @Attendance='' and @InNotation='' and @Shift_Id=0)
		begin
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0 
			WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
		end
		else
		begin
			UPDATE TA_Tbl_ProcessedData SET Shift_Id = @Shift_Id,
											OutNotation=@InNotation,
											OutTime = @Intime,
											Attendance = @Attendance,
											Status = NULL,
											outLocation=@ClockAddress,
											
											ProcessFlag = 0 
			WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
		end
	end	
	else if(@Type='UI')
	begin
		UPDATE TA_Tbl_ProcessedData set Shift_Id = @Shift_Id,
										InNotation=@InNotation,
										InTime = @Intime, 
										LateIn = @LateIn, 
										Attendance = @Attendance, 
										LateInMins = @LateInMins, 
										InLocation=@ClockAddress,
										
										Status = NULL, 
										ProcessFlag = 0 
		WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
	end
	else if(@Type='IO')	
	begin
		INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id, Date, Shift_Id, OutTime,Attendance,ProcessFlag,OutNotation,EarlyOut,EarlyOutMins,InLocation)
		VALUES(@Employee_Code_Id,@Date,@Shift_Id,@Intime,@Attendance,0,@InNotation,@LateIn,@LateInMins,@ClockAddress)
	end
	else if(@Type='UO')
	begin
		UPDATE TA_Tbl_ProcessedData set Shift_Id = @Shift_Id,
										OutNotation=@InNotation,
										OutTime = @Intime,
										EarlyOut = @LateIn,
										Attendance = @Attendance,
										EarlyOutMins = @LateInMins,
										OutLocation=@ClockAddress,
										
										Status = NULL, 
										ProcessFlag = 0 
		WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_InsertAttandanceCode]
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@EmpID as int
AS
BEGIN
	insert into TA_Tbl_AttandanceCode (AttandanceCode,AttandanceValue,EmpID,IsDeleted,CompanyID) 
                values (@AttandanceCode,@AttandanceValue,@EmpID,0,@CompanyID)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAuditField]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_InsertAuditField  
Description : insert into TA_Tbl_AuditField with required information
Tables Included : TA_Tbl_AuditField
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InsertAuditField] 
	-- Add the parameters for the stored procedure here
	@tableId decimal,
    @fieldName nvarchar(100),
	@fieldDescription nvarchar(100),
    @insertBitStatus bit,
    @updateBitStatus bit,
    @deleteBitStatus bit,
    @fieldStatus bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @recCount as int
	set @recCount = (select count(*) from Ta_tbl_AuditField where TableID=@tableId and FieldName=@fieldName)
	Declare @TableName varchar(max)
	Declare @DataType varchar(40)
	set @TableName=(select TableName from TA_Tbl_AuditTable where TableID=@tableId)
	select @DataType=name from sys.types where user_type_id=(
	select user_type_id from sys.columns where object_id=(select object_id from sys.tables where name=CONVERT(varchar(max),@TableName))
	and name=+convert(varchar(max),@fieldName))
	if (@recCount>0)
		Begin
			update TA_Tbl_AuditField set DataType=@DataType,InsertBit=@insertBitStatus,UpdateBit=@updateBitStatus,DeleteBit=@deleteBitStatus,Status= @fieldStatus where TableID=@tableId and FieldName=@fieldName
		End
	Else
		Begin
			INSERT INTO TA_Tbl_AuditField(TableID,FieldName,FieldDescription,InsertBit,UpdateBit,DeleteBit,Status,DataType) VALUES(@tableId,@fieldName,@fieldDescription,@insertBitStatus,@updateBitStatus,@deleteBitStatus,@fieldStatus,@DataType)
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAutoShiftDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<P Velumani>
-- Create date: <13/07/2019>
-- Description:	<Add update Auto Shift Configuration info against Employeeid>
--Proc_TA_InsertAutoShiftDetails 4,1,0,0,0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAutoShiftDetails]
@EmployeeId int,
@shiftID1 int,
@shiftID2 int,
@shiftID3 int,
@shiftID4 int,
@shiftID5 int,
@UserId int,
@nightShiftEndTimeAutoshift nvarchar(10),
@companyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF NOT EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId=@EmployeeId )
	BEGIN
		INSERT INTO TA_Tbl_AutoShiftConfiguration(EmployeeId,ShiftId1,ShiftId2,ShiftId3,ShiftId4,ShiftId5,CreatedBy, CreatedDate) 
		values (@EmployeeId,@shiftID1,@shiftID2,@shiftID3,@shiftID4,@shiftID5,@UserId,getdate())
	END
	ELSE IF EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId=@EmployeeId )
	BEGIN
		Update TA_Tbl_AutoShiftConfiguration set
		ShiftId1 = @shiftID1,
		ShiftId2 = @shiftID2,
		ShiftId3 = @shiftID3,
		ShiftId4 = @shiftID4,
		ShiftId5 = @shiftID5,
		ModifiedBy = @UserId,
		ModifiedDate = getdate()
		where EmployeeId = @EmployeeId
	END

	if Exists(Select * From TA_Tbl_ShiftSettings where NightShiftEndTime_Autoshift is Not null and @companyId!='')
	Begin

		update TA_Tbl_ShiftSettings set NightShiftEndTime_Autoshift=@nightShiftEndTimeAutoshift where CompanyId=@companyId

	End
	Else
	Begin
		update TA_Tbl_ShiftSettings set NightShiftEndTime_Autoshift=@nightShiftEndTimeAutoshift
	End

END


--Select * From TA_Tbl_AutoShiftConfiguration

--update TA_Tbl_ShiftSettings set NightShiftEndTime_Autoshift='2.00' 



--Alter table TA_Tbl_ShiftSettings Add NightShiftEndTime_Autoshift  nvarchar(10)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertChildrendetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_InsertChildrendetails] 
(
@EmpID INT=0,
@childrenname NVARCHAR(50),
@childrendob NVARCHAR(15),
@EmployeeID INT=0
)
AS
BEGIN
	declare @sql as nvarchar(3000) 
	IF (@childrendob='')
	BEGIN
		SET @childrendob=NULL
	END
	set @sql = 'INSERT INTO TA_Tbl_EmpChildrenDetails(Emp_ID,Spouse_Child,Name,DOB,Isdeleted,Employee_ID) 
	VALUES ('+cast(@EmpID as nvarchar(25))+',''C'',N'''+@childrenname+''',N'''+@childrendob+''',0,'+cast(@EmployeeID as nvarchar(25))+')'
    exec(@sql) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompanyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertCompanyDetails]
(@Type char(1),@CompanyId int=0,@CompanyName nvarchar(50),@CompanyDescription nvarchar(255),@CompanyAddress1 nvarchar(255), @CompanyAddress2 nvarchar(255),@CompanyPhone1 nvarchar(15),@CompanyPhone2 nvarchar(15),@CompanyFax1 nvarchar(15),
  @CompanyFax2 nvarchar(15),@CompanyEmail nvarchar(75),@CompanyWebaddress nvarchar(75),@Companylogo image)
as
DECLARE @Isdel int,@Count int
SET @Isdel=1
--Insert Method
if(@Type='I')
Begin  
   select @Count=count(*) FROM TA_Tbl_CompanyDetails WHERE Company_Name=@CompanyName  and IsDeleted=@Isdel 
  if(@Count=0)
  BEGIN
     INSERT INTO TA_Tbl_CompanyDetails(Company_Name,Company_Description,Company_Address1,Company_Address2,Company_Phone1,Company_Phone2,Company_Fax1,Company_Fax2,Company_Email,Company_WebAddress,Company_Logo,IsDeleted)
   VALUES(@CompanyName,@CompanyDescription,@CompanyAddress1, @CompanyAddress2,@CompanyPhone1,@CompanyPhone2,@CompanyFax1,@CompanyFax2,@CompanyEmail,@CompanyWebaddress,@Companylogo,@Isdel)
   END   						
end
--Update Method
if(@Type='U')
   BEGIN
   UPDATE TA_Tbl_CompanyDetails SET Company_Name=@CompanyName,Company_Description=@CompanyDescription,Company_Address1=@CompanyAddress1,Company_Address2=@CompanyAddress2,Company_Phone1=@CompanyPhone1,Company_Phone2=@CompanyPhone2,
   Company_Fax1=@CompanyFax1,Company_Fax2=@CompanyFax2,Company_Email=@CompanyEmail,Company_WebAddress=@CompanyWebaddress,Company_Logo=@Companylogo WHERE Company_Id=@CompanyId
   END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompensationEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/**********************************************************
Updated by    :A.Amsaveni  on 02/07/2013
Description   : added and Isdeleted=0  
***********************************************************/
-- Proc_TA_InsertCompensationEntry '654','2017-01-19','2016-12-04',1,'Test','Pending for Approval','10:51 AM','05:51 PM','07:00','Weekly Off','',1,-1
Create PROCEDURE [dbo].[Proc_TA_InsertCompensationEntry]
	@Employee_Id NVARCHAR(20),
	@ApplicationDate DATETIME,
	@FromDate DATETIME,
	@Status NVARCHAR(20),
	@InTime NVARCHAR(20),
	@OutTime NVARCHAR(20),
	@WorkedHours NVARCHAR(20),
	@DayWorked NVARCHAR(20),
	@ExpDate DATETIME,
	@Quota float, 
	@Empid bigint
AS      
BEGIN      
	SET NOCOUNT ON;		  
	IF NOT EXISTS(SELECT Compensation_Id FROM ta_tbl_compensation WHERE Employee_Id=@Employee_Id and Fromdate=@FromDate and Isdeleted=0)    
	BEGIN
		DECLARE @EmployeeId INT
		DECLARE @levelId AS BIGINT
		Declare @ExpiryDuration int
		Declare @HalfDayCompOff int
		Declare @FullDayCompOff int
		Declare @TotWorkedMins int		
		--Added by manikandan.R on 19-11-2016
		select * from TA_Tbl_ShiftSettings
		--Get Exp date
		select @ExpiryDuration=VaildityCompOffDays from TA_Tbl_ShiftSettings	
		-- Get Employee ID from employee master
		SELECT @EmployeeId=Employee_Id  FROM ta_tbl_employee WHERE employee_code_Id=@Employee_Id  and Isdeleted=0 
		--Get Level Id from employee leave table
		select @levelId=LevelId from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId order by EffectiveDate
		set @TotWorkedMins=SUBSTRING(@WorkedHours,0,CHARINDEX(':',@WorkedHours))*60+SUBSTRING(@WorkedHours,CHARINDEX(':',@WorkedHours)+1,LEN(@WorkedHours))
		set @ExpDate=DATEADD(d,@ExpiryDuration,@FromDate)	
		INSERT INTO TA_Tbl_Compensation
		(
			Employee_Id,
			ApplicationDate,
			FromDate,				
			LevelId,
			status,
			InTime,
			OutTime,
			WorkedHours,
			DayWorked,
			ExpiredDate,
			Quota,
			empid,
			ApprovedBy,
			ApprovedDate,				
			TimeStamp,
			Isdeleted,
			RemainingLeave
		)
		VALUES
		(
			@Employee_Id,
			@ApplicationDate,
			@FromDate,
			@levelId,
			@Status,
			@InTime,
			@OutTime,
			@WorkedHours,
			@DayWorked,
			@ExpDate,
			case when @TotWorkedMins>=@FullDayCompOff then 1 else 0.5 end,
			@Empid,
			case when @Status='Approved' then @Empid else null end,
			case when @Status='Approved' then getdate() else null end,
			GETDATE(),
			0,
			case when @TotWorkedMins>=@FullDayCompOff then 1 else 0.5 end
		)
		SELECT '1' 
	END  
	ELSE    
	BEGIN    
		SELECT '0'    
	END    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_insertCompOffOTStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_EmployeeOTStatus  
Description		:	To Update the OverTime Status in ta_tbl_processedData  table
Tables Included :	ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		:	Karthikeyan.R
Created On		:	21-Mar-2017
Proc_TA_insertCompOffOTStatus 23685,45,'2017/04/11','2017/04/02','12:00',720,'Approved',1,'Weekly Off','09:00','21:00','Test',4,0,'I'

Proc_TA_insertCompOffOTStatus 4046,35,'16/Aug/2022','08/Aug/2022','04:00',240,'Pending',1,'09:00 AM','10:00 PM','tst',4,'1','1'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_insertCompOffOTStatus]
	@Process_Rec_ID BIGINT ,
	@Employee_Id INT ,
	@ApplicationDate datetime ,
	@Date datetime ,
	@HrsExtra VARCHAR(5) ,
	@ExtraMins INT ,
	@Status VARCHAR(50) ,
	@TopLevelId INT,
	@DaysWorked nvarchar(25),
	@InTime nvarchar(20),
	@OutTime nvarchar(20),
	@Reason nvarchar(250),
	@ExtraTime_Id bigint,
	@Approved_By nvarchar(10)
	--@tag nvarchar(2)
As
BEGIN 
	set nocount on
	declare @ProcessID as bigint
	DECLARE @Index INT 
		set @Index= 0
		DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT,@OtText VARCHAR(MAX)
		DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT,@MaxDate DATETIME
		DECLARE @ValidDates INT
		DECLARE @FromDate DATETIME, @ToDate DATETIME
		DECLARE @Employee_code_Id NVARCHAR(50)
		
	
		SET @CompOffDays = 0
		SET @SumOfOTMins = 0
		SET @OtText = ''
	--IF Update then delete the record and insert again.
	--IF(@tag='D')
	BEGIN
		IF NOT EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE Employee_Id=@Employee_Id and isdelete=0 and Date=@Date)
		BEGIN
			select @ProcessID=Process_RecID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
			update TA_Tbl_ProcessedData set OvertimeStatus=null where Process_Rec_ID=@ProcessID
			delete from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
		END
		else
		BEGIn
			IF EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@ExtraTime_Id)
			BEGIn
				select @ProcessID=Process_RecID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
				update TA_Tbl_ProcessedData set OvertimeStatus=null where Process_Rec_ID=@ProcessID
				delete from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
			END
			else
			BEGIN
				SELECT '0'
			END
		END
	END
	IF NOT EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE Employee_Id=@Employee_Id and isdelete=0 and Date=@Date)
	BEGIN
		--Declare the temp table for the insert and update perpose.
		DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,ApplicationDate varchar(20),[Date] varchar(20), HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT, DateToExpired DATETIME, NoOfDays NUMERIC(18,1), RemainingDays NUMERIC(18,1), CompOffSatus VARCHAR(30), TopLevelId INT, UpdatedRow VARCHAR(1),DaysWorked nvarchar(20),InTime nvarchar(20),OutTime nvarchar(20),Reason nvarchar(250))
		-- Insert the values from variable
		INSERT INTO @TblRecords(Process_RecID, Employee_Id,ApplicationDate, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, TopLevelId,DaysWorked, InTime, OutTime,Reason) values (@Process_Rec_ID,@Employee_Id,@ApplicationDate,@Date ,@HrsExtra ,@ExtraMins,@Status,1,0,@TopLevelId,@DaysWorked,@InTime,@OutTime,@Reason)
		SELECT @Employee_code_Id = Employee_Code_Id FROM TA_Tbl_Employee WHERE Employee_Id = @Employee_Id AND IsDeleted=0
		SELECT @FromDate = FromDate,@ToDate = ToDate FROM TA_Tbl_YearSetting WHERE YearSettings_Id in (select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)
			SELECT		@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,'00:00', ISNULL(OtMinHrs, '00:00')),
						@FullDayOTMins = DATEDIFF(MI,'00:00',ISNULL(FullDayOTMinHrs, '00:00')),
						@ValidDates = ISNULL(LP.CompOffValidDays, 60)
						FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
						WHERE ELP.EmployeeId = @Employee_Id AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
						INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
						WHERE YS.IsActive = 1 AND ELP.EmployeeId = @Employee_Id ORDER BY ELP.ToDate DESC)
		update @TblRecords set DateToExpired=(DATEADD(D, @ValidDates, [Date])),NoOfDays=(CASE WHEN ExtraMins >= @FullDayOTMins THEN 1.0 WHEN ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),RemainingDays=(CASE WHEN ExtraMins >= @FullDayOTMins THEN 1.0 WHEN ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),[Date]) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END)
		--Comment by karthikeyan.R 
		--IF(@TypeOfOT=1)
				--	BEGIN
				--		SELECT 
				--			@SumOfOTMins = (@SumOfOTMins + OtMins),
				--			@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),
				--			@OtText = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @OtText ELSE (@OtText + ';' + CAST(Process_Rec_ID AS VARCHAR(50)) + '&' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
				--			@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '') = '' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),
				--			@MaxDate = NULL
				--		FROM TA_Tbl_ProcessedData
				--			WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id 
				--			AND (DATEADD(D, @ValidDates, [Date])) >= @Date AND OtMins > 0 AND ISNULL(OtMins, '') != ''
				--		ORDER BY [Date]
				--	END
			--UPDATE @TblRecords SET 
		--	DateToExpired = CASE WHEN (TR.OverTimeStatus = 'Pending' or TR.OverTimeStatus = 'Forwarded' or TR.OverTimeStatus = 'Approved')
		--	AND TR.CompOffEligible = 1 THEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0), CONVERT(datetime,TR.[Date],103)) END,
		--	NoOfDays =	CASE WHEN (TR.OverTimeStatus = 'Pending' or TR.OverTimeStatus = 'Forwarded' or TR.OverTimeStatus = 'Approved') AND TR.CompOffEligible = 1 THEN	
		--									(	CASE	WHEN TR.ExtraMins / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN '1.0' 
		--													WHEN TR.ExtraMins/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' 
		--										END
		--									) 
		--							END,
		--	RemainingDays = CASE WHEN (TR.OverTimeStatus = 'Pending' or TR.OverTimeStatus = 'Forwarded' or TR.OverTimeStatus = 'Approved') AND TR.CompOffEligible = 1 THEN (CASE WHEN TR.ExtraMins / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN '1.0' WHEN TR.ExtraMins/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' END) END,
		--	CompOffSatus = CASE WHEN (TR.OverTimeStatus = 'Pending' or TR.OverTimeStatus = 'Forwarded' or TR.OverTimeStatus = 'Approved') AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),CONVERT(datetime,TR.[Date],103)) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END) END
		--FROM @TblRecords TR
		--INNER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = TR.Process_RecID
		--LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = TR.TopLevelId
		--select * from @TblRecords
		INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id,ApplicationDate, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest,DaysWorked,InTime, OutTime,Reason,isDelete)
			SELECT Process_RecID, Employee_Id,CONVERT(datetime,ApplicationDate,103),CONVERT(datetime,[Date],103), 
			HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, 
			DateToExpired, NoOfDays, RemainingDays, CompOffSatus,1,DaysWorked,InTime,OutTime,Reason,0 FROM @TblRecords 
			--select * from @TblRecords
			
		SELECT '1' 
	END	 
	else 
	begin
		SELECT '0'    
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertDashboardRightsDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <07-10-2016 14.39>
-- Description:	<Insert and Update the Dashboard Rights Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertDashboardRightsDetails]
	-- Add the parameters for the stored procedure here
	@UsergroupName varchar(250),
	@BoardId int,
	@Dashboard int,
	@Gridview int,
	@Chart int,	
	@Empid int,
	@Viewprev int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Usergroupid int
    set @UsergroupId=(select groupId from TA_Tbl_Usergroup where groupName=@UsergroupName and isDeleted=0)
	if exists(select * from ta_tbl_DashboardUserrights where Usergroupid=@Usergroupid and BoardId=@BoardId)
	begin
		update ta_tbl_DashboardUserrights set Empid=@Empid,ViewPrev=@Viewprev,Dashboard=@Dashboard,Gridview=@Gridview,Chart=@Chart
		where Usergroupid=@Usergroupid and BoardId=@BoardId
	end 
	else
	begin		
		insert into ta_tbl_DashboardUserrights values(@Usergroupid,@BoardId,@Viewprev,@Dashboard,@Gridview,@Chart,@Empid)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDataAfterYearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_InsertDataAfterYearClosure
Description	:	It is used to insert or update values based on input
Tables used	:	TA_Tbl_YearClosure 
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
*/
CREATE   procedure [dbo].[Proc_TA_InsertDataAfterYearClosure]      
(      
	@Year_SettingID INT,      
	@OrgLevelId INT,      
	@Employee_Id INT,      
	@LeaveTypeID INT,      
	@CarryPrevYear_AvailDays FLOAT,      
	@Current_Quota INT, 
	@AvailableLeaves FLOAT,           
	@Emp_ID INT      
)      
AS      
Begin
	DECLARE @count as int

	Declare @UTCTime datetime 
	Set @UTCTime=[dbo].[GetUTCTimeZoneDateTime](@Emp_ID)

	SELECT @count=count(YearClosureId) from TA_Tbl_YearClosure where Year_SettingID=@Year_SettingID 
	AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID
	if(@count>0)
	BEGIN
		UPDATE TA_Tbl_YearClosure
		SET Carry_PrevYear=@CarryPrevYear_AvailDays,    Current_Quota=@Current_Quota,Available_Leaves=@AvailableLeaves,Emp_ID=@Emp_ID,Time_Stamp=@UTCTime
		WHERE Year_SettingID=@Year_SettingID AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID 
	END
	ELSE
	BEGIN 
		INSERT INTO TA_Tbl_YearClosure(Year_SettingID ,OrgLevelId  ,Employee_Id  ,LeaveTypeID ,Carry_PrevYear,Current_Quota ,Available_Leaves,Time_Stamp,Emp_ID   )      
		VALUES (@Year_SettingID,   @OrgLevelId   ,@Employee_Id   ,@LeaveTypeID  ,@CarryPrevYear_AvailDays,    @Current_Quota ,@AvailableLeaves,@UTCTime,@Emp_ID   )      
	END
End

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDemoInfo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Thilakraj>
-- Create date: <26-Nov-2013>
-- Description:	<To insert Demo Version in Table>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertDemoInfo]
	@DemoType nVarchar(50)
AS
BEGIN
	if exists(Select * from TA_Tbl_Demo)
	Begin 
	Delete from TA_Tbl_Demo
	Insert Into TA_Tbl_Demo(DemoType) Values(@DemoType)
	End
	Else
	Begin
		Insert Into TA_Tbl_Demo(DemoType) Values(@DemoType)
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDepartment]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertDepartment]
(@CompanyId int,@RegionId int,@BranchId int,@DepartmentName nvarchar(50),@DepartDes nvarchar(255))
as
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	INSERT INTO TA_Tbl_Department (Company_Id,Region_Id,Branch_Id,Department_Name,Department_Description,Isdeleted) VALUES(@CompanyId,@RegionId,@BranchId,@DepartmentName,@DepartDes,@Isdel)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDiscrepancyData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_InsertDiscrepancyData] 'emp102','01/01/2009','03:44 pm','In',0,'','','',0,6
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertDiscrepancyData]
	@EmployeeCodeID as nvarchar(25),
	@InDate as nvarchar(20),
	@InTime as nvarchar(20),
	@InPunchType as nvarchar(25),
	@InReaderID as int,
	@OutDate as nvarchar(20),
	@OutTime as nvarchar(20),
	@OutPunchType as nvarchar(25),
	@OutReaderID as int,
	@EmpID as int,
	@strManaulEntryStatus as nvarchar(30),
	@Reason as nvarchar(255)
AS
BEGIN
	set nocount on;
	if @OutDate=''
	begin
		set @OutDate=NULL
	end
	if @InDate=''
	begin
		set @InDate=NULL
	end
	if @Intime=''
	begin
		set @InTime=NULL
	end
	if @OutTime=''
	begin
		set @OutTime=NULL
	end
	if (@Reason='' or @Reason is null)
	begin
		set @Reason='Discrepancy Entry'
	end
	if(@strManaulEntryStatus='')
	begin
		set @strManaulEntryStatus='Pending'
	end
	--Declare @Terminal_Id int
	--Declare @Terminal_IdCount int
	--if(@InReaderID=0)
	--BEGIN		
	--	select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787'
	--	if(@Terminal_Id='')
	--	begin
	--		insert into TA_Tbl_Terminal values('787','787','787',1,GETDATE(),1,0)			
	--		select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787'
	--	end		
	--	if(@Terminal_Id!='')
	--	begin
	--		select @Terminal_IdCount=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
	--		if(@Terminal_IdCount=2)
	--		begin
	--			set @InReaderID=@Terminal_Id
	--			set @OutReaderID=@Terminal_Id
	--		end
	--		else if(@Terminal_IdCount=1)
	--		begin
	--			set @InReaderID=@Terminal_Id
	--		end			
	--		if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@Terminal_Id and PunchType=@InPunchType)
	--		begin
	--			select top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@Terminal_Id
	--		end
	--		IF(@OutReaderID!=0)
	--		BEGIN
	--			if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID and PunchType=@OutPunchType)
	--			begin
	--				select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID
	--			end
	--		end
	--	end		
	--END	
	--IF(@OutReaderID=0)
	--BEGIN
	--	set @Terminal_Id =''
	--	select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788'
	--	if(@Terminal_Id='')
	--	begin
	--		insert into TA_Tbl_Terminal values('788','788','788',1,GETDATE(),1,0)			
	--		select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788'
	--	end
	--	if(@Terminal_Id!='')
	--	begin
	--		select @Terminal_IdCount=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
	--		if(@Terminal_IdCount=1)
	--		begin
	--			set @OutReaderID=@Terminal_Id
	--		end
	--		if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID and PunchType=@OutPunchType)
	--		begin
	--			select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID
	--		end
	--	end	
	--END	
	declare @YearID as int
	select @YearID = YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1
	
	insert into Ta_Tbl_ManualTimeEntry 
	(
		ManualTimeEntry_Date,
		ManualTimeEntry_Employee_Id,
		ManualTimeEntry_InDate,
		ManualTimeEntry_InTime,
		ManualTimeEntry_InPunchType,
		ManualTimeEntry_InReaderID,
		ManualTimeEntry_OutDate,
		ManualTimeEntry_OutTime,
		ManualTimeEntry_OutPunchType,
		ManualTimeEntry_OutReaderID,
		ManualTimeEntry_Reason,
		Clk_Process,
		ManualTimeEntry_Status,
		YearSettings_Id,
		Isdeleted,
		Emp_ID,
		IsDiscrepancyEntry,
		IsOnDuty
	)
	values 
	(
		Convert(varchar(15),getDate(),101),
		@EmployeeCodeID,
		@InDate,
		@InTime,
		@InPunchType,
		@InReaderID,
		@OutDate,
		@OutTime,
		@OutPunchType,
		@OutReaderID,
		@Reason,
		'N',
		@strManaulEntryStatus,
		@YearID,
		0,
		@EmpID,
		1,
		0
	)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]
(
	@ScheduleId int,
	@MailType varchar(5),
	@EmailId varchar(250)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	insert into TA_tbl_MailIdsForTriggeringEmail (ScheduleId,MailType,EmailID) values (@ScheduleId,@MailType,@EmailId)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailScheduleStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_InsertEmailScheduleStatus] 23,'04-Apr-2022','09-Apr-2022','2022-04-13',1,'758','manikanda',''
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmailScheduleStatus]
(
	@ScheduleId int,
	@DurationFrom datetime,
	@DurationTo datetime,
	@SentDate datetime,
	@Status int,
	@To_Mail varchar(20)=null,
	@EmailID varchar(max)=null,
	@ErrorMessage nvarchar(max)=null
)
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    IF(@ErrorMessage!='MailSendSuccessfully')
    BEGIN    
		INSERT INTO TA_tbl_EmailScheduleStatus VALUES 
		(@ScheduleId,@DurationFrom,@DurationTo,GETDATE(),@Status,@To_Mail,@EmailID,@ErrorMessage)
	END
	IF(@Status=1)
	BEGIN
		IF EXISTS(SELECT ScheduleId FROM TA_Tbl_EmailSchedule where ScheduleId=@ScheduleId and Reminder_afterDays!=0)
		BEGIN
			Declare @reminderDate int
			SELECT @reminderDate=Reminder_afterDays FROM TA_Tbl_EmailSchedule where ScheduleId=@ScheduleId 
			IF(@reminderDate!=0)
			BEGIN
				IF NOT EXISTS(SELECT ScheduledID FROM Ta_Tbl_EmailScheduleReminder where ScheduledID=@ScheduleId and CONVERT(varchar(11),ReminderDate)=CONVERT(varchar(11),dateadd(d,@reminderDate,GETDATE())))
				BEGIN
					INSERT INTO Ta_Tbl_EmailScheduleReminder VALUES(@ScheduleId,DATEADD(d,@reminderDate,@SentDate),0,@DurationFrom,@DurationTo)
				END
			END
			IF(@ErrorMessage='MailSendSuccessfully')
			BEGIN
				UPDATE TA_Tbl_EmailSchedulereminder SET STATUS=1 where ScheduledID=@ScheduleId and CONVERT(varchar(11),reminderdate)=CONVERT(varchar(11),getdate())
			END
		END
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: <ALTER  Date,,>  
-- Description: <Description,,>  
-- Modified by : Prabakaran.P
-- Modified on : 24-Mar-08
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy]   
 @EmployeeId INT,  
 @LeavePolicyID INT,  
 @Fromdate NVARCHAR(15),  
 @Todate NVARCHAR(15),  
 @auEmpId INT   
AS  
BEGIN  
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)  
	declare @count int 
	declare @YearSettingId as int
	select @count =count(*) from TA_Tbl_Emp_LeavePolicy where EmployeeId = @EmployeeId and  
	((FromDate between @Fromdate and @todate) or (ToDate between @fromDate and @Todate))	
	if (@count=0)
	begin
		select @YearSettingId=YearSettings_Id from Ta_Tbl_YearSetting where IsActive=1
		set @sql = 'INSERT INTO TA_Tbl_Emp_LeavePolicy (EmployeeId,LeavePolicy_Id,FromDate,ToDate,Isdeleted,Emp_Id,YearSettingId)  
					 VALUES ('+cast(@EmployeeId as nvarchar(25))+','+cast(@LeavePolicyID as nvarchar(25))+',N'''+@Fromdate+''',N'''+@Todate+''',0,'+cast(@auEmpId as nvarchar(25))+',' + cast(@YearSettingId as nvarchar(25)) + ')'  
		exec(@sql) 
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_InsertEmp_LeavePolicy_YearClosure
Description	:	It is used to insert values for Employeee Leave Policy
Tables used	:	TA_Tbl_Emp_LeavePolicy and Ta_Tbl_YearSetting
Created by	:	Prabakaran.P
Created on	:	15-Feb-08
Proc_TA_InsertEmp_LeavePolicy_YearClosure 5,161,'01/01/2009','12/31/2009',5,37
*/
CREATE   PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]   
 @EmpID INT,  
 @LeavePolicyID INT,  
 @Fromdate NVARCHAR(15),  
 @Todate NVARCHAR(15),  
 @auEmployeeID INT,
 @YearSettingId int
AS  
declare @sql as nvarchar(3000)  
BEGIN  
 SET NOCOUNT ON;  

 Declare @UTCTime datetime 
	Set @UTCTime=[dbo].[GetUTCTimeZoneDateTime](@EmpID)

declare @count int 
set @count = (select count(*) from TA_Tbl_Emp_LeavePolicy where EmployeeId = @EmpID and LeavePolicy_Id=@LeavePolicyID and FromDate =@Fromdate and ToDate=@Todate)
if (@count=0)
	begin
		set @sql = 'INSERT INTO TA_Tbl_Emp_LeavePolicy (EmployeeId,LeavePolicy_Id,FromDate,ToDate,Isdeleted,Time_stamp,Emp_Id,YearSettingId) VALUES ('+cast(@EmpID as nvarchar(25))+','+cast(@LeavePolicyID as nvarchar(25))+',N'''+@Fromdate+''',N'''+@Todate+''',0,'+@UTCTime+','+cast(@auEmployeeID as nvarchar(25))+',' + cast(@YearSettingId as nvarchar(25)) + ')'  
		exec(@sql)
	end
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpDetails](@EmpId varchar(20),@EmpName varchar(50) )
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TA_Tbl_TempShiftAllocation(EmployeeId,EmployeeName) VALUES(@EmpId,@EmpName);
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpLeavePolicydetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Modified Author:R.Manikandan
-- Modified date: <12-July-2019 04:05 PM>
-- Description:	<Insert Employee Leave policy details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpLeavePolicydetails]
	@EmployeeId INT,
	@EmpLeavepolicyID INT,
	@PolicyID INT,
	@LeaveType_Id INT,
	@No_Of_Days DECIMAL(18,1),
	@auEmpId INT,
	@MaxDays_Month DECIMAL(18,1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)
	 Declare @UTCTime datetime 
	Set @UTCTime=[dbo].[GetUTCTimeZoneDateTime](@auEmpId)

	INSERT INTO TA_Tbl_Emp_LeavePolicyDetails (EmpID,Emp_LeavePolicyId,Policy_ID,LeaveType_Id,No_Of_Days,Isdeleted,Time_Stamp,Emp_Id,MaxDays_Month)
	VALUES (cast(@EmployeeId as nvarchar(25)),cast(@EmpLeavepolicyID as nvarchar(25)),cast(@PolicyID as nvarchar(25)),cast(@LeaveType_Id as nvarchar(25)),cast(@No_Of_Days as nvarchar(25)),0,@UTCTime,cast(@auEmpId as nvarchar(25)),@MaxDays_Month)
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified by : Prabakaran.P
Modified on : 25-June-08
Modified By			:	A.K.T.MOORTHI
Date Of Modified		:	07-Apr-2014
Description			:	Update IsDeleted = 1, InActiveDate = DateOfJoinDate, Employee_Status = 0, Report_Exclude = 1 When Employee Count Greater Then 5, Bze User Can Able To Create N Number Of User.
								But They Can Access Only 5 Employee For Hole Application.
*/
CREATE  PROCEDURE  [dbo].[Proc_TA_InsertEmployeeDetails]   
(  
	@type CHAR(1),
	@EmployeeId INT=0,
	@LevelId INT=0,
	@UserGroupId NVARCHAR(50)='',  
	@DesignationId INT=0,
	@BusRouteId INT=0,
	@EmpFirstName NVARCHAR(50)='',
	@EmpMiddleName NVARCHAR(50)='',  
	@EmpLastName NVARCHAR(50)='',
	@EmpFatherName NVARCHAR(50)='',
	@EmpMotherName NVARCHAR(50)='',
	@dob NVARCHAR(15)=null,  
	@dobrecord NVARCHAR(15)=null,
	@BloodGroup NVARCHAR(10)='',
	@EmailId NVARCHAR(100)='',
	@ContactAddress NVARCHAR(255)='',  
	@PermanentAddress NVARCHAR(255)='',
	@PhoneNo NVARCHAR(20)='',
	@MobileNo NVARCHAR(20)='',
	@Gender NVARCHAR(10)='',  
	@MaritalStatus NVARCHAR(10)='',
	@Nationality NVARCHAR(50)='',
	@Religion INT,  
	@Photo IMAGE,  
	@PersonalEmailId NVARCHAR(100)='',
	@PassportNo NVARCHAR(50)='',
	@PExpiry NVARCHAR(15)=null,
	@VisaNo NVARCHAR(50)='',  
	@VExpiry NVARCHAR(15)=null,
	@VehicleType NVARCHAR(20)='',
	@VehicleNo NVARCHAR(50)='',  
	@AnniversaryDate NVARCHAR(15)=null,  
	@NativePlace INT=0,  
	@District NVARCHAR(50)='',  
	@State INT=0,  
	@Country INT=0,  
	@SpouseNo INT=0,  
	@ChildrenNo INT=0,  
	@EmpCode NVARCHAR(15)='',  	
	@DateOfJoin NVARCHAR(15)=null,  
	@ReportingTo INT=0,   
	@LeaveSancAuthority INT=0,  	  
	@PrevExperience FLOAT=0,  
	@BasicSalary FLOAT,  
	@HostelWorker BIT=0, 
	@Username NVARCHAR(15)='',  
	@Password NVARCHAR(50)='',  
	@Qual_Join NVARCHAR(50)=null,
	@Qual_Employment NVARCHAR(50)=null,  
	@OutDoorJob BIT=0,  
	@CompOffEligible BIT=0,  
	@OTEligible BIT=0,  
	@ESIeligible BIT=0, 
	@PFeligible BIT=0,
	@ReportExclude BIT=0,  
	@EmpStatus BIT=0,  
	@SwipeCardNo NVARCHAR(20),
	@intEmpCategory NVARCHAR(15),
	@intEmpType NVARCHAR(15),  
	@EmpID INT=0,
	@strBasicSalEffDate NVARCHAR(20)=null,
	@strDesigEffDate NVARCHAR(20)=null,
	@intYearSettingsId INT,
	@strLevelEffDate NVARCHAR(20)=null, 
	@strEmpCatEffDate NVARCHAR(20)=null, 
	@strEmpTypeEffDate NVARCHAR(20)=null,
	@intFlexibleTimings int,
	@InActiveDate NVARCHAR(15)=null,	
	@CustomField1 nvarchar(max)=null,
	@CustomField2 nvarchar(max)=null,
	@CustomField3 nvarchar(max)=null,
	@CustomField4 nvarchar(max)=null,
	@CustomField5 nvarchar(max)=null,
	@ApplnMode BIT,
	@penalty bit,
	@MobileClockInOUt bit,
	@SMS bit,
	@IsPassportReminderRequired bit = 0,
	@PassportRemindDays int = 0,
	@IsVisaReminderRequired bit =0,
	@VisaRemindDays int = 0,
	-- payroll config--
	@hra int=0,
	@DA int =0,
	@MA int=0,
	@CA int =0,
	@PFESI int=0,
	@TaxPolicy int=0,
	@CEA int=0,
	@CTC bigint=0

) 
AS  
	set nocount on 
	DECLARE @Isdeleted INT 
	SET @Isdeleted=0  
	DECLARE @countBasicPay INT
	DECLARE @countDesignation INT  
	DECLARE @countLevel INT
	DECLARE @countCategory INT
	DECLARE @countType INT
	DECLARE @Inactive_Status BIT
	Declare @Deleted int
	SET @countBasicPay=0  
	SET @countDesignation=0
	SET @countLevel=0
	SET @countCategory=0
	SET @countType=0
	SET @Inactive_Status = (CASE WHEN ISNULL(@EmpStatus, 0) = 0 or @EmpStatus='' THEN 1 ELSE 0 END)
	if(@Religion=0)
	begin
		select top 1 @Religion=ID from TA_Tbl_Religion where Name='All' and IsDeleted=0
		set @Religion=ISNULL(@Religion,0)
	end
	-- insert  
	IF (@type='I')  
	BEGIN
		if (@Password is null or @Password='') 
		begin
			set @Password='QL5OWbmiorXf+5GMDoaz1w=='
		end
		INSERT INTO TA_Tbl_Employee 
		(
			UserGroup_Id,
			Bus_Id,
			Employee_FirstName,
			Employee_MiddleName,
			Employee_LastName,  
			Father_name,
			Mother_name,
			DateofBirth,
			DateofBirth_Record,
			Blood_Group,
			EmailId,
			Contact_Address,
			Permanent_Address,
			Phone_Number,
			Mobile_Number,
			Gender,
			Marital_status,
			Nationality,
			Religion,
			Personal_mailid,
			Passport_No,  
			Passport_expirydate,
			Visa_No,
			Visa_expirydate,
			Vehicle_Type,
			Vehicle_No,
			Anniversary_Date,
			Native_Place,
			District,
			State,
			Country,
			Spouse_No,
			Children_No,
			Employee_Code_Id,
			DateOfJoining,
			Reporting_To,  
			Leave_Sanc_Authority,
			Prev_Experience,
			Hostel,
			UserName,
			Emp_password,
			Qual_JoiningTime,
			Qual_Employment,
			OutDoorJob,
			CompOff_Eligible,
			OT_Eligible,
			ESI_Eligible,
			PF_Eligible,
			Report_Exclude,
			Employee_Status,
			SwipeCardNo,
			Emp_ID,
			Isdeleted,
			IsFlexible,
			InActiveDate,
			InActive_Status,
			CustomField1,
			CustomField2,
			CustomField3,
			CustomField4,
			CustomField5,
			penalty,
			MobileClockInOUt,
			SMSEnabled,
			Basic_Salary,
			IsPassportReminderRequired,
			PassportRemindDays,
			IsVisaReminderRequired,
			VisaRemindDays,
			HRA,DA,MedicalAlllowance,CEDAllowance,CA,PF_Policy,Tax_Policy,Emp_Ctc
		)
		VALUES 
		(
			@UserGroupId,
			cast(@BusRouteId as nvarchar(25)),
			@EmpFirstName,
			@EmpMiddleName,
			@EmpLastName,
			@EmpFatherName,
			@EmpMotherName,
			case when isnull(@dob,'')='' then null else @dob end,
			case when isnull(@dobrecord,'')='' then null else @dobrecord end,
			@BloodGroup,
			@EmailId,
			@ContactAddress,
			@PermanentAddress,
			@PhoneNo,
			@MobileNo,
			@Gender,
			@MaritalStatus,
			@Nationality,
			convert(varchar(10),@Religion) ,
			@PersonalEmailId,
			@PassportNo,
			case when isnull(@PExpiry,'')='' then null else @PExpiry end,  
			@VisaNo,
			case when isnull(@VExpiry,'')='' then null else @VExpiry end,
			@VehicleType,
			@VehicleNo,
			case when isnull(@AnniversaryDate,'')='' then null else @AnniversaryDate end,
			cast(@NativePlace as nvarchar(25)),
			@District,
			cast(@State as nvarchar(25)),
			cast(@Country as nvarchar(25)),
			cast(@SpouseNo as nvarchar(25)),
			cast(@ChildrenNo as nvarchar(25)),
			@EmpCode,			
			case when isnull(@DateOfJoin,'')='' then null else @DateOfJoin end,
			cast(@ReportingTo as nvarchar(25)),
			cast(@LeaveSancAuthority as nvarchar(25)),     
			cast(@PrevExperience as nvarchar(25)),
			cast(@HostelWorker as nvarchar(25)),
			@Username,
			@Password,
			@Qual_Join,
			@Qual_Employment,
			cast(@OutDoorJob as nvarchar(25)),
			cast(@CompOffEligible as nvarchar(25)),
			cast(@OTEligible as nvarchar(25)),
			cast(@ESIeligible as nvarchar(25)),
			cast(@PFeligible as nvarchar(25)),
			cast(@ReportExclude as nvarchar(25)),
			cast(@EmpStatus as nvarchar(25)),
			@SwipeCardNo,
			cast(@EmpID as nvarchar(25)),
			cast(@Isdeleted as nvarchar(25)),
			cast(@intFlexibleTimings as nvarchar(25)),
			case when isnull(@InActiveDate,'')='' then null else @InActiveDate end ,
			CAST(@Inactive_Status AS VARCHAR(10)),
			cast(@CustomField1 as nvarchar(1000)),
			cast(@CustomField2 as nvarchar(1000)),
			cast(@CustomField3 as nvarchar(1000)),
			cast(@CustomField4 as nvarchar(1000)),
			cast(@CustomField5 as nvarchar(1000)),
			@penalty,
			@MobileClockInOUt,
			@SMS,
			@BasicSalary,
			@IsPassportReminderRequired,
			@PassportRemindDays,
			@IsVisaReminderRequired,
			@VisaRemindDays,
			@hra,@DA,@MA,@CEA,@CA,@PFESI,@TaxPolicy,@CTC
		)
		--exec(@sql)  
		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
		declare @nextId as int    		
		select @nextId =max(employee_id) from ta_tbl_employee	
		INSERT INTO TA_Tbl_EmployeePay (EmployeeId,BasicPay,EffectiveDate,EmpID) VALUES(@nextId,@BasicSalary,@strBasicSalEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeDesignation (EmployeeId,DesignationID,EffectiveDate,EmpID) VALUES(@nextId,@DesignationId,@strDesigEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId,LevelId,EffectiveDate,EmpID) VALUES(@nextId,@LevelId,@strLevelEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeCategory (EmployeeId,CategoryId,EffectiveDate,EmpId)VALUES(@nextId,@intEmpCategory,@strEmpCatEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeType (EmployeeId,TypeId,EffectiveDate,EmpId)VALUES(@nextId,@intEmpType,@strEmpTypeEffDate,@EmpID)
		Insert Into TA_Tbl_LevelChanges(EmployeeId,Emp_LevelID,Transfer_FromDate) Values(@EmployeeId,@LevelId,cast(Convert(date,getdate()) as nvarchar(20)))

		-- Type Details Insert Ends here
		if @Deleted=1
		begin
			Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
		end
	END
	---update  
	ELSE IF (@type='U')  
	BEGIN  
		IF (@Password is null or @Password='')  
		BEGIN  
			SELECT @Password = Emp_password FROM TA_Tbl_Employee WHERE Employee_Id =@EmployeeId  
			if (@Password is null or @Password='') 
			begin
				set @Password='QL5OWbmiorXf+5GMDoaz1w=='
			end
		END
		--Manual Entry Employee Code Update, while changing the Employee Code Id
		DECLARE @EmployeeCodeId as varchar(15)
		SELECT @EmployeeCodeId=Employee_Code_Id FROM TA_Tbl_Employee WHERE Employee_Id =@EmployeeId
		if(@EmployeeCodeId<>@EmpCode)
		BEGIN
			update TA_Tbl_ManualTimeEntry set ManualTimeEntry_Employee_Id=@EmpCode where ManualTimeEntry_Employee_Id=@EmployeeCodeId
		END
		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]

			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
		UPDATE TA_Tbl_Employee SET
		MobileClockInOUt = @MobileClockInOUt,
		SMSEnabled=@SMS,
		penalty=@penalty,	
		UserGroup_Id=@UserGroupId,  
		Bus_Id=cast(@BusRouteId as nvarchar(25)),Employee_FirstName=@EmpFirstName,Employee_MiddleName=@EmpMiddleName,Employee_LastName=@EmpLastName,Father_name=@EmpFatherName,Mother_name=@EmpMotherName, 
		Blood_Group=@BloodGroup,EmailId=@EmailId,Contact_Address=@ContactAddress,Permanent_Address=@PermanentAddress,Phone_Number=@PhoneNo,Mobile_Number=@MobileNo,Gender=@Gender,Marital_status=@MaritalStatus,  
		Nationality=@Nationality,Religion=convert(varchar(10),@Religion),Personal_mailid=@PersonalEmailId,Passport_No=@PassportNo,Visa_No=@VisaNo,Vehicle_Type=@VehicleType,  
		Vehicle_No=@VehicleNo,Native_Place=cast(@NativePlace as nvarchar(25)),District=@District,State=cast(@State as nvarchar(25)),Country=cast(@Country as nvarchar(25)),Spouse_No=cast(@SpouseNo as nvarchar(25)),Children_No=cast(@ChildrenNo as nvarchar(25)),Employee_Code_Id=@EmpCode,  
		Reporting_To=cast(@ReportingTo as nvarchar(25)),Leave_Sanc_Authority=cast(@LeaveSancAuthority as nvarchar(25)),Prev_Experience=cast(@PrevExperience as nvarchar(25)),Hostel=cast(@HostelWorker as nvarchar(25)),UserName=@Username,Emp_password=@Password,Qual_JoiningTime=@Qual_Join,  
		Qual_Employment=@Qual_Employment,OutDoorJob=cast(@OutDoorJob as nvarchar(25)),CompOff_Eligible=cast(@CompOffEligible as nvarchar(25)),OT_Eligible=cast(@OTEligible as nvarchar(25)),ESI_Eligible=cast(@ESIeligible as nvarchar(25)),PF_Eligible=cast(@PFeligible as nvarchar(25)),
		Report_Exclude=cast(@ReportExclude as nvarchar(25)),
		Employee_Status=cast(@EmpStatus as nvarchar(25)),
		SwipeCardNo=@SwipeCardNo,
		modify_by=cast(@EmpID as nvarchar(25)),
		modify_date=cast(getdate() as nvarchar(25)),
		IsFlexible=cast(@intFlexibleTimings as nvarchar(25)),
		CustomField1  =cast(@CustomField1 as nvarchar(1000)),
		CustomField2  =cast(@CustomField2 as nvarchar(1000)),
		CustomField3  =cast(@CustomField3 as nvarchar(1000)),
		CustomField4  =cast(@CustomField4 as nvarchar(1000)),
		CustomField5  =cast(@CustomField5 as nvarchar(1000)),
		InActiveDate= case @InActiveDate when '' then null else @InActiveDate end,
		InActive_Status = CAST(@Inactive_Status AS VARCHAR(10)),
		Basic_Salary=@BasicSalary,
		DateofBirth_Record=	case when isnull(@dobrecord,'')=''	then null else @dobrecord end,		
		Anniversary_Date=	case when isnull(@AnniversaryDate,'')='' then null else @AnniversaryDate end,
		DateOfJoining=		case when isnull(@DateOfJoin,'')='' then null else @DateOfJoin end,
		DateofBirth=		case when isnull(@dob,'')=''		then null else @dob end,
		Photo=case when (@Photo is null)then null else @Photo end,
		IsPassportReminderRequired = @IsPassportReminderRequired,
        IsVisaReminderRequired = @IsVisaReminderRequired,
		HRA=@hra,DA=@DA,CA=@CA,CEDAllowance=@CEA,PF_Policy=@PFESI,Tax_Policy=@TaxPolicy,Emp_Ctc=@CTC 
		where Employee_Id = @EmployeeId	

		-- Organization Level Changes insert into Table Created By Maria Prasanth 11:05 22-02-2023

		IF((Select Count(*) From TA_Tbl_LevelChanges where Transfer_FromDate>=Cast(Convert(date,GETDATE()) as varchar(20))and Transfer_ToDate IS Null and EmployeeID=@EmployeeId)>0)
		begin
			
			Update TA_Tbl_LevelChanges set Emp_LevelID=@LevelId where EmployeeID=@EmployeeId and Transfer_FromDate>=Cast(Convert(date,GETDATE()) as varchar(20))
		End
		Else
		Begin
			
			Declare @PreviousFromDate DateTime

			Select @PreviousFromDate=Transfer_FromDate  From TA_Tbl_LevelChanges where EmployeeId=@EmployeeId 

			print @PreviousFromDate

			Update TA_Tbl_LevelChanges set Transfer_ToDate=cast(Convert(date,DateAdd(day,-1,getdate())) as nvarchar(20)) where EmployeeID=@EmployeeId and Transfer_ToDate is Null

			Insert Into TA_Tbl_LevelChanges(EmployeeId,Emp_LevelID,Transfer_FromDate) Values(@EmployeeId,@LevelId,cast(Convert(date,getdate()) as nvarchar(20)))
		End

		IF((SELECT CONVERT(datetime,Passport_expirydate) from TA_Tbl_Employee where Employee_Id=@EmployeeId)!=CONVERT(datetime,@PExpiry))
		begin
			update TA_Tbl_Employee set Passport_expirydate=case when isnull(@PExpiry,'')=''	then null else @PExpiry end,
			PassportRemindDays=null where Employee_Id=@EmployeeId
		end
		
		IF((SELECT CONVERT(datetime,Visa_expirydate) from TA_Tbl_Employee where Employee_Id=@EmployeeId)!=CONVERT(datetime,@VExpiry))
		begin
			update TA_Tbl_Employee set Visa_expirydate=	case when isnull(@VExpiry,'')=''	then null else @VExpiry end,
			VisaRemindDays=null where Employee_Id=@EmployeeId
		end				
		if @Deleted=1
			begin
				Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			end			
		-- UPDATE/Insert Employee Basic Pay Details
		BEGIN
			select @countBasicPay=count(EmployeeId) from TA_Tbl_EmployeePay where EffectiveDate=@strBasicSalEffDate and EmployeeId = @EmployeeId
			if(@countBasicPay=0)
			begin
				--Adding Timestamp to getdate() for null insert value error while modifyinh the employee by MAnjula.P on 09-Oct-2013
				INSERT INTO TA_Tbl_EmployeePay (EmployeeId,BasicPay,EffectiveDate,EmpID,Timestamp)VALUES(@EmployeeId,@BasicSalary,@strBasicSalEffDate,@EmpID,GETDATE())
			end
			else
			begin
				UPDATE TA_Tbl_EmployeePay SET BasicPay=@BasicSalary,EmpID=@EmpID where EmployeeId = @EmployeeId  and EffectiveDate=@strBasicSalEffDate
			end
		END
		-- Employee Pay Details UPDATE ends here
		-- Insert/Update Employee Designation Details
		BEGIN
			Select @countDesignation=count(EmployeeId) from TA_Tbl_EmployeeDesignation where EffectiveDate=@strDesigEffDate and EmployeeId = @EmployeeId
			if(@countDesignation=0)
				begin
					INSERT INTO TA_Tbl_EmployeeDesignation (EmployeeId,DesignationID,EffectiveDate,EmpID) VALUES(@EmployeeId,@DesignationId,@strDesigEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeDesignation SET DesignationID=@DesignationId,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strDesigEffDate  
				end
		END
		-- Designation Details Insert Ends here
		-- Insert/Update Employee Level Details
		BEGIN
			Select @countLevel=count(EmployeeId) from TA_Tbl_EmployeeLevel where EffectiveDate=@strLevelEffDate and EmployeeId = @EmployeeId
			if(@countLevel=0)
				begin
					INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId,LevelID,EffectiveDate,EmpID) VALUES(@EmployeeId,@LevelId,@strLevelEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeLevel SET LevelId=@LevelId,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strLevelEffDate  
				end
		END
		-- Level Details Insert/Update Ends here
		-- Insert/Update Employee Category Details
		BEGIN
			Select @countCategory=count(EmployeeId) from TA_Tbl_EmployeeCategory where EffectiveDate=@strEmpCatEffDate and EmployeeId = @EmployeeId
			if(@countCategory=0)
				begin				
					INSERT INTO TA_Tbl_EmployeeCategory (EmployeeId,CategoryId,EffectiveDate,EmpID) VALUES(@EmployeeId,@intEmpCategory,@strEmpCatEffDate,@EmpID)
				end
			else
				begin				
					UPDATE TA_Tbl_EmployeeCategory SET CategoryId=@intEmpCategory,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strEmpCatEffDate  
				end
		END
		-- Category Details Insert/Update Ends here
		-- Insert/Update Employee Type Details
		BEGIN
			Select @countType=count(EmployeeId) from TA_Tbl_EmployeeType where EffectiveDate=@strEmpTypeEffDate and EmployeeId = @EmployeeId
			if(@countType=0)
				begin
					INSERT INTO TA_Tbl_EmployeeType (EmployeeId,TypeId,EffectiveDate,EmpID) VALUES(@EmployeeId,@intEmpType,@strEmpTypeEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeType SET TypeId=@intEmpType,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strEmpTypeEffDate  
				end
		END
		IF(@ApplnMode = 0)
		BEGIN		
			IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTrigTA_Tbl_Employee]'))
			begin
				--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
				DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
				set @Deleted=1
			end	
			/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
			UPDATE TA_Tbl_Employee SET
				Isdeleted = 1,
				--Report_Exclude = 1,
				Employee_Status = 0,
				InActiveDate = DATEADD(D, 1, DateOfJoining)
			WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> '18000000' ) AND
				Employee_Code_Id <> '18000000' AND ISNULL(InActive_Status, 0) = 0
			/* End */
			if @Deleted=1
			begin
				Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			end
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails]
@EmployeeCodeId nvarchar(50),
@deviceId nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	if exists(Select Employee_Code_Id from TA_Tbl_EmployeeEntrance where Employee_Code_Id=@EmployeeCodeId)
	begin
			Update TA_Tbl_EmployeeEntrance set Device_Id=@deviceId Where Employee_Code_Id=@EmployeeCodeId
	End
	Else
	begin
		Insert into TA_Tbl_EmployeeEntrance (Employee_Code_Id,Device_Id) values(@EmployeeCodeId,@deviceId);
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]
	@EmployeeCodeId NVARCHAR(50),
	@deviceId NVARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT Employee_Code_Id FROM TA_Tbl_EmployeeEntrance WHERE Employee_Code_Id=@EmployeeCodeId)
	BEGIN
		UPDATE TA_Tbl_EmployeeEntrance set Device_Id=@deviceId WHERE Employee_Code_Id=@EmployeeCodeId
	END
	ELSE
	BEGIN
		INSERT INTO TA_Tbl_EmployeeEntrance (Employee_Code_Id,Device_Id) VALUES(@EmployeeCodeId,@deviceId);
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpName] 
--[Proc_TA_InsertEmpName] '1','2','3'
(@EmpID INT,@EmployeeId nvarchar(20),@EmpName nvarchar(50), @loginEmployeeId INT)  
AS  
BEGIN  
 SET NOCOUNT ON;  
 declare @recCount int  
declare @sql nvarchar(2000)
set @sql = ''
 set @recCount = (select count(*) from ta_tbl_TempShiftAllocation where EmpID=@EmpID and LoginEmployeeId=@loginEmployeeId)  
 if (@recCount=0)  
 begin  
set @sql = @sql + 'INSERT INTO TA_Tbl_TempShiftAllocation VALUES(' + cast(@EmpID as nvarchar) + ',N''' + @EmployeeId + ''',N''' + @EmpName + ''','+cast(@loginEmployeeId as nvarchar)+')' ;
exec(@sql)
 end  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpNameGroupPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpNameGroupPolicy]         
/****************************************************************************************/            
-- Name    : [Proc_TA_InsertEmpNameGroupPolicy] 223,'1231235676','ewqqwe wqeq',6,'2009/01/01',1           
-- Desc    : To add the enties in TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : P.Santhosh Raj            
-- Date    : 25-Mar-2009            
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/       
(    
@EmpID INT,    
@EmployeeId nvarchar(20),    
@EmpName nvarchar(50),     
@loginEmployeeId INT,    
@DateOfJoining varchar(30),  
@LevelID int  
)          
AS          
BEGIN          
 SET NOCOUNT ON;          
declare @recCount int          
declare @sql nvarchar(2000)        
set @sql = ''        
 set @recCount = (select count(*) from TA_Tbl_TempGroupPolicyAllocation where EmpID=@EmpID and LoginEmployeeId=@loginEmployeeId)          
 if (@recCount=0)          
 begin          
set @sql = @sql + 'INSERT INTO TA_Tbl_TempGroupPolicyAllocation VALUES(' + cast(@EmpID as nvarchar) + ',N''' + @EmployeeId + ''',N''' + @EmpName + ''','+cast(@loginEmployeeId as nvarchar)+','''+@DateOfJoining + ''','+cast(@LevelID as nvarchar)+')' ;      
exec(@sql)        
 end          
END          
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEncashmentDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_InsertEncashmentDetails
Description	:	Insert Records in TA_Tbl_Encashment
Tables Included	:	TA_Tbl_Encashment
Created By	:	Prabakaran
Created On	:	28-Nov-07
Modified By	:
Modified On	:
*/
CREATE procedure [dbo].[Proc_TA_InsertEncashmentDetails]
@Employee_Id bigint,
@LeaveTypeId bigint,
@NumberOfDays decimal(18,1),
@Reason nvarchar(50)
as
declare @YearSettingId bigint
set @YearSettingId=(select YearSettings_Id from TA_Tbl_YearSetting Where Isactive=1)
begin
insert into TA_Tbl_Encashment(EmployeeId,LeaveTypeId,NumberOfDays,YearSettingId,Reason,Isdeleted) 
values(@Employee_Id,@LeaveTypeId,@NumberOfDays,@YearSettingId,@Reason,0)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertFolderPath]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- select * from Ta_Tbl_FolderPathConfiguration
-- Create date: <22-Oct-2021 06:38 PM>
-- Description:	<Inserting folder path details>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_InsertFolderPath]
	@Path1 varchar(max),
	@Path2 varchar(max),
	@Path3 varchar(max),
	@Path4 varchar(max),
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if not exists(select * from Ta_Tbl_FolderPathConfiguration)
	begin
		Insert into Ta_Tbl_FolderPathConfiguration(EmployeeFolderPath,OndutyFolderPath,LeaveFolderPath,AttendanceData,CreatedBy,CreatedDate) values(@Path1,@Path2,@Path3,@Path4,@EmployeeID,GETDATE())
		
	end
	else
	begin
		update Ta_Tbl_FolderPathConfiguration set EmployeeFolderPath=@Path1,OndutyFolderPath=@Path2,LeaveFolderPath=@Path3,
		AttendanceData=@Path4,
		ModifiedBy=@EmployeeID, ModifiedDate=GETDATE()
	end
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGeofenceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_InsertGeofenceDetails 'addr','Manikandan',10,'Manikandan','Manikandan','Manikandan','Manikandan','Manikandan','',''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertGeofenceDetails]
	@Options nvarchar(max), 
	@LocationName nvarchar(500),
	@Radius int,
	@Description nvarchar(1000), 
	@Address nvarchar(500),
	@City nvarchar(500),
	@State nvarchar(500),
	@Country nvarchar(500),
	@latitude varchar(30),
	@longitude varchar(30),
	@CreatedBy int,
	@insertflag char(1),
	@geoID bigint
AS
BEGIN	
	SET NOCOUNT ON;
	IF(@insertflag='I')
	BEGIN
		INSERT INTO Ta_tbl_LandMarks
		(
			Options ,
			LocationName ,
			Radius ,
			Description, 
			Address,
			City,
			State,
			Country,
			CreatedBy,
			CreatedDate,
			latitude,
			longitude
		) 
		VALUES
		(
			@Options,
			@LocationName,
			@Radius,
			@Description,
			@Address,
			@City,
			@State,
			@Country,
			@CreatedBy,
			GETDATE(),
			@latitude,
			@longitude
		)
	END
	ELSE
	BEGIN
		UPDATE Ta_tbl_LandMarks SET Options=@Options,
									LocationName=@LocationName,
									Radius=@Radius,
									Description=@Description,
									Address=@Address,
									City=@City,
									State=@State,
									Country=@Country,
									ModifiedBy=@CreatedBy,
									ModifiedDate=GETDATE(),
									latitude=@latitude,
									longitude=@longitude
		WHERE id=@geoID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGetEmployeeLatLongDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertGetEmployeeLatLongDetails] 
	-- Add the parameters for the stored procedure here
	@empId int,
	@Latitude float,
	@Longitude float,
	@EntryDt varchar(20),
	@EntryTime varchar(20),
	@PunchType varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	
	Insert into TA_tbl_FencingAttendance (EmpID,CurrentLatitude,CurrenrLongitude,EntryDate,EntryTime,PunchType) values(@empId,@Latitude,@Longitude,@EntryDt,@EntryTime,@PunchType)

	--Delete From TA_tbl_FencingAttendance 

	--Select * From TA_tbl_FencingAttendance
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGrade]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertGrade] 
	-- Add the parameters for the stored procedure here
	@Type CHAR(1),
	@Grade_ID INT,
	@Grade_Name NVARCHAR(50),
	@Grade_Level INT,
	@EmpID INT
AS
DECLARE @Isdeleted BIT
declare @sql as nvarchar(3000)
SET @Isdeleted=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF (@Type='I')
  begin
	--INSERT INTO TA_Tbl_Grade (Grade_Name,Grade_Level,EmpID,Isdeleted) VALUES(@Grade_Name,@Grade_Level,@EmpID,@Isdeleted)
    set @sql = 'INSERT INTO TA_Tbl_Grade (Grade_Name,Grade_Level,Emp_ID,Isdeleted) VALUES(N'''+@Grade_Name+''','+cast(@Grade_Level as nvarchar(25))+','+cast(@EmpID as nvarchar(25))+','+cast(@Isdeleted as nvarchar(25))+')'
    exec(@sql) 
  end
ELSE IF(@Type='U')
  begin	
    --UPDATE TA_Tbl_Grade SET Grade_Name=@Grade_Name,Grade_Level=@Grade_Level,EmpID=@EmpID WHERE Grade_ID=@Grade_ID
    set @sql = 'UPDATE TA_Tbl_Grade SET Grade_Name=N'''+@Grade_Name+''',Grade_Level='+cast(@Grade_Level as nvarchar(25))+',Emp_ID='+cast(@EmpID as nvarchar(25))+' WHERE Grade_ID='+cast(@Grade_ID as nvarchar(25))+''
    exec(@sql)
  end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--    Proc_TA_InsertHoliday 'I',0,'G','02/29/2008','02/29/2008','test',35,6
CREATE    PROCEDURE [dbo].[Proc_TA_InsertHoliday] 
(
	@Type char(1),
	@HolidayId int=0,
	@HolidayType char(1),
	@Holiday_FromDate datetime,
	@Holiday_Todate datetime,
	@Holiday_Description nvarchar(255),
	@YearSettings_Id nvarchar(25),
	@Emp_Id nvarchar(25),
	@XMLData xml
)
as
	declare @sql as nvarchar(3000)
	declare @Isdeleted bit
	set @Isdeleted=0
	Declare @LevelId int
	set @LevelId=0
   --Insert Method
	if(@Type='I')
		begin
			set @sql = 'INSERT INTO TA_Tbl_Holiday(Holiday_Type,Holiday_FromDate,Holiday_ToDate,Holiday_Description,Isdeleted,YearSettings_Id,Emp_Id,LevelId) VALUES('''+ @HolidayType +''','''+cast(@Holiday_FromDate as nvarchar(25))+''','''+cast(@Holiday_Todate as nvarchar(25))+''',N''' + @Holiday_Description + ''',''' +cast(@Isdeleted as nvarchar(25))+ ''','''+cast(@YearSettings_Id as nvarchar(25))+''','''+ cast(@Emp_Id as nvarchar(25)) +''','''+ cast(@LevelId as nvarchar(10)) +''')'  
			exec(@sql)
			DECLARE @Index int
			declare @TempId int	   
			set @TempId= (select @@Identity)
			set @Index = 0 
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO [TA_Tbl_HolidayChildTable]
			select xm.LevelId,@TempId from OPENXML(@Index, '/DocumentElement/TA_Tbl_Holiday_Levels')
			with (LevelId int 'LevelId') as xm
			exec sp_xml_removedocument @Index  
			
			Declare @holi_dayId int
			
			Select @holi_dayId=Max(Holiday_Id) From TA_Tbl_Holiday where YearSettings_Id=@YearSettings_Id

			insert into TA_tbl_HolidayHistory (Holiday_Id,userId,CreatedDate,Type) values(@holi_dayId,@Emp_Id,getdate(),'Insert')
		end
   --Update Mehod
	else if(@Type='U')
		begin
			set @sql ='UPDATE TA_Tbl_Holiday SET Holiday_Type=''' + @HolidayType + ''',Holiday_FromDate='''+cast(@Holiday_FromDate as nvarchar(25))+''',Holiday_ToDate=''' + cast(@Holiday_Todate as nvarchar(25)) + ''',Holiday_Description=N''' + @Holiday_Description + ''', Emp_Id= ''' + cast(@Emp_Id as  nvarchar(25)) + ''', LevelId= ''' + cast(@LevelId as  nvarchar(10)) + '''  WHERE Holiday_Id= ''' + cast(@HolidayId as  nvarchar(25)) + ''' '
			exec(@sql)
			delete from TA_Tbl_HolidayChildTable where Holiday_Id=@HolidayId
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO [TA_Tbl_HolidayChildTable]
			select xm.LevelId,@HolidayId from OPENXML(@Index, '/DocumentElement/TA_Tbl_Holiday_Levels')
			with (LevelId int 'LevelId') as xm
			exec sp_xml_removedocument @Index   

			update TA_tbl_HolidayHistory set userId=@Emp_Id,CreatedDate=GETDATE(),Type='Update' where Holiday_Id=@HolidayId
		end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_InsertImportMasterData]
			@Emp_FirstName nvarchar(50)
           ,@Emp_MiddleName  nvarchar(50)
           ,@Emp_LastName  nvarchar(50)
           ,@Father_Name  nvarchar(50)
           ,@Mother_Name  nvarchar(50)
           ,@DateOfBirth   nvarchar(25)
           ,@DateOfBirth_Record  nvarchar(25)
           ,@Blood_Group  nvarchar(5)
           ,@Email_Id  nvarchar(200)
           ,@Contact_Address  nvarchar(500)
           ,@Permanent_Address  nvarchar(500)
           ,@Phone_Number  nvarchar(50)
           ,@Mobile_Number  nvarchar(50)
           ,@Gender  nvarchar(50)
           ,@Marital_Status  nvarchar(50)
           ,@Nationality  nvarchar(50)
           ,@Religion  nvarchar(50)
           ,@Personal_EmailID  nvarchar(100)
           ,@Passport_No  nvarchar(50)
           ,@Passport_ExpiryDate  nvarchar(50)
           ,@Visa_No  nvarchar(50)
           ,@Visa_ExpiryDate  nvarchar(25)
           ,@Employee_Code  nvarchar(50)
           ,@DateOfJoining  nvarchar(25)
           ,@Qualification_joiningtime  nvarchar(50)
           ,@Qualification_Employement  nvarchar(50)
           ,@OutDoorJob  nvarchar(5)
           ,@CompOff_Eligible  nvarchar(5)
           ,@OT_Eligible  nvarchar(5)
           ,@ESI_Eligible  nvarchar(5)
           ,@PF_Eligible  nvarchar(5)
           ,@Report_Exclude  nvarchar(5)
           ,@Employee_Status  nvarchar(5)
           ,@SwipeCardNo  nvarchar(50)
           ,@IsDeleted  nvarchar(5)
           --Changed the length of below variable. Reason in below condition were used more than the defined length. Due to the data is not saving properly 
           --into database
           ,@Hostel  nvarchar(5)
           ,@Designation  nvarchar(50)
           ,@Grade  nvarchar(50)
		   ,@GradeNo nvarchar(5)
           ,@EmployeeType  nvarchar(50)
           ,@EmployeeCategory  nvarchar(50)
           ,@BasicSalary  nvarchar(50)
           ,@Level1  nvarchar(50)
           ,@Level2  nvarchar(50)
           ,@Level3  nvarchar(50)
           ,@Level4  nvarchar(50)
           ,@Level5  nvarchar(50)
           ,@Level6  nvarchar(50)
           ,@Level7  nvarchar(50)
           ,@Level8  nvarchar(50)
           ,@Level9  nvarchar(50)
           ,@Level10 nvarchar(50)
AS
BEGIN
IF(@BasicSalary='' or @BasicSalary='0')
BEGIN
	set @BasicSalary=1
END
 IF(@Passport_No='')
	BEGIN
		set @Passport_ExpiryDate=null
	END
 IF(@Passport_ExpiryDate='')
 BEGIN
	set @Passport_ExpiryDate=null
 END
	IF(@Visa_No='')
	BEGIN
	set @Visa_ExpiryDate=null
	END
 IF(@Visa_ExpiryDate='')
	BEGIN
	set @Visa_ExpiryDate=null
	END
 IF(@DateOfBirth_Record='')
 BEGIN
	SET @DateOfBirth_Record=NULL
 END

 --adsf
 --asdf

 declare @countDesignation int
 set @countDesignation=(select COUNT(*) from TA_Tbl_Title where TitleName=@Designation)
 IF(@countDesignation<>0)
 begin
	declare @GradeID int
	select @GradeID=GradeID from TA_Tbl_Title where TitleName=@Designation
	select @Grade=Grade_Name from TA_Tbl_Grade where Grade_ID=CONVERT(int,@GradeID)
	select @GradeNo=Grade_Level from TA_Tbl_Grade where Grade_ID=CONVERT(int,@GradeID)
 end
IF(@Employee_Status='')
BEGIN
SET @Employee_Status=1
END
declare @intEmpCount as int
select @intEmpCount=count(*) from Ta_Tbl_ImportMasterData where Employee_Code=@Employee_Code
if(@intEmpCount=0)
Begin
INSERT INTO [Ta_Tbl_ImportMasterData]
           ([Emp_FirstName]
           ,[Emp_MiddleName]
           ,[Emp_LastName]
           ,[Father_Name]
           ,[Mother_Name]
           ,[DateOfBirth]
           ,[DateOfBirth_Record]
           ,[Blood_Group]
           ,[Email_Id]
           ,[Contact_Address]
           ,[Permanent_Address]
           ,[Phone_Number]
           ,[Mobile_Number]
           ,[Gender]
           ,[Marital_Status]
           ,[Nationality]
           ,[Religion]
           ,[Personal_EmailID]
           ,[Passport_No]
           ,[Passport_ExpiryDate]
           ,[Visa_No]
           ,[Visa_ExpiryDate]
           ,[Employee_Code]
           ,[DateOfJoining]
           ,[Qualification_joiningtime]
           ,[Qualification_Employement]
           ,[OutDoorJob]
           ,[CompOff_Eligible]
           ,[OT_Eligible]
           ,[ESI_Eligible]
           ,[PF_Eligible]
           ,[Report_Exclude]
           ,[Employee_Status]
           ,[SwipeCardNo]
           ,[IsDeleted]
           ,[Hostel]
           ,[Designation]
           ,[Grade]
		   ,[GradeNo]
           ,[EmployeeType]
           ,[EmployeeCategory]
           ,[BasicSalary]
           ,[Level1]
           ,[Level2]
           ,[Level3]
           ,[Level4]
           ,[Level5]
           ,[Level6]
           ,[Level7]
           ,[Level8]
           ,[Level9]
           ,[Level10])
     VALUES
		   (@Emp_FirstName
           ,@Emp_MiddleName
           ,@Emp_LastName
           ,@Father_Name
           ,@Mother_Name
           ,@DateOfBirth
           ,@DateOfBirth_Record
           ,@Blood_Group
           ,@Email_Id
           ,@Contact_Address
           ,@Permanent_Address
           ,@Phone_Number
           ,@Mobile_Number
           ,dbo.Func_TA_ProperCase(@Gender)
           ,@Marital_Status
           ,@Nationality
           ,@Religion
           ,@Personal_EmailID
           ,@Passport_No
           ,@Passport_ExpiryDate
           ,@Visa_No
           ,@Visa_ExpiryDate
           ,@Employee_Code
           ,@DateOfJoining
           ,@Qualification_joiningtime
           ,@Qualification_Employement
           ,CASE @OutDoorJob WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @CompOff_Eligible WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @OT_Eligible WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @ESI_Eligible WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @PF_Eligible WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @Report_Exclude WHEN 'TRUE' THEN 1 ELSE 0 END
          -- ,CASE @Employee_Status WHEN 'TRUE' THEN 1 ELSE 0 END employee status not get from user in simple and advanced template so better set as 1
           ,1
		   ,@SwipeCardNo
           ,CASE @IsDeleted WHEN 'TRUE' THEN 1 ELSE 0 END
           ,CASE @Hostel WHEN 'TRUE' THEN 1 ELSE 0 END
           ,@Designation
           ,@Grade
		   ,@GradeNo
           ,@EmployeeType
           ,@EmployeeCategory
           ,@BasicSalary
           ,@Level1
           ,@Level2
           ,@Level3
           ,@Level4
           ,@Level5
           ,@Level6
           ,@Level7
           ,@Level8
           ,@Level9
           ,@Level10)
end
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterDataStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORT
-- Modified Date	:	26-Sep-2013
-- Description		:	To Remove the Grade And GradeNo Parameters.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertImportMasterDataStandard]
			@Emp_FirstName varchar(50)
           ,@Emp_MiddleName  varchar(50)
           ,@Emp_LastName  varchar(50)
           ,@Father_Name  varchar(50)
           ,@Mother_Name  varchar(50)
           ,@DateOfBirth   varchar(25)
           ,@DateOfBirth_Record  varchar(25)
           ,@Blood_Group  varchar(5)
           ,@Email_Id  varchar(200)
           ,@Contact_Address  varchar(500)
           ,@Permanent_Address  varchar(500)
           ,@Phone_Number  varchar(50)
           ,@Mobile_Number  varchar(50)
           ,@Gender  varchar(50)
           ,@Marital_Status  varchar(50)
           ,@Nationality  varchar(50)
           ,@Religion  varchar(50)
           ,@Personal_EmailID  varchar(100)
           ,@Passport_No  varchar(50)
           ,@Passport_ExpiryDate  varchar(50)
           ,@Visa_No  varchar(50)
           ,@Visa_ExpiryDate  varchar(25)
           ,@Employee_Code  varchar(50)
           ,@DateOfJoining  varchar(25)
           ,@Qualification_joiningtime  varchar(50)
           ,@Qualification_Employement  varchar(50)
           ,@OutDoorJob  varchar(1)
           ,@CompOff_Eligible  varchar(1)
           ,@OT_Eligible  varchar(1)
           ,@ESI_Eligible  varchar(50)
           ,@PF_Eligible  varchar(1)
           ,@Report_Exclude  varchar(1)
           ,@Employee_Status  varchar(1)
           ,@SwipeCardNo  varchar(50)
           ,@IsDeleted  varchar(1)
           ,@Hostel  varchar(1)
           ,@Designation  varchar(50)           
           ,@EmployeeType  varchar(50)
           ,@EmployeeCategory  varchar(50)
           ,@BasicSalary  varchar(50)
           ,@Level1  varchar(50)
           ,@Level2  varchar(50)
           ,@Level3  varchar(50)
           ,@Level4  varchar(50)
           ,@Level5  varchar(50)
           ,@Level6  varchar(50)
           ,@Level7  varchar(50)
           ,@Level8  varchar(50)
           ,@Level9  varchar(50)
           ,@Level10 varchar(50)
AS
BEGIN
	IF(@BasicSalary='' or @BasicSalary='0')
		BEGIN
			set @BasicSalary=1
		END
	IF(@Passport_No='')
		BEGIN
			set @Passport_ExpiryDate=null
		END
	IF(@Passport_ExpiryDate='')
		BEGIN
			set @Passport_ExpiryDate=null
		END
	IF(@Visa_No='')
		BEGIN
			set @Visa_ExpiryDate=null
		END
	IF(@Visa_ExpiryDate='')
		BEGIN
			set @Visa_ExpiryDate=null
		END
	IF(@DateOfBirth_Record='')
		BEGIN
			SET @DateOfBirth_Record=NULL
		END
	IF(@Employee_Status='')
		BEGIN
			SET @Employee_Status=1
		END
	declare @intEmpCount as int
	set @intEmpCount=(select count(*) from Ta_Tbl_ImportMasterData where Employee_Code=@Employee_Code)
	if(@intEmpCount=0)
		Begin
			INSERT INTO [Ta_Tbl_ImportMasterData]
           ([Emp_FirstName]
           ,[Emp_MiddleName]
           ,[Emp_LastName]
           ,[Father_Name]
           ,[Mother_Name]
           ,[DateOfBirth]
           ,[DateOfBirth_Record]
           ,[Blood_Group]
           ,[Email_Id]
           ,[Contact_Address]
           ,[Permanent_Address]
           ,[Phone_Number]
           ,[Mobile_Number]
           ,[Gender]
           ,[Marital_Status]
           ,[Nationality]
           ,[Religion]
           ,[Personal_EmailID]
           ,[Passport_No]
           ,[Passport_ExpiryDate]
           ,[Visa_No]
           ,[Visa_ExpiryDate]
           ,[Employee_Code]
           ,[DateOfJoining]
           ,[Qualification_joiningtime]
           ,[Qualification_Employement]
           ,[OutDoorJob]
           ,[CompOff_Eligible]
           ,[OT_Eligible]
           ,[ESI_Eligible]
           ,[PF_Eligible]
           ,[Report_Exclude]
           ,[Employee_Status]
           ,[SwipeCardNo]
           ,[IsDeleted]
           ,[Hostel]
           ,[Designation]
           ,[Grade]
		   ,[GradeNo]
           ,[EmployeeType]
           ,[EmployeeCategory]
           ,[BasicSalary]
           ,[Level1]
           ,[Level2]
           ,[Level3]
           ,[Level4]
           ,[Level5]
           ,[Level6]
           ,[Level7]
           ,[Level8]
           ,[Level9]
           ,[Level10])
     VALUES
		   (@Emp_FirstName
           ,@Emp_MiddleName
           ,@Emp_LastName
           ,@Father_Name
           ,@Mother_Name
           ,@DateOfBirth
           ,@DateOfBirth_Record
           ,@Blood_Group
           ,@Email_Id
           ,@Contact_Address
           ,@Permanent_Address
           ,@Phone_Number
           ,@Mobile_Number
           ,dbo.Func_TA_ProperCase(@Gender)
           ,@Marital_Status
           ,@Nationality
           ,@Religion
           ,@Personal_EmailID
           ,@Passport_No
           ,@Passport_ExpiryDate
           ,@Visa_No
           ,@Visa_ExpiryDate
           ,@Employee_Code
           ,@DateOfJoining
           ,@Qualification_joiningtime
           ,@Qualification_Employement
           ,@OutDoorJob
           ,@CompOff_Eligible
           ,@OT_Eligible
           ,@ESI_Eligible
           ,@PF_Eligible
           ,@Report_Exclude
           ,@Employee_Status
           ,@Employee_Code
           ,@IsDeleted
           ,@Hostel
           ,@Designation
           ,0
		   ,0
           ,@EmployeeType
           ,@EmployeeCategory
           ,@BasicSalary
           ,@Level1
           ,@Level2
           ,@Level3
           ,@Level4
           ,@Level5
           ,@Level6
           ,@Level7
           ,@Level8
           ,@Level9,
           @Level10)
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertInAndOutPunchDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Inserting clock details>
-- Modified by manikandan
-- Need to share this procedure to client upto 2.4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertInAndOutPunchDetails]
	@gstrCompanyId varchar(20),
	@inClk_EmpId varchar(50),
	@inClk_DeviceId varchar(50),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20),
	@inPunchType varchar(20),
	@gstrClockDate varchar(20),
	@inClk_Remarks varchar(max),
	@inClk_User varchar(20),
	@inClk_Status varchar(20),
	@Type char(2),
	@PunchType_Remarks varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type='I')
    begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status) 
		VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status)
	end
	else if(@Type='O')
	begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Date,Clk_Remarks,
		Clk_User,Clk_Status,PunchType_Remarks)
		VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,@PunchType_Remarks)		
	end
	else if(@Type='IV')
	begin
		 INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status,IsVoid) 
		 --Modified below line
		 VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,1)
	end
	else if(@Type='OV')
	begin
		 INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status,IsVoid)
		 --Modified below line
		 VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,1)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertInDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Inserting in and out punch details to clock details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertInDetailsForService]
	-- Add the parameters for the stored procedure here	
	@gstrCompanyId varchar(30),
	@inClk_EmpId varchar(30), 
	@inClk_DeviceId varchar(30),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20), 
	@inPunchType varchar(30),
	@gstrClockDate varchar(20),
	@inClk_Remarks varchar(max), 
	@inClk_User varchar(30), 
	@inClk_Status varchar(10),
	@PunchType_Remarks varchar(max),
	@Type char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if(@Type='I')
    begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,
		Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status) VALUES(@gstrCompanyId,@inClk_EmpId,
		@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status)
	end
	if(@Type='O')
	begin
		INSERT INTO TA_Tbl_ClockDetails (Clk_CompId,Clk_EmpId, Clk_OutDeviceId,Clk_OutDate, Clk_OutTime, Clk_OutPunchType,
		Clk_Process, Clk_Date,Clk_Remarks,Clk_User,Clk_Status,PunchType_Remarks)VALUES(@gstrCompanyId,@inClk_EmpId,
		@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,'N',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,@PunchType_Remarks)		
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveAnalysisNotes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveAnalysisNotes]
@Notes as varchar(8000),
@iDate as datetime,
@EmpID as int
AS
BEGIN
SET NOCOUNT ON;
	Insert into TA_Tbl_LeaveAnalysisNotes (
			Notes,
			DateInserted,
			EmpID
			)
	Values
		(
			@Notes,
			@iDate,
			@EmpID
		)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Proc_TA_GetCompOffDays 10860,2
Description		:	Insert into Leave Appliacation for Employee
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting, TA_Tbl_OverTimeStatus
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	A.K.T.MOORTHI
Modified On		:	23-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
Modifed by Gopinath for removing the lines added for Globalweekoff days due to V1.5 release


exec Proc_TA_InsertLeaveApplication @EmployeeID=6,@Leave_ApplicationDate='2024-09-24 10:59:00',@LeaveType_id=1,@Type=N'Leave',@Leave_FromDate='2024-09-23 00:00:00',
@Leave_ToDate='2024-09-23 00:00:00',@Leave_SessionFrom=N'First half',@Leave_SessionTo=N'Second half',@NumberOfDays=1.00,@Reason=N'ok',
@IsBorrow=0,@auEmpId=N'1',@YearSettings_Id=N'2',@LeaveStatus=N'Forwarded',@SuccessiveYear=0,@Intervening='',@isCalendar=0


*/


CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication](
	@EmployeeID INT,
	@Leave_ApplicationDate DATETIME=null,
	@LeaveType_id INT,
	@Type NVARCHAR(20),
	@Leave_FromDate DATETIME,
	@Leave_ToDate DATETIME,
	@Leave_SessionFrom NVARCHAR(20),
	@Leave_SessionTo NVARCHAR(20),
	@NumberOfDays DECIMAL(8,2),
	@Reason NVARCHAR(250),
	@IsBorrow INT,
	@auEmpId NVARCHAR(50),
	@YearSettings_Id NVARCHAR(20),
	@LeaveStatus NVARCHAR(30),
	@SuccessiveYear INT,
	@Intervening char(5),
	@isCalendar int=0
	
) 
AS
BEGIN
	SET NOCOUNT ON;
	declare @MCFilepath NVARCHAR(200)
	DECLARE @LevelId INT
	declare @CountRecord INT
	declare @LeaveApplicationId INT
	DECLARE @Isdeleted BIT 
	set @Isdeleted= 0
	declare @del BIT 
	set @del= 0
	DECLARE @SQLQuery NVARCHAR(MAX) 
	set @SQLQuery= ''
	SELECT @LevelId = LevelId FROM TA_Tbl_EmployeeLevel WHERE EmployeeId = @EmployeeID
	WHILE((SELECT id FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> '')
	BEGIN 	
		IF((SELECT levelId FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> 1)
		BEGIN
			SELECT @LevelId = parentId FROM Ta_Tbl_levelDetails WHERE id = @LevelId
		END
		ELSE
		BEGIN
			BREAK
		END
	END
	SET @LevelId = @LevelId
	SELECT @CountRecord = count(Employee_Id) FROM TA_Tbl_Employee 
		WHERE Leave_Sanc_Authority = Reporting_To AND Employee_Id = @EmployeeID  
	IF(@LeaveStatus = '' AND @CountRecord > 0)
	BEGIN
		SET @LeaveStatus = 'Forwarded'
	END
	ELSE IF(@LeaveStatus = '' AND @CountRecord = 0)
	BEGIN
		SET @LeaveStatus = 'Pending'
	END	
	INSERT INTO TA_Tbl_LeaveApplication(Employee_Id, Leave_ApplicationDate, LeaveType_id, Type, Leave_FromDate, Leave_ToDate, Leave_SessionFrom, Leave_SessionTo, NumberOfDays, Reason, Status, IsDeleted, IsBorrow, Emp_Id, YearSettings_Id, CompanyId, Successiveyear,Intervening,MCFilePath,isCalanderflag)
	VALUES(CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
	CAST(@LeaveType_id AS NVARCHAR(20)), @Type,CAST(@Leave_FromDate AS NVARCHAR(20)),
	CAST(@Leave_ToDate AS NVARCHAR(20)), @Leave_SessionFrom,@Leave_SessionTo,
	CAST(@NumberOfDays AS NVARCHAR(20)), @Reason,@LeaveStatus,CAST(@Isdeleted AS NVARCHAR(10)),
	CAST(@IsBorrow AS NVARCHAR(10)),@auEmpId,@YearSettings_Id,CAST(@LevelId AS NVARCHAR(20)),
	CAST(@SuccessiveYear AS NVARCHAR(20)),@Intervening,@MCFilepath,@isCalendar)
	
	SET @LeaveApplicationId = IDENT_CURRENT('TA_Tbl_LeaveApplication')
	Declare @diff int
	declare @i int
	declare @fromdate datetime
	declare @Todate datetime
	declare @fromsession varchar(20)
	declare @tosession varchar(20)
	set @i=0
	set @fromdate=@Leave_FromDate 
	set @Todate=@Leave_ToDate	
	set @diff=(select DATEDIFF(d,@Leave_FromDate,@Leave_ToDate))
	if(@diff=0)
		begin
			insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
			CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),@Leave_SessionFrom , @Leave_SessionTo,@LeaveStatus,@Isdeleted) 
		END
	ELSE
		BEGIN			 
			WHILE @i<=@diff 
				BEGIN
					IF @fromdate=@Todate
						BEGIN
							IF(@Leave_SessionTo='Second half')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted) 		
								end
							if(@Leave_SessionTo='First half')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),'First half' , 'First half',@LeaveStatus,@Isdeleted) 		
								end
						end
					else if @fromdate=@Leave_FromDate 
						begin
							if(@Leave_SessionFrom='Second half')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),'Second half' , 'Second half',@LeaveStatus,@Isdeleted) 		
								end
							if(@Leave_SessionFrom='First half')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(getdate() AS NVARCHAR(20)),
									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted) 		
								end
							--end								
						end	
					else
						begin
							insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
							CAST(@fromdate AS NVARCHAR(20)),CAST(@fromdate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted)
						end				
					set @fromdate=DATEADD(d,1,@fromdate)					
					set @i=@i+1					
				end
		end
	IF(@Type= 'Comp Off')
	BEGIN
		DECLARE @CompOffId BIGINT 
		set @CompOffId= 0
		Declare @RemainingDays NUMERIC(18,1) 
		set @RemainingDays= 0.0
		DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
		UPDATE TA_Tbl_OverTimeStatus SET CompOffSatus = 'Expired'
		WHERE DateToExpired < GETDATE() AND
			ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
			OverTimeStatus = 'Approved' AND
			CompOffEligible = 1 AND
			Employee_Id = @EmployeeId
		INSERT INTO @TblRecord
			SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE DateToExpired >= GETDATE() AND
				ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
				OverTimeStatus = 'Approved' AND
				CompOffEligible = 1 AND
				Employee_Id = @EmployeeId
			ORDER BY Date
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN 0.0 END),
				CompOffSatus = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN 'Not Taken'
					WHEN (@RemainingDays <= @NumberOfDays) THEN 'Taken' END),
				LeaveApplicationId = ISNULL(LeaveApplicationId, '') + ':' + CAST(@LeaveApplicationId AS VARCHAR(20))
			WHERE ExtraTime_Id = @CompOffId
			SET @NumberOfDays = (@NumberOfDays - @RemainingDays)
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
	END
	declare @LeaveID as int
	set @LeaveID=(select LevelId from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID and EffectiveDate in (select MAX(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID))
	SELECT @LeaveApplicationId AS [LeaveApplicationId],@LeaveStatus as [LeaveApplicationStatus],@LeaveID as LevelID
	If ((@LeaveStatus='Forwarded' or @LeaveStatus='Approved') and @EmployeeID!=@auEmpId)
	begin
		Execute [Proc_TA_UpdateLeaveApplicationConversation] @LeaveApplicationId,@LeaveStatus,@auEmpId,'Ok',@auEmpId,@Leave_ApplicationDate
	End
END











--ALTER PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication](
--	@EmployeeID INT,
--	@Leave_ApplicationDate DATETIME=null,
--	@LeaveType_id INT,
--	@Type NVARCHAR(20),
--	@Leave_FromDate DATETIME,
--	@Leave_ToDate DATETIME,
--	@Leave_SessionFrom NVARCHAR(20),
--	@Leave_SessionTo NVARCHAR(20),
--	@NumberOfDays DECIMAL(8,2),
--	@Reason NVARCHAR(250),
--	@IsBorrow INT,
--	@auEmpId NVARCHAR(50),
--	@YearSettings_Id NVARCHAR(20),
--	@LeaveStatus NVARCHAR(30),
--	@SuccessiveYear INT,
--	@Intervening char(5),
--	@isCalendar int=0
	
--) 
--AS
--BEGIN
--	SET NOCOUNT ON;
--	declare @MCFilepath NVARCHAR(200)
--	DECLARE @LevelId INT
--	declare @CountRecord INT
--	declare @LeaveApplicationId INT
--	DECLARE @Isdeleted BIT 
	
--	set @Isdeleted= 0
--	declare @del BIT 
--	set @del= 0
--	-- Mariaprasanth Include this Variable to Convert the Timezone GetDatetime on 06-Jan-2024 
--	Declare @getTimezoneDT DateTime
--	set @getTimezoneDT=dbo.GetUTCTimeZoneDateTime(@EmployeeID)


--	DECLARE @SQLQuery NVARCHAR(MAX) 
--	set @SQLQuery= ''
--	SELECT @LevelId = LevelId FROM TA_Tbl_EmployeeLevel WHERE EmployeeId = @EmployeeID
--	WHILE((SELECT id FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> '')
--	BEGIN 	
--		IF((SELECT levelId FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> 1)
--		BEGIN
--			SELECT @LevelId = parentId FROM Ta_Tbl_levelDetails WHERE id = @LevelId
--		END
--		ELSE
--		BEGIN
--			BREAK
--		END
--	END
--	SET @LevelId = @LevelId
--	SELECT @CountRecord = count(Employee_Id) FROM TA_Tbl_Employee 
--		WHERE Leave_Sanc_Authority = Reporting_To AND Employee_Id = @EmployeeID  
--	IF(@LeaveStatus = '' AND @CountRecord > 0)
--	BEGIN
--		SET @LeaveStatus = 'Forwarded'
--	END
--	ELSE IF(@LeaveStatus = '' AND @CountRecord = 0)
--	BEGIN
--		SET @LeaveStatus = 'Pending'
--	END	
--	--INSERT INTO TA_Tbl_LeaveApplication(Employee_Id, Leave_ApplicationDate, LeaveType_id, Type, Leave_FromDate, Leave_ToDate, Leave_SessionFrom, Leave_SessionTo, NumberOfDays, Reason, Status, IsDeleted, IsBorrow, Emp_Id, YearSettings_Id, CompanyId, Successiveyear,Intervening,MCFilePath,isCalanderflag)
--	--VALUES(CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
--	--CAST(@LeaveType_id AS NVARCHAR(20)), @Type,CAST(@Leave_FromDate AS NVARCHAR(20)),
--	--CAST(@Leave_ToDate AS NVARCHAR(20)), @Leave_SessionFrom,@Leave_SessionTo,
--	--CAST(@NumberOfDays AS NVARCHAR(20)), @Reason,@LeaveStatus,CAST(@Isdeleted AS NVARCHAR(10)),
--	--CAST(@IsBorrow AS NVARCHAR(10)),@auEmpId,@YearSettings_Id,CAST(@LevelId AS NVARCHAR(20)),
--	--CAST(@SuccessiveYear AS NVARCHAR(20)),@Intervening,@MCFilepath,@isCalendar)

--		INSERT INTO TA_Tbl_LeaveApplication(Employee_Id, Leave_ApplicationDate, LeaveType_id, Type, Leave_FromDate, Leave_ToDate, Leave_SessionFrom, Leave_SessionTo, NumberOfDays, Reason, Status, IsDeleted, IsBorrow, Emp_Id, YearSettings_Id, CompanyId, Successiveyear,Intervening,MCFilePath,isCalanderflag)
--	VALUES(CAST(@EmployeeID AS NVARCHAR(20)),Cast(@getTimezoneDT As nvarchar(20)),
--	CAST(@LeaveType_id AS NVARCHAR(20)), @Type,CAST(@Leave_FromDate AS NVARCHAR(20)),
--	CAST(@Leave_ToDate AS NVARCHAR(20)), @Leave_SessionFrom,@Leave_SessionTo,
--	CAST(@NumberOfDays AS NVARCHAR(20)), @Reason,@LeaveStatus,CAST(@Isdeleted AS NVARCHAR(10)),
--	CAST(@IsBorrow AS NVARCHAR(10)),@auEmpId,@YearSettings_Id,CAST(@LevelId AS NVARCHAR(20)),
--	CAST(@SuccessiveYear AS NVARCHAR(20)),@Intervening,@MCFilepath,@isCalendar)

	
	
--	SET @LeaveApplicationId = IDENT_CURRENT('TA_Tbl_LeaveApplication')
--	Declare @diff int
--	declare @i int
--	declare @fromdate datetime
--	declare @Todate datetime
--	--declare @fromsession varchar(20)='0'
--	--declare @tosession varchar(20)
--	set @i=0
--	set @fromdate=@Leave_FromDate 
--	set @Todate=@Leave_ToDate	
--	set @diff=(select DATEDIFF(d,@Leave_FromDate,@Leave_ToDate))
--	if(@diff=0)
--		begin
--			--insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
--			--CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),@Leave_SessionFrom , @Leave_SessionTo,@LeaveStatus,@Isdeleted) 
--			--Select * from TA_Tbl_LeaveApplicationExists

--			insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),GETDATE(),--CAST(@getTimezoneDT AS NVARCHAR(20)),
--			CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),@Leave_SessionFrom , @Leave_SessionTo,@LeaveStatus,@Isdeleted)
--		END
--	ELSE
--		BEGIN			 
--			WHILE @i<=@diff 
--				BEGIN
--					IF @fromdate=@Todate
--						BEGIN
--							IF(@Leave_SessionTo='Second half')
--								begin
--									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),GETDATE(),--CAST(@getTimezoneDT AS NVARCHAR(20)),
--									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted) 		
--								end
--							if(@Leave_SessionTo='First half')
--								begin
--									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),GETDATE(),--CAST(@getTimezoneDT AS NVARCHAR(20)),
--									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),'First half' , 'First half',@LeaveStatus,@Isdeleted) 		
--								end
--						end
--					else if @fromdate=@Leave_FromDate 
--						begin
--							if(@Leave_SessionFrom='Second half')
--								begin
--									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),GETDATE(),--CAST(@getTimezoneDT AS NVARCHAR(20)),
--									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),'Second half' , 'Second half',@LeaveStatus,@Isdeleted) 		
--								end
--							if(@Leave_SessionFrom='First half')
--								begin
--									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),GETDATE(),--CAST(@getTimezoneDT AS NVARCHAR(20)),
--									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted) 		
--								end
--							--end								
--						end	
--					else
--						begin
--							insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(@getTimezoneDT AS NVARCHAR(20)),
--							CAST(@fromdate AS NVARCHAR(20)),CAST(@fromdate AS NVARCHAR(20)),'First half' , 'Second half',@LeaveStatus,@Isdeleted)
--						end				
--					set @fromdate=DATEADD(d,1,@fromdate)					
--					set @i=@i+1					
--				end
--		end
--	IF(@Type= 'Comp Off')
--	BEGIN
--		DECLARE @CompOffId BIGINT 
--		set @CompOffId= 0
--		Declare @RemainingDays NUMERIC(18,1) 
--		set @RemainingDays= 0.0
--		DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
--		UPDATE TA_Tbl_OverTimeStatus SET CompOffSatus = 'Expired'
--		WHERE DateToExpired < GETDATE() AND
--			ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
--			OverTimeStatus = 'Approved' AND
--			CompOffEligible = 1 AND
--			Employee_Id = @EmployeeId
--		INSERT INTO @TblRecord
--			SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
--			WHERE DateToExpired >= GETDATE() AND
--				ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
--				OverTimeStatus = 'Approved' AND
--				CompOffEligible = 1 AND
--				Employee_Id = @EmployeeId
--			ORDER BY Date
--		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
--		BEGIN
--			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
--			UPDATE TA_Tbl_OverTimeStatus SET
--				@RemainingDays = RemainingDays,
--				RemainingDays = (CASE 
--					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
--					WHEN (@RemainingDays <= @NumberOfDays) THEN 0.0 END),
--				CompOffSatus = (CASE 
--					WHEN (@RemainingDays > @NumberOfDays) THEN 'Not Taken'
--					WHEN (@RemainingDays <= @NumberOfDays) THEN 'Taken' END),
--				LeaveApplicationId = ISNULL(LeaveApplicationId, '') + ':' + CAST(@LeaveApplicationId AS VARCHAR(20))
--			WHERE ExtraTime_Id = @CompOffId
--			SET @NumberOfDays = (@NumberOfDays - @RemainingDays)
--			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
--		END
--	END
--	declare @LeaveID as int
--	set @LeaveID=(select LevelId from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID and EffectiveDate in (select MAX(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID))
--	SELECT @LeaveApplicationId AS [LeaveApplicationId],@LeaveStatus as [LeaveApplicationStatus],@LeaveID as LevelID
--	If ((@LeaveStatus='Forwarded' or @LeaveStatus='Approved') and @EmployeeID!=@auEmpId)
--	begin
--		Declare @getTimezone nvarchar(100)
--		set @getTimezoneDT=dbo.GetUTCTimeZoneDateTime(@EmployeeID)
--		set @getTimezone=Cast (@getTimezoneDT as nvarchar(100))
--		Execute [Proc_TA_UpdateLeaveApplicationConversation] @LeaveApplicationId,@LeaveStatus,@auEmpId,'Ok',@auEmpId,@getTimezone
--	End
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_InsertLeaveApplication  '5','03/17/2008','52','Leave','03/17/2008','03/17/2008','First Session','Second Session',1.0,'TEst Reason',0,6,''
--exec Proc_TA_InsertLeaveApplication @leaveApplicationId=628,@EmployeeID=35,@Leave_ApplicationDate='2013-07-02 00:00:00',@LeaveType_id=1,@Type=N'Leave',@Leave_FromDate='2013-07-05 00:00:00',@Leave_ToDate='2013-07-05 00:00:00',@Leave_SessionFrom=N'First Half',@Leave_SessionTo=N'Second Half',@NumberOfDays=1.00,@Reason=N'Test Chennai....',@IsBorrow=0,@auEmpId=N'1',@YearSettings_Id=N'6',@LeaveStatus=N'',@intimationType=N'P',@CCMail='',@InformTo=''
CREATE     PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication_Angler]  
(
  --Proc_TA_InsertLeaveApplication  '','','','صباح','','','صerبewrاح','صباewrحrewr',1.0,'صبerاح'
@leaveApplicationId int,
@EmployeeID int,
@Leave_ApplicationDate datetime,
@LeaveType_id int,
@Type nvarchar(20),
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@Leave_SessionFrom nvarchar(20),
@Leave_SessionTo nvarchar(20),
@NumberOfDays decimal(8,2),
@Reason nvarchar(1050),
@IsBorrow int,
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@InformTo VARCHAR(MAX) = NULL
)  
as  
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF(@intimationType != 'UP-WI')
BEGIN
	SET @InformTo = NULL
END
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Leave_ToDate as nvarchar(50)), 102) and EL.LevelId is not null
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @CountRecord as int  
set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID)  
declare @sql nvarchar(2000)
set @sql=''
	begin
		if(@LeaveStatus='' and @CountRecord>0)
			BEGIN
			set @LeaveStatus='Forwarded'
			END
		else if (@LeaveStatus='' and @CountRecord=0)
			BEGIN
			set @LeaveStatus='Pending'
			END
	--Insert Method  
	begin  
if(@LeaveStatus!='Reply')
BEGIN
		set @sql= @sql + 'INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Reason,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)'
		set @sql= @sql + 'VALUES(''' + cast(@leaveApplicationId as nvarchar(20)) + ''',''' + cast(@EmployeeID as nvarchar(20)) + ''',''' + cast(@Leave_ApplicationDate as nvarchar(20)) + ''','''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + ''',N''' + @Type + ''',''' + cast(@Leave_FromDate as nvarchar(20))+ ''','''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ ''',N''' + @Leave_SessionFrom + ''',N''' + @Leave_SessionTo + ''',''' + cast(@NumberOfDays as nvarchar(20)) + ''',N'''
		set @sql= @sql + @Reason + ''',N''' + @LeaveStatus + ''',''' + cast(@Isdeleted as nvarchar(10)) +  ''',''' + cast(@IsBorrow as nvarchar(10)) +  ''',N''' + @auEmpId + ''',N''' + @YearSettings_Id + ''',N''' + @intimationType + ''', ''' + ISNULL(@InformTo, '') + ''')'
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplicationMaster set Status=@LeaveStatus,IntimationType=@intimationType,Emp_Id=@auEmpId,CCMail=@CCMail where LeaveApplication_Id=@leaveApplicationId
END
else
BEGIN
set @sql= @sql + 'INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)'
		set @sql= @sql + 'VALUES(''' + cast(@leaveApplicationId as nvarchar(20)) + ''',''' + cast(@EmployeeID as nvarchar(20)) + ''',''' + cast(@Leave_ApplicationDate as nvarchar(20)) + ''','''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + ''',N''' + @Type + ''',''' + cast(@Leave_FromDate as nvarchar(20))+ ''','''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ ''',N''' + @Leave_SessionFrom + ''',N''' + @Leave_SessionTo + ''',''' + cast(@NumberOfDays as nvarchar(20)) + ''',N'''
		set @sql= @sql + @LeaveStatus + ''',''' + cast(@Isdeleted as nvarchar(10)) +  ''',''' + cast(@IsBorrow as nvarchar(10)) +  ''',N''' + @auEmpId + ''',N''' + @YearSettings_Id + ''',N''' + @intimationType + ''', ''' + ISNULL(@InformTo, '') + ''')'
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplication set Reason=t2.Reason
		from TA_Tbl_LeaveApplicationMaster t2
		inner join TA_Tbl_LeaveApplication t1 on t2.LeaveApplication_Id=t1.LeaveApplication_Id
		UPDATE TA_Tbl_LeaveApplicationMaster set Status=@LeaveStatus,IntimationType=@intimationType,Emp_Id=@auEmpId,CCMail=@CCMail where LeaveApplication_Id=@leaveApplicationId
END
        SELECT LA.LeaveApplication_Id, LD.Id AS LevelId FROM TA_Tbl_LeaveApplication LA
        INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = LA.Employee_Id
		INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
        INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
        WHERE LA.LeaveApplication_Id = @leaveApplicationId
	end
	end
	--Remove the temporary tables here  
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_InsertLeaveApplication  '5','03/17/2008','52','Leave','03/17/2008','03/17/2008','First Session','Second Session',1.0,'TEst Reason',0,6,''
CREATE     PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]  
(
@leaveApplicationId int,
@EmployeeID int,
@Leave_ApplicationDate datetime,
@LeaveType_id int,
@Type nvarchar(20),
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@Leave_SessionFrom nvarchar(20),
@Leave_SessionTo nvarchar(20),
@NumberOfDays decimal(8,2),
@Reason nvarchar(1050),
@IsBorrow int,
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@InformTo VARCHAR(MAX)
)  
as  
BEGIN
SET NOCOUNT ON;
IF(@intimationType != 'UP-WI')
BEGIN
	SET @InformTo = NULL
END
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Leave_ToDate as nvarchar(50)), 102) and EL.LevelId is not null
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @sql nvarchar(2000)
set @sql=''
set @sql= @sql + 'INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)'
		set @sql= @sql + 'VALUES(''' + cast(@leaveApplicationId as nvarchar(20)) + ''',''' + cast(@EmployeeID as nvarchar(20)) + ''',''' + cast(@Leave_ApplicationDate as nvarchar(20)) + ''','''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + ''',N''' + @Type + ''',''' + cast(@Leave_FromDate as nvarchar(20))+ ''','''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ ''',N''' + @Leave_SessionFrom + ''',N''' + @Leave_SessionTo + ''',''' + cast(@NumberOfDays as nvarchar(20)) + ''',N'''
		set @sql= @sql + @LeaveStatus + ''',''' + cast(@Isdeleted as nvarchar(10)) +  ''',''' + cast(@IsBorrow as nvarchar(10)) +  ''',N''' + @auEmpId + ''',N''' + @YearSettings_Id + ''',N''' + @intimationType + ''', ''' + ISNULL(@InformTo, '') + ''')'
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplication set Reason=t2.Reason
		from TA_Tbl_LeaveApplicationMaster t2
		inner join TA_Tbl_LeaveApplication t1 on t2.LeaveApplication_Id=t1.LeaveApplication_Id
		where t2.LeaveApplication_Id=@leaveApplicationId
        SELECT LA.LeaveApplication_Id, LD.Id AS LevelId FROM TA_Tbl_LeaveApplication LA
        INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = LA.Employee_Id
		INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
        INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
        WHERE LA.LeaveApplication_Id = @leaveApplicationId
		--update the processflag
		update Ta_Tbl_ProcessedData set processflag=0
		from Ta_Tbl_LeaveApplication t2
		inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
		inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
		t1.date between t2.Leave_FromDate and t2.Leave_ToDate
		where t2.LeaveApplication_Id=@leaveApplicationId
		declare @intEmployeeId as int
		set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@leaveApplicationId)
		--Update year closure
		update ta_tbl_yearclosure set Leave_Taken=
		(select isnull(sum(NumberOfDays),0.0)
		from Ta_Tbl_LeaveApplication
		inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
		where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
		and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
		and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
		and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status='Approved'
		and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId
		)	
	--Remove the temporary tables here  
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.MANIKANDAN
-- Create date: 04-02-2013
-- Description:	Inserting the Leave and Permission details to emailTriggering Table
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]
	-- Add the parameters for the stored procedure here
	@LeaveApplicationId bigint,
	@FromEmailID nvarchar(max),
	@ToEmailId nvarchar(max),
	@CCEmailid nvarchar(max),
	@Subjects nvarchar(max),
	@BodyContent nvarchar(max),
	@Attachment nvarchar(max),
	@AraisedFrom nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO Ta_tbl_EmailReportNotSendedDetails values(@LeaveApplicationId,@FromEmailID,@ToEmailId,@CCEmailid,@Subjects,@BodyContent,@Attachment,@AraisedFrom)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_InsertLeaveApplicationMaster  '5','03/17/2008','52','Leave','03/17/2008','03/17/2008','First Session','Second Session',1.0,'TEst Reason',0,6,''
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationMaster]  
(
@EmployeeID int,
@Leave_ApplicationDate datetime,
@Reason nvarchar(1050),
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@LeaveAvailedYear decimal(18,1),
@LeaveAvailedMonth decimal(18,1)
)  
as  
BEGIN
SET NOCOUNT ON;
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @CountRecord as int  
set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID)  
declare @sql nvarchar(3000)
set @sql=''
begin
		if(@LeaveStatus='' and @CountRecord>0)
			BEGIN
			set @LeaveStatus='Forwarded'
			END
		else if (@LeaveStatus='' and @CountRecord=0)
			BEGIN
			set @LeaveStatus='Pending'
			END
--Insert Method  
	begin  
		set @sql= @sql + 'INSERT INTO TA_Tbl_LeaveApplicationMaster(Employee_Id,Leave_ApplicationDate,Reason,Status,IsDeleted,Emp_Id,YearSettings_Id,IntimationType,CCMail,LeaveAvailedYear,LeaveAvailedMonth)'
		set @sql= @sql + 'VALUES(''' + cast(@EmployeeID as nvarchar(20)) + ''',''' + cast(@Leave_ApplicationDate as nvarchar(20)) + ''','''
		set @sql= @sql + @Reason + ''',N''' + @LeaveStatus + ''',''' + cast(@Isdeleted as nvarchar(10)) +  ''',N''' + @auEmpId + ''',N''' + @YearSettings_Id + ''',N''' + @intimationType + ''',''' + @CCMail + ''',''' + cast(@LeaveAvailedYear as nvarchar(20)) + ''',''' + cast(@LeaveAvailedMonth as nvarchar(20)) +''')'
		exec(@sql)
      SELECT @@IDENTITY AS LeaveApplication_Id
	end
end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author				:	Arun vinoth
-- ALTER  date		:	28 June 2007
-- Description		:	Leave policy - Insert
--Modified By		:	Manikandan.R
--Modified Date		:	15-10-2011
--Modified By		:	A.K.T.MOORTHI
--Modified Date		:	31-Dec-2013
-- Description		:	Add the Halfdaycompoff, VaildDays Column for insert and update query.
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_TA_InsertLeavePolicy] 
	@Type CHAR(1)='',
	@Policy_Id INT=0,
	@PolicyName NVARCHAR(50)='',
	@Permission_MaxHrs_Month NVARCHAR(5)='',
	@Permission_MaxInstances_Month INT=0,
	@Permission_MaxHrs_Instance NVARCHAR(5)='',
	@Employee_Id INT,
	@PermissionBeforeLeave INT, 
	@PermissionAfterLeave INT,
	@OtHourWise INT,
 	@OtDayWise INT,
	@OtMinHrs VARCHAR(20),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@Gender VARCHAR(10),
	@Religion INT,
	@HalfDayCompOff VARCHAR(5),
	@VaildDays INT,
	@companyID int,
	@Per_MinHrs_Instance NVARCHAR(5)
AS	
BEGIN
	SET NOCOUNT ON;
	DECLARE @IsDeleted BIT
	SET @IsDeleted=0
	IF (@Type='I')
	BEGIN 
		INSERT INTO TA_Tbl_LeavePolicy (PolicyName, Permission_MaxHrs_Month, Permission_MaxInstances_Month, Permission_MaxHrs_Instance, IsDeleted, Emp_Id, PermissionBeforeLeave, PermissionAfterLeave, OtHourWise, OtDayWise, OtMinHrs, EmployeeCategory, EmployeeType, Gender, Religion, FullDayOTMinHrs, CompOffValidDays,companyID,Permission_MinHrs_Instance)
		VALUES (@PolicyName, @Permission_MaxHrs_Month, @Permission_MaxInstances_Month, @Permission_MaxHrs_Instance, @IsDeleted, @Employee_Id, @PermissionBeforeLeave, @PermissionAfterLeave, @OtHourWise, @OtDayWise, @HalfDayCompOff, @EmployeeCategory, @EmployeeType, @Gender, @Religion, @OtMinHrs, @VaildDays,@companyID,@Per_MinHrs_Instance)
	END
	ELSE IF (@Type='U')
	BEGIN
		UPDATE TA_Tbl_LeavePolicy SET 
			PolicyName = @PolicyName,
			Permission_MaxHrs_Month = @Permission_MaxHrs_Month,
			Permission_MaxInstances_Month = @Permission_MaxInstances_Month,
			Permission_MaxHrs_Instance = @Permission_MaxHrs_Instance,
			IsDeleted=@IsDeleted,
			Emp_Id=@Employee_Id,
			Time_Stamp=getdate(),
			PermissionBeforeLeave = @PermissionBeforeLeave,
			PermissionAfterLeave = @PermissionAfterLeave,
			OtHourWise = @OtHourWise,
			OtDayWise = @OtDayWise,
			OtMinHrs = @HalfDayCompOff,
			EmployeeCategory = @EmployeeCategory,
			EmployeeType = @EmployeeType,
			Gender = @Gender,
			Religion = @Religion,
			FullDayOTMinHrs = @OtMinHrs,
			CompOffValidDays = @VaildDays,
			companyID=@companyID,
			Permission_MinHrs_Instance=@Per_MinHrs_Instance
		WHERE  Policy_Id = @Policy_Id
	END
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- ALTER  date: 13 Jan 2010
-- Description:	Leave Policy details Insert
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeavePolicyDetails]
	-- Add the parameters for the stored procedure here
		@Policy_Id INT,
		@LeaveType_Id INT,
		@MaxDays_applicable FLOAT=0,
        @MaxDaysPerMonth FLOAT=0,
		@MaxDays_avail FLOAT=0,
		@MinDays_avail FLOAT=0,
		@Spells INT,
		@MaxDays_Acc FLOAT=0,
		@LossOfPay BIT,
		@Max_LOP_Days FLOAT=0,
		@Count_BeforeWeeklyOff BIT,
		@Count_AfterWeeklyOff BIT,
		@Count_Intervening BIT,
		@Borrow_FromNextYear BIT,
		@Carry_ToNextYear BIT,
		@Encashment BIT,
		@Calc_Factor FLOAT=0,
		@MinWorkDays FLOAT=0,
		@WeekDays BIT,
		@WeekOff BIT,
		@Leave BIT,
		@Holidays BIT,
		@ApplicableAfterDays FLOAT,
		@Employee_Id INT,
		@AvailServicePeriod int
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TA_Tbl_LeavePolicyDetails (Policy_Id,LeaveType_Id,MaxDays_applicable,MaxDays_Month,MaxDays_avail,MinDays_avail,Spells,MaxDays_Acc,LossOfPay,Max_LOP_Days,Count_BeforeWeeklyOff,Count_AfterWeeklyOff,Count_Intervening,Borrow_FromNextYear,Carry_ToNextYear,Encashment,Calc_Factor,MinWorkDays,WeekDays,WeekOff,Leave,Holidays,ApplicableAfterDays,Emp_Id,AvailServicePeriod)
	VALUES (@Policy_Id,@LeaveType_Id,@MaxDays_applicable,@MaxDaysPerMonth,@MaxDays_avail,@MinDays_avail,@Spells,@MaxDays_Acc,@LossOfPay,@Max_LOP_Days,@Count_BeforeWeeklyOff,@Count_AfterWeeklyOff,@Count_Intervening,@Borrow_FromNextYear,@Carry_ToNextYear,@Encashment,@Calc_Factor,@MinWorkDays,@WeekDays,@WeekOff,@Leave,@Holidays,@ApplicableAfterDays,@Employee_Id,@AvailServicePeriod)
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLevelWiseRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		senthil
-- Create date: 23-Aug-08
-- Description:	Insert/update levelwise rights
--Proc_TA_InsertLevelWiseRights 8,'47,3,2,1,113,3,2,1'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLevelWiseRights]
	@GroupId as int,
	@LevelID as nvarchar(3000),
	@empid as nvarchar(30)
AS
BEGIN
	declare @Query as varchar(7000)
	declare @RecCount as int
	set @RecCount = (select count(*) from TA_Tbl_LevelRights where groupID = @GroupID)
	if (@RecCount>0)
		Begin
				set @Query = 'update TA_TBL_LevelRights set LevelID=''' + @LevelID + ''', emp_id = ''' + @empid + ''' where GroupID= ' + cast (@GroupID as nvarchar(100))
		End
	Else
		Begin
				set @Query = 'insert into TA_Tbl_LevelRights (GroupID, LevelID,emp_id) values (' + cast (@GroupID as nvarchar(100)) + ',''' + @LevelID + ''',''' + @empid  + ''')'
		End
	exec (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLoanEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_InsertLoanEntry]
(
@employeeID nvarchar(20)=null,
@loanAmount bigint=null,
@totalDeductionMonth numeric(2)=null,
@deductionStartMonth nvarchar(20)=null,
@monthlyDedcutAmount nvarchar(20)=null,
@loandescription nvarchar(20)=null,
@tag nvarchar(20)=null,
@loanId bigint=null

)
As
Begin
	Declare @Emp_ID bigint
	Declare @balanceAmount bigint
	set @balanceAmount=@loanAmount
	Select @Emp_ID=Employee_ID From TA_Tbl_Employee where Employee_Code_Id=@employeeID

	if(@tag='I')
	Begin
		Insert Into TA_Tbl_LoanEntryDetails (Employee_Id,Loan_Amount,Total_DeductionMonth,Deduction_StartMonth,Monthly_DeductAmount,Loan_BalanceAmount,Loan_Description,isdeleted,Loan_Entry_Date,ModifyDate,ISLoanClose) values 
		(@Emp_ID,@loanAmount,@totalDeductionMonth,@deductionStartMonth,Convert(bigint,@monthlyDedcutAmount),@balanceAmount,@loandescription,0,GETDATE(),null,0)
		Select '1' as LoanStatus
	End
	else If(@tag='U')
	Begin
		Update TA_Tbl_LoanEntryDetails set Loan_Amount=@loanAmount,Total_DeductionMonth=@totalDeductionMonth,Deduction_StartMonth=@deductionStartMonth,Monthly_DeductAmount=@monthlyDedcutAmount,Loan_BalanceAmount=@loanAmount,Loan_Description=@loandescription,ModifyDate=GETDATE() where Loan_ID=@loanId
	End
	else if(@tag='S')
	Begin
		If (isNull(@loanId,0)=0)
		Begin
			Select L.Loan_ID,E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName,L.Loan_Amount,L.Total_DeductionMonth,L.Deduction_StartMonth,L.Monthly_DeductAmount,L.Loan_BalanceAmount,L.Loan_Description,1 as flag From TA_Tbl_LoanEntryDetails L inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id where L.Isdeleted=0 and E.Isdeleted=0 and L.ISLoanClose=0
		End
		Else
		Begin
			Select L.Loan_ID,E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName,L.Loan_Amount,L.Total_DeductionMonth,L.Deduction_StartMonth,L.Monthly_DeductAmount,L.Loan_BalanceAmount,L.Loan_Description,1 as flag From TA_Tbl_LoanEntryDetails L inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id where L.Loan_ID=@loanId and L.isdeleted=0 and L.ISLoanClose=0
		End
	End
	else if(@tag='D')
	Begin
		Update TA_Tbl_LoanEntryDetails set isdeleted=1 where Loan_ID=@loanId
	End

	IF(@tag='DoJ')
	Begin
		Select DateOfJoining,Employee_Code_Id From TA_Tbl_Employee where Employee_Code_Id=@employeeID
	End
End

-- Select * From TA_tbl_Employee

-- Select * From TA_Tbl_LoanEntryDetails
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogDownloaded]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		: Manjula.P
Created Date	: 21-May-2013
Descriptions	: For creating log downloaded details as per the given requirements by sathish sir 
*/
CREATE proc [dbo].[Proc_TA_InsertLogDownloaded]
(
@LoggedEmployeeId int 
)
as begin
insert into ta_tbl_LogDownloaded(LoggedEmployeeId,LoggedDate) values(@LoggedEmployeeId,GETDATE())
select * from ta_tbl_LogDownloaded where LoggedId=(select @@IDENTITY as LoggedId)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj>
-- Create date: <Create Date,,26-Nov-07>
-- Description:	<Description,,Inserting CustomerLogo>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLogo](@logo image)
AS
DECLARE @Count as int
BEGIN
		set @count=(select count(*) from Ta_Tbl_Branding)
		if(@count=0)
		begin
		INSERT INTO Ta_Tbl_Branding(Cus_Image)values(@logo)	
		end
		else
		begin
		UPDATE Ta_Tbl_Branding SET Cus_Image=@logo
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLookupTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLookupTable]
	-- Add the parameters for the stored procedure here
@category CHAR,
@ID INT,
@Type INT,
@Title NVARCHAR(50),
@Parent INT,
@Remarks NVARCHAR(50),
@EmpID INT
AS
DECLARE @Isdeleted BIT
declare @sql as nvarchar(3000)
SET @Isdeleted=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF(@category='I')
  begin
	--INSERT INTO TA_Tbl_Lookup(Type,Title ,Parent,Remarks,EmpID,Isdeleted) VALUES(@Type,@Title,@Parent,@Remarks,@EmpID,@Isdeleted)
     set @sql = 'INSERT INTO TA_Tbl_Lookup(Type,Title ,Parent,Remarks,EmpID,Isdeleted) VALUES('+cast(@Type as nvarchar(25))+',N'''+@Title+''','+cast(@Parent as nvarchar(25))+',N'''+@Remarks+''','+cast(@EmpID as nvarchar(25))+','+cast(@Isdeleted as nvarchar(25))+')'  
	 exec(@sql)
  end
ELSE IF(@category='U')
   begin
	set @sql = 'UPDATE TA_Tbl_Lookup SET Title=N'''+@Title+''',Parent='+cast(@Parent as nvarchar(25))+' WHERE ID='+cast(@ID as nvarchar(25))+''
	exec(@sql)
   end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMailConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Manjula.P,>
-- Create date: <Create Date,23-Aug-2013,>
-- Description:	<Description,Inserting email configuration details for email scheduling,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMailConfiguration]
(
	@FromEmailId varchar(300),
	@SMTPClientHost varchar(100),
	@SMTPPort varchar(50),
	@SSLEnable bit,
	@MailAuthentication bit,
	@MailAuthenticateUser varchar(30),
	@MailAuthenticatePassword varchar(30),
	@isRequired int
)
AS
BEGIN
	SET NOCOUNT ON;
    delete from TA_Tbl_MailConfiguration
    --alter table TA_Tbl_MailConfiguration add isRequired bit default(0)
    insert into TA_Tbl_MailConfiguration values (@FromEmailId,@SMTPClientHost,@SMTPPort,@SSLEnable,@MailAuthentication,@MailAuthenticateUser,@MailAuthenticatePassword,@isRequired)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : KUMUTHINI. L  
--  Created On         : 03-Sep-2007  
--  Modified On        : 22-Nov-2007  
--  Description         : This Procedure is used to insert the Manual Time Entry  
--  [Proc_TA_InsertManualTimeEntry] 787,'04-03-2019 14:00:22','04-03-2019 14:00:22','04-03-2019 14:00:22','Shift In','','','',0,0,'Shift In',0,'Approved','04-03-2019 14:00:22',4,3,0
-- ================================================================================    
CREATE  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),
	@ManualEntry_Date DATETIME,
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImported int
)  
AS  
begin
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0
Declare @Intime_New NVARCHAR(100)
Declare @outTime_New NVARCHAR(100)

	select @Intime_New=replace(@InTime,N'பிற்பகல்','PM')
	select @Intime_New=replace(@InTime,N'முற்பகல்','AM')

	select @outTime_New=replace(@OutTime,'பிற்பகல்','PM')
	select @outTime_New=replace(@OutTime,'முற்பகல்','AM')

	--if(len(@InTime)>=17)
	--BEGIN
	--	if(substring(REPLACE(@InTime,':',''),1,6)<='115959')
	--	BEGIN
	--		set @intime=substring(REPLACE(@intime,':',''),1,2)+':'+substring(REPLACE(@intime,':',''),3,2)+':00 AM'
	--	END
	--	ELSE
	--	BEGIN
	--		set @intime=substring(REPLACE(@intime,':',''),1,2)+':'+substring(REPLACE(@intime,':',''),3,2)+':00 PM'
	--	END
	--END
	--if(len(@OutTime)>=17)
	--BEGIN
	--	if(substring(REPLACE(@OutTime,':',''),1,6)<='115959')
	--	BEGIN
	--		set @OutTime=substring(REPLACE(@OutTime,':',''),1,2)+':'+substring(REPLACE(@OutTime,':',''),3,2)+':00 AM'
	--	END
	--	ELSE
	--	BEGIN
	--		set @OutTime=substring(REPLACE(@OutTime,':',''),1,2)+':'+substring(REPLACE(@OutTime,':',''),3,2)+':00 PM'
	--	END
	--END

	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID='787'
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReader_Id
		if(@CountReader>1)
		begin			
			set @OutReader_Id=@InReader_Id
		end		
		--if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType=@InPunchType)
		--begin
		--	select Top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType in('In','Shift In')
		--end
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID='788'
	END		
	IF(@InDate = ' ')
	   BEGIN    
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,
		 ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,
		 Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		 VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@outTime_New,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,@Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10))
		 ,cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1))) 
	   END
	ELSE IF(@OutDate = ' ')  
	  BEGIN
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@Intime_New,@InPunchType,cast(@InReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
	ELSE
	  BEGIN    
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@Intime_New,@InPunchType,@OutDate,@outTime_New,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),'N', cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry_Group  
--  Author                 : Sashma  
--  Created On         : 03-May-2011  
--  Description         : This Procedure is used to insert the Manual Time Entry for a group of employees  
-- ================================================================================  
  --Proc_TA_InsertManualTimeEntry_Group '06/06/2011 12:00:00 AM','2011/06/06','09:52:16 AM','In','','','',1,0,'IN entry',0,'06/06/2011 13:52:30',1,'2',
CREATE PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry_Group]  
(  
	@ManualEntry_Date DATETIME,  
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@xml xml
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0  
	Declare @Index int
	Set @Index = 0;   
	IF(@InDate = ' ')  
	   BEGIN  
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		 select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@OutTime,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,xm.Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0 
		 from OpenXML(@Index, '/NewDataSet/Table')
		 With (EmpID Bigint 'EmpID',EmployeeId varchar(15) 'EmployeeId',Status varchar(20) 'Status') as xm 
		 Exec sp_xml_removedocument @Index
	   END  
	ELSE IF(@OutDate = ' ')  
	  BEGIN  
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,cast(@InReader_Id as nvarchar(10)),
		@Reason,xm.Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0  
		from OpenXML(@Index, '/NewDataSet/Table')
		With (EmpID Bigint 'EmpID',EmployeeId varchar(15) 'EmployeeId',Status varchar(20) 'Status') as xm 
		Exec sp_xml_removedocument @Index
	  END  
	ELSE
	  BEGIN
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,@OutDate,@OutTime,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,xm.Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0  
		from OpenXML(@Index, '/NewDataSet/Table')
		With (EmpID Bigint 'EmpID',EmployeeId varchar(15) 'EmployeeId',Status varchar(20) 'Status') as xm 
		Exec sp_xml_removedocument @Index
	  END
	  Delete FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @UserId
  END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryImport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : Gopinath.K  
--  Created On         : 26-Aug-14  
--  Description         : This Procedure is used to insert the Manual Time Entry by import functionality 
-- ================================================================================  
CREATE  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryImport]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),  
	@ManualEntry_Date DATETIME,  
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImport INT
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0  
	DECLARE @sql nvarchar(4000)
	SET @sql = ''    
	IF(@InDate = ' ')  
	   BEGIN  
		 SET @sql = ''
		 SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)'
		 SET @sql = @sql + ' VALUES(''' + @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @OutDate + ''',N''' + @OutTime + ''',N''' +@OutPunchType + ''',''' + cast(@OutReader_Id as nvarchar(10)) +  ''',N''' 
		 SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(@TimeStamp as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''' ,''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@IsImport as nvarchar(10)) + ''')' 
	   END  
	ELSE IF(@OutDate = ' ')  
	  BEGIN  
		SET @sql = ''
		SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)'
		SET @sql = @sql + ' VALUES('''+ @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @InDate + ''',N''' + @InTime + ''',N''' + @InPunchType + ''',''' + cast(@InReader_Id as nvarchar(10)) +  ''',N''' 
		SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(@TimeStamp as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''',''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@IsImport as nvarchar(10)) + ''')'   
	  END  
	ELSE
	  BEGIN
		SET @sql = ''
		SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)'
		SET @sql = @sql + ' VALUES('''+ @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @InDate + ''',N''' + @InTime + ''',N''' + @InPunchType + ''',N''' + @OutDate + ''',N''' + @OutTime + ''',N''' +@OutPunchType + ''',''' + cast(@InReader_Id as nvarchar(10)) +  ''',''' + cast(@OutReader_Id as nvarchar(10)) +  ''',N''' 
		SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(@TimeStamp as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''',''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@IsImport as nvarchar(10)) + ''')'   
	  END
	EXEC (@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : KUMUTHINI. L  
--  Created On         : 03-Sep-2007  
--  Modified On        : 22-Nov-2007  
--  Description         : This Procedure is used to insert the Manual Time Entry  
--  [Proc_TA_InsertManualTimeEntry] 787,'04-03-2019 14:00:22','04-03-2019 14:00:22','04-03-2019 14:00:22','Shift In','','','',0,0,'Shift In',0,'Approved','04-03-2019 14:00:22',4,3,0
-- ================================================================================    
CREATE  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),
	@ManualEntry_Date DATETIME,
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImported int,
	@Latitude_value varchar(20),
	@Longitude_value varchar(20),
	@Clock_Address varchar(500)
)  
AS  
begin
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0
	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=787
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReader_Id
		if(@CountReader>1)
		begin			
			set @OutReader_Id=@InReader_Id
		end		
		--if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType=@InPunchType)
		--begin
		--	select Top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType in('In','Shift In')
		--end
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=788
	END		
	IF(@InDate = ' ')
	   BEGIN    
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,
		 ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,
		 Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported,
		 Latitude_value,Longitude_value,Clock_Address)
		 VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@OutTime,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,@Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10))
		 ,cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)),@Latitude_value,@longitude_value,@Clock_Address) 
	   END
	ELSE IF(@OutDate = ' ')  
	  BEGIN
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported,
		Latitude_value,Longitude_value,Clock_Address)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,cast(@InReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),'N',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1))
		,@Latitude_value,@longitude_value,@Clock_Address) 
	  END
	ELSE
	  BEGIN    
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,@OutDate,@OutTime,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),'N', cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
end

--Select * From TA_Tbl_ManualTimeEntry
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--	Modified By		:	Manjula.P
--	Modified On		:	04-Oct-2013
--	Descriptions		:	Inserting Religion into its table then taking its id
--	Modified By		:	Manjula.P
--	Modified On		:	09-Oct-2013
--	Descriptions		:	Adding Timestamp to GETDATE() because of cannot insert null values in EmpPay by Manjula.P on 09-Oct-2013 Mantis : 0019368
--	Modified By		:	Manjula.P
--	Modified On		:	10-Jan-2013
--	Descriptions		:	Added @ParentLevelId param for adding ParentLevelId into title master table 
--	Modified By		:	A.K.T.MOORTHI
--	Modified On		:	13-Jan-2013
--	Descriptions		:	To Comment All @ParentLevelId Variable
--	Modified By		:	Manjula.P
--	Modified On		:	17-JAn-2013
--	Descriptions		:	Adding Condition for Enterprise and standard seperately
--	Modified By		:	A.K.T.MOORTHI
--	Modified On		:	08-Apr-2014
--	Descriptions		:	To Add Parameter For Check Application Mode And Add Condition Based On Application Mode
-- =============================================

create PROCEDURE [dbo].[Proc_TA_InsertMasterData]
	@ApplnMode BIT
AS
BEGIN
	set nocount on
	declare @GradeName as nvarchar(255)
	declare @GradeLevel as nvarchar(255)
	declare @ImportGradeLevel as nvarchar(255)
	--Added by Manjula.P on 10-Jan-2014 for getting levelid from designation after included levelid in title table
	--declare @ParentLevelId as int;
	--set @ParentLevelId=0;
	--set @ParentLevelId=(select top 1 isnull(id,0) from  TA_Tbl_LevelDetails t2 inner join Ta_Tbl_ImportMasterData t1 on t2.name=t1.Level1)
	--************************************************************
	select top 1 @GradeName=grade_Name,@GradeLevel=Grade_Level,@ImportGradeLevel=GradeNo from
	(select  distinct ta_tbl_grade.grade_Name,ta_tbl_grade.Grade_Level,Ta_tbl_importMasterData.GradeNo from Ta_tbl_importMasterData 
	inner join ta_tbl_grade on ta_tbl_grade.grade_Name=Ta_tbl_importMasterData.grade and ta_tbl_grade.Grade_Level<>Ta_tbl_importMasterData.GradeNo 
	where ta_tbl_grade.isdeleted=0) GradeTable
	declare @errMessage as nvarchar(4000)
	--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
	if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
		begin
			if(@GradeName<>'')
			BEGIN
				set @errMessage='Grade Name : ' + @GradeName +  ' has different GradeNo (' + @ImportGradeLevel + ') in the Employee Import file. Change the GradeNo as ' + @GradeLevel + ' in the Employee Import file'
			END
		end
	declare @Designation as nvarchar(255)
	declare @Grade as nvarchar(255)
	declare @ImportGrade as nvarchar(255)
	select top 1 @Designation=TitleName,@Grade=grade_Name,@ImportGrade=Grade from
	(select  distinct ta_tbl_title.TitleName,ta_tbl_grade.grade_Name,Ta_tbl_importMasterData.Grade from Ta_tbl_importMasterData
	inner join ta_tbl_title on  ta_tbl_title.TitleName=Ta_tbl_importMasterData.Designation 
	inner join ta_tbl_grade on ta_tbl_grade.Grade_Id=ta_tbl_title.GradeId and ta_tbl_grade.grade_Name<>Ta_tbl_importMasterData.grade
	where ta_tbl_grade.isdeleted=0 ) GradeTable --and TA_Tbl_Title.LevelID=@ParentLevelId
	--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
	if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
	begin
	if(@Designation<>'')
	BEGIN
	set @errMessage='Designation : ' + @Designation +  ' has different Grade (' + @ImportGrade + ') in the Employee Import file. Change the Grade as ' + @Grade + ' in the Employee Import file'
	END
	END
	declare @EmployeeCode as nvarchar(15)
	select Top 1 @EmployeeCode=Ta_Tbl_Employee.Employee_Code_Id
	from Ta_Tbl_Employee
	inner join Ta_tbl_importMasterData on Ta_Tbl_Employee.Employee_Code_Id=Ta_tbl_importMasterData.Employee_Code
	where Ta_Tbl_Employee.IsDeleted=0
	if(@EmployeeCode<>'')
	BEGIN
	set @errMessage='Employee Code : ' + @EmployeeCode +  ' is already exists. Remove it from Employee Import file'
	END
	declare @SwipeCardNo as nvarchar(15)
	select Top 1 @SwipeCardNo=Ta_Tbl_Employee.Employee_Code_Id
	from Ta_Tbl_Employee
	inner join Ta_tbl_importMasterData on Ta_Tbl_Employee.SwipeCardNo=Ta_tbl_importMasterData.SwipeCardNo
	where Ta_Tbl_Employee.IsDeleted=0
	if(@SwipeCardNo<>'' and @SwipeCardNo is not null)
	BEGIN
	set @errMessage='SwipeCardNo (Biometerc Number) : ' + @SwipeCardNo +  ' is already exists. Remove it from Employee Import file'
	END
	if(@errMessage<>'')
	BEGIN
			RAISERROR (@errMessage,16,1);
	END
	else
	BEGIN
		--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
		if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
		begin
		insert into ta_tbl_grade (Grade_Name,Grade_Level,Isdeleted) 
		select  distinct Grade,Gradeno,'0' as Isdeleted from Ta_tbl_importMasterData 
		where grade not in (select grade_Name from ta_tbl_grade  where isdeleted=0) 
		order by Ta_tbl_importMasterData.grade
		END
		DECLARE @TblDesignation TABLE (UniqueId BIGINT IDENTITY(1,1), LevelId BIGINT, Desingation nvarchar(MAX), GradeId BIGINT, Prog BIT)
		DECLARE @Id BIGINT, @LevelId BIGINT, @Title nvarchar(MAX)
		IF NOT EXISTS(SELECT Grade_Name FROM TA_Tbl_Grade WHERE Grade_Name = 'SEGrade' AND Isdeleted = 0)
		BEGIN
		--Enterprise	
			INSERT INTO @TblDesignation
				SELECT DISTINCT ID.Level1_Id, ID.Designation, G.Grade_ID, 0 FROM Ta_tbl_importMasterData ID
				INNER JOIN TA_Tbl_Grade G on G.Grade_Name = ID.Grade
			WHILE(EXISTS(SELECT LevelId FROM @TblDesignation WHERE Prog = 0))
			BEGIN
				SELECT TOP 1 @Id = UniqueId, @LevelId = LevelId, @Title = Desingation FROM @TblDesignation WHERE Prog = 0
				IF NOT EXISTS(SELECT TitleName FROM TA_Tbl_Title T WHERE T.LevelID = @LevelId AND T.TitleName = @Title)
				BEGIN
					INSERT INTO TA_Tbl_Title(TitleName, TitleDescription, GradeID, Isdeleted, LevelID)
						SELECT Desingation, Desingation, GradeId, 0, LevelId FROM @TblDesignation WHERE UniqueId = @Id
				END
				UPDATE @TblDesignation SET Prog = 1 WHERE UniqueId = @Id
			END
		END
		ELSE
		BEGIN
		--Standard
			INSERT INTO @TblDesignation
				SELECT DISTINCT ID.Level1_Id, ID.Designation, G.Grade_ID, 0 FROM Ta_tbl_importMasterData ID
				INNER JOIN TA_Tbl_Grade G on G.Grade_Name = 'SEGrade'
			WHILE(EXISTS(SELECT LevelId FROM @TblDesignation WHERE Prog = 0))
			BEGIN
				SELECT TOP 1 @Id = UniqueId, @LevelId = LevelId, @Title = Desingation FROM @TblDesignation WHERE Prog = 0
				IF NOT EXISTS(SELECT TitleName FROM TA_Tbl_Title T WHERE T.LevelID = @LevelId AND T.TitleName = @Title)
				BEGIN
					INSERT INTO TA_Tbl_Title(TitleName, TitleDescription, GradeID, Isdeleted, LevelID)
						SELECT Desingation, Desingation, GradeId, 0, LevelId FROM @TblDesignation WHERE UniqueId = @Id
				END
				UPDATE @TblDesignation SET Prog = 1 WHERE UniqueId = @Id
			END
		END		
		--***********************************************************************************
		insert into ta_tbl_category(CategoryName,Isdeleted)
		select distinct Employeecategory,'0' as Isdeleted from Ta_tbl_importMasterData 
		where Employeecategory not in (select CategoryName from ta_tbl_Category where isdeleted=0)
		insert into ta_tbl_type(TypeName,Isdeleted)
		select distinct Employeetype,'0' as Isdeleted from Ta_tbl_importMasterData 
		where Employeetype not in (select typeName from ta_tbl_Type where isdeleted=0)
		--Adding By Manjula.P on 04-Oct-2013 to inserting religion to master table if its <> null or ''
		insert into TA_Tbl_Religion(Name,IsDeleted,Description)
		select distinct Religion,0 as Isdeleted,Religion from Ta_tbl_importMasterData
		where Religion is not null and Religion<>'' and Religion not in (select Name from TA_Tbl_Religion where isdeleted=0) 
		--*********************************************************************************************
		Declare @UserGroup_Id int
		set @UserGroup_Id=0
		if not exists(select groupId from TA_Tbl_Usergroup where groupName='IndividualUsers')
		begin
			INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N'IndividualUsers', 1, 0, GETDATE(), 0, N'1')
		end
		select @UserGroup_Id=groupId from TA_Tbl_Usergroup where groupName='IndividualUsers'
		set @UserGroup_Id=ISNULL(@UserGroup_Id,0)	
			
		INSERT INTO [TA_Tbl_Employee]           
				   ([Employee_FirstName]
				   ,[Employee_MiddleName]
				   ,[Employee_LastName]
				   ,[Father_name]
				   ,[Mother_name]
				   ,[DateofBirth]
				   ,[DateofBirth_Record]
				   ,[Blood_Group]
				   ,[EmailId]
				   ,[Contact_Address]
				   ,[Permanent_Address]
				   ,[Phone_Number]
				   ,[Mobile_Number]
				   ,[Gender]
				   ,[Marital_status]
				   ,[Nationality]
				   --Commented by MAnjula.P on 04-Oct-2013 to avoiding Religion Converstion error
				   --,[Religion]          
				   ,[Personal_mailid]
				   ,[Passport_No]
				   ,[Passport_expirydate]
				   ,[Visa_No]
				   ,[Visa_expirydate]          
				   ,[Employee_Code_Id]
				   ,[DateOfJoining]                    
				   ,[UserName]
				   ,[Emp_password]
				   ,[Qual_JoiningTime]
				   ,[Qual_Employment]
				   ,[OutDoorJob]
				   ,[CompOff_Eligible]
				   ,[OT_Eligible]
				   ,[ESI_Eligible]
				   ,[PF_Eligible]
				   ,[Report_Exclude]
				   ,[Employee_Status]
				   ,[SwipeCardNo]           
				   ,[Isdeleted]
				   ,[Hostel],
				   IsImported, InActive_Status,UserGroup_Id
				   )
		select [Emp_FirstName]
				   ,[Emp_MiddleName]
				   ,[Emp_LastName]
				   ,[Father_name]
				   ,[Mother_name]
				   ,[DateofBirth]
				   ,[DateofBirth_Record]
				   ,[Blood_Group]
				   ,[Email_Id]
				   ,[Contact_Address]
				   ,[Permanent_Address]
				   ,[Phone_Number]
				   ,[Mobile_Number]
				   ,[Gender]
				   ,[Marital_status]
				   ,[Nationality]
				 --Commented by MAnjula.P on 04-Oct-2013 to avoiding Religion Converstion error
				 --  ,[Religion]          
				   ,[Personal_emailid]
				   ,[Passport_No]
				   ,case when [Passport_expirydate] IS null or [Passport_expirydate]='' then null else Passport_ExpiryDate end
				   ,[Visa_No]
				   ,case when [Visa_expirydate] IS null or [Visa_expirydate]='' then null else [Visa_expirydate] end
				   ,[Employee_Code] as [Employee_Code_Id]
				   ,[DateOfJoining]                    
				   ,[Employee_Code] as [UserName]
				   ,'QL5OWbmiorXf+5GMDoaz1w==' as [Emp_password]
				   ,[Qualification_JoiningTime]
				   ,[Qualification_Employement]
				   ,[OutDoorJob]
				   ,[CompOff_Eligible]
				   ,[OT_Eligible]
				   ,[ESI_Eligible]
				   ,[PF_Eligible]
				   ,[Report_Exclude]
				   ,[Employee_Status]
				   ,[SwipeCardNo]           
				   ,[Isdeleted]
				   ,[Hostel],1,0,@UserGroup_Id
		from Ta_tbl_importMasterData
		where [Employee_Code] not in (select employee_code_id from ta_tbl_employee where ((Isdeleted = 0 OR (1 =1 AND @ApplnMode = 0))))
		insert into ta_tbl_employeecategory (EmployeeId, CategoryID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_category.CategoryID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id = Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_category on ta_tbl_category.CategoryName = Ta_Tbl_ImportMasterData.EmployeeCategory
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeecategory)
		insert into ta_tbl_employeeType (EmployeeId, TypeID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_type.typeID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_type on ta_tbl_type.TypeName = Ta_Tbl_ImportMasterData.EmployeeType
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeeType)
		--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
		if not exists (select * from TA_Tbl_Grade where Grade_Name='SEGrade' and Isdeleted=0)
		begin
			--Enterprise
		insert into ta_tbl_employeeDesignation (EmployeeId, DesignationID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_title.TitleID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_title on ta_tbl_title.TitleName = Ta_Tbl_ImportMasterData.Designation 
		AND ta_tbl_title.LevelID = Ta_Tbl_ImportMasterData.Level1_Id
		inner join ta_tbl_Grade on ta_tbl_Grade.Grade_Id =ta_tbl_title.GradeId 
		--and ta_tbl_Grade.Grade_Level=Ta_Tbl_ImportMasterData.GradeNo
		and ta_tbl_Grade.Grade_ID=TA_Tbl_Title.GradeID
		where Ta_tbl_employee.Employee_Id 
		not in (select EmployeeId from ta_tbl_employeeDesignation)
		--TA_Tbl_Title.LevelID=@ParentLevelId and 
		end
		else
		begin
			--Standard
			insert into ta_tbl_employeeDesignation (EmployeeId, DesignationID, EffectiveDate) 
			select Ta_tbl_employee.Employee_ID, ta_tbl_title.TitleID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
			inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
			inner join ta_tbl_title on ta_tbl_title.TitleName = Ta_Tbl_ImportMasterData.Designation 
			AND ta_tbl_title.LevelID = Ta_Tbl_ImportMasterData.Level1_Id
			inner join ta_tbl_Grade on ta_tbl_Grade.Grade_Name ='SEGrade'
			where Ta_tbl_employee.Employee_Id 
			not in (select EmployeeId from ta_tbl_employeeDesignation)
			--TA_Tbl_Title.LevelID=@ParentLevelId and 
		end
		--***********************************************************************************
		--Adding Timestamp to GETDATE() because of cannot insert null values in EmpPay by Manjula.P on 09-Oct-2013 Mantis : 0019368
		insert into ta_tbl_employeePay (EmployeeId, BasicPay, EffectiveDate,Timestamp) 
		select Ta_tbl_employee.Employee_ID, Ta_Tbl_ImportMasterData.BasicSalary,Ta_Tbl_ImportMasterData.DateOfJoining,GETDATE() from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeePay)
		--Adding By Manjula.P on 04-Oct-2013 for updating Religion 
		update E set Religion=R.ID from ta_tbl_Employee E 
		inner join Ta_Tbl_ImportMasterData IM on IM.Employee_Code=E.Employee_Code_Id and IM.Religion is not null and IM.Religion <>'' 
		inner join TA_Tbl_Religion R on R.Name=IM.Religion
		where E.Isdeleted=0
		--********************************************************
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterDataLevelsParent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMasterDataLevelsParent]
AS
BEGIN
insert into ta_tbl_leveldetails (levelid,parentid,name,description)
select distinct 1,0,level1,level1 from Ta_Tbl_ImportMasterData where 
level1 not in (select name from ta_tbl_leveldetails where isdeleted=0 and parentid=0)
and level1 <>''
--Added by Manikandan.R
--On 05-02-2014 05.22PM
declare @groupId as bigint
set @groupId=(select GroupId from ta_tbl_usergroup where groupName='SuperAdmin')
insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) 
select @groupId,id,1 from Ta_Tbl_levelDetails where id not in(select levelId from TA_Tbl_LevelRights where @groupId=@groupId)
--select * from TA_Tbl_LevelRights order by GroupId,LevelId 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMobileClockIn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-08-2019 02:41 PM>
-- Description:	<Insert Mobile Clock in and Clock out time>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMobileClockIn]
(
	@EmployeeCodeID varchar(20),
	@ClockDate datetime,
	@Clock_Time varchar(15),
	@PunchType varchar(20),
	@Latitude_value varchar(20),
	@Longitude_value varchar(20),
	@Clock_Address varchar(500)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Insert into Ta_tbl_mobileClockInAndOut values(@EmployeeCodeID,@ClockDate,@Clock_Time,@PunchType,GETDATE(),@Latitude_value,@Longitude_value,@Clock_Address)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNearingShiftDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <17-03-2017 02.54 pm>
-- Description:	<Update shift details through Nearest shift allocation screen>
-- Proc_TA_InsertNearingShiftDetails 3,'05/01/2019 12:00:00 AM',3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertNearingShiftDetails]
	@Empid bigint,
	@ShiftDate datetime,
	@ShiftID int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @year INT
	DECLARE @month INT
	DECLARE @day INT
	DECLARE @DynamicQuery VARCHAR(MAX)
	SET @DynamicQuery =''	
	SELECT @year=DATEPART(YEAR,@ShiftDate),@month=DATEPART(MONTH,@ShiftDate),@day=DATEPART(DAY,@ShiftDate)
	--select @year,@month,@day
	IF(@year is not null and @month is not null and @day is not null)
	BEGIN
		if exists(select * from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@Empid)
		begin
			SET @DynamicQuery =@DynamicQuery +'update TA_Tbl_PermanentShiftAllocation set day'+CONVERT(VARCHAR(2),@day)+'shift='+CONVERT(VARCHAR(2),@ShiftID)+ ' where
			month='+CONVERT(VARCHAR(20),@month)+' and year='+CONVERT(VARCHAR(20),@year)+' and employeeid='+CONVERT(VARCHAR(20),@Empid)
		end
		else
		begin

	/*  Hariharan J ************Common UTC DateGet ******** 14-02-2024 */
			SET @DynamicQuery =@DynamicQuery +'insert into TA_Tbl_PermanentShiftAllocation (day'+CONVERT(VARCHAR(2),@day)+'shift,month,year,employeeid,Emp_id,dateshift)
			values('+CONVERT(VARCHAR(2),@ShiftID)+ ','+CONVERT(VARCHAR(20),@month)+','+CONVERT(VARCHAR(20),@year)+','+CONVERT(VARCHAR(20),@Empid)+',1,'''+Convert(varchar(11),DATEADD(dd,-(DAY(GetUTCDate())-1),GetUTCDate()))+''')'
			print(@DynamicQuery)
		end
					
		EXECUTE(@DynamicQuery)
		Declare @SwipeCardNumber varchar(50)
		select @SwipeCardNumber=SwipeCardNo from ta_tbl_employee where Employee_Id=@Empid and isdeleted=0
		--select @ShiftDate,@ShiftDate,@EmployeeCodeId
		DELETE PD FROM TA_Tbl_ProcessedData PD Where PD.Date BETWEEN @ShiftDate AND @ShiftDate And PD.Employee_Code_Id=@SwipeCardNumber
		Update TA_Tbl_Clk_RawData Set CLK_FLAG=0,CLK_PROCESS=0 Where CLK_DATE BETWEEN dateadd(d,-1,@ShiftDate) AND dateadd(d,1,@ShiftDate)
		and CLK_CARDID=@SwipeCardNumber
		Delete CD from TA_Tbl_ClockDetails CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN @ShiftDate AND @ShiftDate 
		Delete CD from ta_tbl_MatchedPunches CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN @ShiftDate AND @ShiftDate 
		UPDATE MT SET MT.Clk_Process = 'N' from TA_Tbl_ManualTimeEntry MT
		Inner join TA_Tbl_Employee E on E.Employee_Code_Id = MT.ManualTimeEntry_Employee_Id 
		AND ((MT.ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@ShiftDate) AND DateAdd(d,1,@ShiftDate)) 
		OR (MT.ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@ShiftDate) AND DateAdd(d,1,@ShiftDate)))
		where E.Employee_Id=@Empid
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNews]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	created by : senthil
	created on : 10 Aug 2007
	Description : Inserting and updating news/Events
*/
CREATE procedure [dbo].[Proc_TA_InsertNews]
(
	@newsEventFromDate as datetime,
    @newsEventToDate as datetime,
	@newsEventTitle as nvarchar(254),
	@newsEventDescription as nvarchar(500),
	@newsEventActive as bit,
	@newsEventImage as nvarchar(254),
	@leftNewsEvent as bit,
	@rightNewsEvent as bit,
	@leftBanner as bit,
	@rightBanner as bit,
	@employeeId as decimal(18,0),
	@opr as nvarchar(1),
	@newsEventId as int
)
as 
Begin
	declare @sql as varchar(3000)
    declare @dotposition as varchar(25)
    declare @strreplace as varchar(25)
    declare @result as varchar(25)
    declare @nextId as int
	if @opr='I'
		Begin
            insert into ta_tbl_newsEvents (newsEventFromDate,newsEventToDate,newsEventTitle,newsEventDescription,newsEventActive,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,Emp_Id,Isdeleted) values (@newsEventFromDate,@newsEventToDate,@newsEventTitle,@newsEventDescription,@newsEventActive,@leftNewsEvent,@rightNewsEvent,@leftBanner,@rightbanner,@employeeId,0)
            if (@newsEventImage <> '')
             begin
               set @nextId = (select @@identity)
               set @dotposition = CHARINDEX('.',@newsEventImage)
               set @strreplace = SUBSTRING(@newsEventImage,1,@dotposition-1)
               set @result = REPLACE(@newsEventImage,@strreplace,@nextId)
			   update ta_tbl_newsEvents set newsEventImage=@result where newsEvent_Id=@nextId
             end
			--insert into ta_tbl_newsEvents (newsEventDate,newsEventTitle,newsEventDescription,newsEventActive,newsEventImage,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,employee_Id,Isdeleted) values (@newsEventDate,@newsEventTitle,@newsEventDescription,@newsEventActive,@newsEventImage,@leftNewsEvent,@rightNewsEvent,@leftBanner,@rightbanner,@employeeId,0)
		--	set @sql = 'insert into ta_tbl_newsEvents (newsEventDate,newsEventTitle,newsEventDescription,newsEventActive,newsEventImage,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,employee_Id,Isdeleted) values (' + cast (@newsEventDate as nvarchar(25)) + ',N''' + @newsEventTitle + ',' + @newsEventDescription + ',' + cast(@newsEventActive as nvarchar(25)) + ',' + @newsEventImage + ',' + cast (@leftNewsEvent as nvarchar(25)) + ',' + cast (@rightNewsEvent as nvarchar(25))  + ',' +  cast (@leftBanner as nvarchar(25))  + ',' +  cast (@rightbanner as nvarchar(25))  + ',' +  cast (@employeeId as nvarchar(25)) + ',0)'
		--	exec(@sql)
		End
	else
		Begin
			update ta_tbl_newsEvents set newsEventFromDate=@newsEventFromDate,newsEventToDate=@newsEventToDate,newsEventTitle=@newsEventTitle,newsEventDescription=@newsEventDescription,newsEventActive=@newsEventActive,newsEventImage=@newsEventImage,leftNewsEvent=@leftNewsEvent,rightNewsEvent=@rightNewsEvent,leftBanner=@leftBanner,rightbanner=@rightBanner,Emp_Id=@employeeId,Isdeleted=0 where newsEvent_Id=@newsEventId
		End
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : Gopinath.K
--  Created On         : 06-Jun-2014
--  Description         : This Procedure is used to insert the Onduty Entry
--	Descriptinos		:	Seperated from Manual Entry Insert due to adding of Shift ID and Shift date seperately
-- [Proc_TA_InsertOnDutyEntry] 787787,'20170817','20170817','09:00','Shift In','20170817','12:00','Shift Out',0,0,'testing',0,'Approved','20170817',48,1,1,2,'20170817',1
-- ================================================================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntry]  
(  
@ManualEntry_EmployeeId NVARCHAR(20),  
@ManualEntry_Date DATETIME,  
@InDate NVARCHAR(20),  
@InTime NVARCHAR(20), 
@InPunchType NVARCHAR(25),
@OutDate NVARCHAR(20),  
@OutTime NVARCHAR(20),
@OutPunchType NVARCHAR(25),
@InReader_Id INT,  
@OutReader_Id INT,  
@Reason NVARCHAR(max),  
@RouteId INT, 
@Status nVarchar(25),
@UserId INT,
@YearSettings_Id NVARCHAR(25),
@IsOnDuty INT,
@ShiftId NVARCHAR(25),
@ShiftDate NVARCHAR(20),
@OndutyID int
)  
AS  
begin
	set nocount on
	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=787
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=788
	END	
	DECLARE @Isdel INT  
	SET @Isdel=0  
	DECLARE @sql nvarchar(4000)
	SET @sql = ''    
	IF(@InDate = ' ')  
	   BEGIN  
		 --SET @InDate = NULL  
		 SET @sql = ''
		 SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)'
		 SET @sql = @sql + ' VALUES(''' + @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @OutDate + ''',N''' + @OutTime + ''',N''' +@OutPunchType + ''',''' + cast(@OutReader_Id as nvarchar(10)) +  ''',N''' 
		 SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(Getdate() as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''' ,''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@ShiftId as nvarchar(10)) + ''',''' + cast(@ShiftDate as nvarchar(20)) + ''','''+ cast(@OndutyID as nvarchar(20)) + ''')' 
	   END  
	ELSE IF(@OutDate = ' ')  
	  BEGIN  
	   --SET @OutDate = NULL  
		SET @sql = ''
		SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)'
		SET @sql = @sql + ' VALUES('''+ @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @InDate + ''',N''' + @InTime + ''',N''' + @InPunchType + ''',''' + cast(@InReader_Id as nvarchar(10)) +  ''',N''' 
		SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(Getdate() as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''',''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@ShiftId as nvarchar(10)) + ''',''' + cast(@ShiftDate as nvarchar(20)) + ''','''+ cast(@OndutyID as nvarchar(20)) + ''')'   
	  END  
	ELSE
	  BEGIN
		SET @sql = ''
		SET @sql = @sql + 'INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)'
		SET @sql = @sql + ' VALUES('''+ @ManualEntry_EmployeeId + ''',''' + cast(@ManualEntry_Date as nvarchar(20)) + ''',N''' + @InDate + ''',N''' + @InTime + ''',N''' + @InPunchType + ''',N''' + @OutDate + ''',N''' + @OutTime + ''',N''' +@OutPunchType + ''',''' + cast(@InReader_Id as nvarchar(10)) +  ''',''' + cast(@OutReader_Id as nvarchar(10)) +  ''',N''' 
		SET @sql = @sql + @Reason + ''',N''' +@Status + ''',''' + cast(@RouteId as nvarchar(20)) + ''',''N'',''' + cast(@Isdel as nvarchar(10)) + ''',''' + cast(Getdate() as nvarchar(20)) + ''',''' + cast(@UserId as nvarchar(10)) + ''',''' + cast(@YearSettings_Id as nvarchar(10)) + ''',''' + cast(@IsOnDuty as nvarchar(10)) + ''',''' + cast(@ShiftId as nvarchar(10)) + ''',''' + cast(@ShiftDate as nvarchar(20)) + ''','''+ cast(@OndutyID as nvarchar(20)) + ''')'   
	  END
	EXEC (@sql)
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntryForTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ================================================================================  
--  Procedure Name		: Proc_TA_InsertOnDutyEntryForTable  
--  Author              : Karthikeyan.R
--  Created On			: 08-Mar-2016
--  Description         : This Procedure is used to insert and update the Onduty Entry
--	TableName			: TA_Tbl_OndutyEntry
-- [Proc_TA_InsertOnDutyEntryForTable] 'I','0','659','11-24-2017',1,0,'11/24/2017','09:00','11/24/2017','14:00','اختبارات','Approved','48','',''
-- ================================================================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntryForTable]
	-- Add the parameters for the stored procedure here
	@type nvarchar(2),
	@Onduty_ID int,
	@Onduty_EmployeeID nvarchar(20),
	@Onduty_EntryDate	datetime,
	@Onduty_Type int,
	@IncludeweekOff int,
	@Onduty_FromDate datetime,
	@Onduty_FromTime nvarchar(50),
	@Onduty_ToDate datetime,
	@Onduty_ToTime nvarchar(50),
	@Onduty_Reason nvarchar(Max),
	@Onduty_Status nvarchar(25),
	@Emp_Id int,
	@From_Session nvarchar(25),
	@To_Session nvarchar(25)
AS
BEGIN
	SET NOCOUNT ON;
	--print 's'

	declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@Emp_Id)

	--Print @GetUTCTime
	--Select * from TA_Tbl_OndutyEntry

	DECLARE @Isdel INT  
	SET @Isdel=0  
	declare @OndutyID as int
	DECLARE @sql nvarchar(4000)
	SET @sql = ''  
	BEGIN
	if(@type='I')
	BEGIN
		Declare @YearSettings_Id  int
		select @YearSettings_Id =YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
		INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FromDate,Onduty_FromTime,Onduty_ToDate,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,From_Session,To_Session,YearSettings_Id) 
		VALUES (@Onduty_EmployeeID,cast(@Onduty_EntryDate as nvarchar(20)),CAST(@Onduty_Type as nvarchar(10)),CAST(@IncludeweekOff as nvarchar(10)) ,
		cast(@Onduty_FromDate as nvarchar(20) ), CAST(@Onduty_FromTime as nvarchar(50)),cast(@Onduty_ToDate as nvarchar(20)) ,
		 CAST(@Onduty_ToTime as nvarchar(50)) , CAST(@Onduty_Reason as nvarchar(max)) ,CAST(@Onduty_Status as nvarchar(25)) , CAST(@Isdel as nvarchar(2)) ,@GetUTCTime,CAST(@Emp_Id as nvarchar(10)) 
		 ,CAST(@From_Session as nvarchar(25)) ,CAST(@To_Session as nvarchar(25)),@YearSettings_Id)
		select @OndutyID=MAX(Onduty_ID) from TA_Tbl_OndutyEntry
	END
	else
		begin
			SET @sql = @sql + 'update TA_Tbl_OndutyEntry set IncludeWeekOff=N''' +CAST(@IncludeweekOff as nvarchar(10)) + ''',Onduty_Type=N''' +CAST(@Onduty_Type as nvarchar(10)) + ''',Onduty_FromDate=N''' +CAST(@Onduty_FromDate as nvarchar(20)) + ''',Onduty_FromTime=N''' +CAST(@Onduty_FromTime as nvarchar(20)) +''',Onduty_ToDate=N''' +CAST(@Onduty_ToDate as nvarchar(20)) +''',Onduty_ToTime=N'''+CAST(@Onduty_ToTime as nvarchar(20))+''',Onduty_Reason=N'''+CAST(@Onduty_Reason as nvarchar(max)) +''',From_Session=N'''+CAST(@From_Session as nvarchar(20)) +''',To_Session=N'''+CAST(@To_Session as nvarchar(20)) +''',Onduty_Status=N'''+CAST(@Onduty_Status as nvarchar(20)) +''',Emp_Id=N''' +CAST(@Emp_Id as nvarchar(25)) +''' where Onduty_ID=N''' +CAST(@Onduty_ID as nvarchar(25)) +''''
			EXEC (@sql)	
			set @OndutyID=@Onduty_ID
		end
		select @OndutyID as [Onduty_ID]
	End
	Declare @Onduty_EmployeeID_AutoID int
	select @Onduty_EmployeeID_AutoID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id =@Onduty_EmployeeID and Isdeleted=0 
	if((@Onduty_Status='Forwarded' or @Onduty_Status='Approved')and @Onduty_EmployeeID_AutoID!=@Emp_Id)
	BEGIN
		DECLARE @orderBy as int 
		DECLARE @OnDutyConversationCount as int 
		SELECT @OnDutyConversationCount=COUNT(*) FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @OndutyID
		SET @orderBy = @OnDutyConversationCount + 1
		INSERT INTO TA_Tbl_OnDutyConversation(OnDutyApplicationId,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@OndutyID, 'Ok', @orderBy, @Emp_Id,@GetUTCTime)	
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertorUpdateEmployeeLingual]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- Create date: 28 Nov 07
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertorUpdateEmployeeLingual] 
	-- Add the parameters for the stored procedure here
	@LanguageId int,
    @EmployeeId int
AS
declare @RecordExisting as int
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	set @RecordExisting=(SELECT count(*) FROM TA_Tbl_EmployeeLingual WHERE EmployeeId=@EmployeeId)
    if (@RecordExisting=0)
       begin
           INSERT INTO TA_Tbl_EmployeeLingual(LanguageId, EmployeeId) VALUES(@LanguageId, @EmployeeId)
       end
    else
       begin
           UPDATE TA_Tbl_EmployeeLingual SET LanguageId = @LanguageId WHERE EmployeeId = @EmployeeId
       end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_InsertOtType]
	@OtType as varchar(50),
	@OtValue as varchar(25),
	@CompanyID as int,
	@EmpId as int
AS
BEGIN	
	insert into TA_Tbl_OtType (OtType,OtValue,EmpID,IsDeleted,CompanyID) values (@OtType,@OtValue,@EmpID,0,@CompanyID)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPayrollLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_InsertPayrollLeaveDetails]
(
   @MonthCloseId int,
   @LeaveType Varchar(25),
   @EmployeeId NVarchar(20)
)
AS
begin
	SET NOCOUNT ON;
	Declare @query as Varchar(3000)
	Declare @query1 as Varchar(3000)
	Declare @query2 as Varchar(3000)
	Declare @query3 as Varchar(3000)
	Declare @LeaveType_Id as Varchar(25)
	Declare @MonthClosureId as int
	create table #Temp(LeaveType_Id int)
	create table #Temp1(MonthClosure_Id int)
	set @query = 'select LeaveType_Id from TA_Tbl_LeaveType where LeaveType = ''' + @LeaveType + ''''
	insert into #Temp EXEC(@query)
	set @LeaveType_Id=(select * from #Temp)
	set @query1 = 'select MonthClosure_Id from TA_Tbl_PayrollProcessLeaveDetails where MonthClosure_Id = ' + Cast(@MonthCloseId as Varchar) + ' and Employee_Id = ' + @EmployeeId + ' and LeaveType_id = ' + Cast(@LeaveType_Id as Varchar)
	insert into #Temp1 EXEC(@query1)
	set @MonthClosureId = (select * from #Temp1)
	set @MonthClosureId = isnull(@MonthClosureId,-1)
	if(@MonthClosureId = -1)
	begin
	   set @query2 = 'insert into TA_Tbl_PayrollProcessLeaveDetails(MonthClosure_Id,Employee_Id,LeaveType_id,Leave_Count)VALUES(' + Cast(@MonthCloseId as Varchar) + ', ' + @EmployeeId + ',' + Cast(@LeaveType_Id as Varchar) +',1)'
	   EXEC(@query2)
	end
	else if(@MonthClosureId > 0)
	begin
	   set @query3 =  'UPDATE TA_Tbl_PayrollProcessLeaveDetails SET Leave_Count = Leave_Count + 1 WHERE MonthClosure_Id = ' + Cast(@MonthCloseId as Varchar) + 'and LeaveType_id = ' + Cast(@LeaveType_Id as Varchar) + ' and Employee_Id = ' + @EmployeeId + ' '
	   EXEC(@query3)
	end
	drop table #Temp
	drop table #Temp1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified by	:	Prabakaran.P
-- Modified on	:	06-Feb-10
-- Proc_TA_InsertPermission 5,'26/Mar/2019','1','26/Mar/2019 09:00','26/Mar/2019 09:30','26/Mar/2019',1,3,'Approved','',null
CREATE  PROCEDURE [dbo].[Proc_TA_InsertPermission]
(
	@EmployeeID int,
	@Permission_Date datetime,
	@PermissionType nvarchar(50),
	@Permission_FromTime datetime,
	@Permission_EndTime datetime,
	@Reason nvarchar(1000),
	@auEmpId nvarchar(50),
	@YearSettings_Id nvarchar(20),
	@strPermissionStatus nvarchar(20),
	@CCMail varchar(3000),
	@Permission_Hours varchar(5)
)
as
BEGIN
	SET NOCOUNT ON;
		declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@EmployeeID)



	declare @UnPlanned as int
	set @UnPlanned=0
	if @EmployeeID<>@auEmpID
	Begin
	set @UnPlanned=1
	end	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
		[EffectiveDate] ASC
		) ON [PRIMARY]
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
		[LevelId] ASC
		) ON [PRIMARY]
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
		[EmployeeId] ASC
		)ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Permission_Date as nvarchar(50)), 102) and EL.LevelId is not null
	declare @sql nvarchar(MAX)
	declare @Isdeleted bit
	declare @del bit
	set @del=0
	set @Isdeleted=0
	set @sql=''
	declare @CountRecord as int
	set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID and Isdeleted=0)
	if(@strPermissionStatus='' and @CountRecord>0)
		BEGIN
			set @strPermissionStatus='Forwarded'
		END
	else if (@strPermissionStatus='' and @CountRecord=0)
		BEGIN
			set @strPermissionStatus='Pending'
		END
	begin
	--Arabic content is not inserting properly into database, uncomment the below coding and comment the static coding.
	--set @sql='INSERT INTO TA_Tbl_Permission
	--(Employee_Id,Permission_Date,Permission_Type,Permission_FromTime,Permission_ToTime,Permission_Reason,Permission_Status,IsDeleted,Emp_Id,YearSettings_Id, UnPlanned, CCMail,Permission_Hours,No_Of_Hours) 
	--VALUES(''' + cast(@EmployeeID as nvarchar(25)) + ''', '''+ cast(@Permission_Date as nvarchar(100)) + ''',N''' + @PermissionType + ''',''' + cast(@Permission_FromTime as nvarchar(100)) + ''',''' + cast(@Permission_EndTime as nvarchar(100)) + ''',N''' + @Reason + ''',N''' + @strPermissionStatus + ''',''' + cast(@Isdeleted as nvarchar(5)) + ''',N''' + @auEmpId + ''',N''' + @YearSettings_Id + ''', ' + cast(@UnPlanned as nvarchar(25)) + ',''' + @CCMail + ''',''' + @Permission_Hours + ''',''' + @Permission_Hours + ''')'
	--Exec(@sql)
	
	INSERT INTO TA_Tbl_Permission
	(Employee_Id,Permission_Date,Permission_Type,Permission_FromTime,Permission_ToTime,Permission_Reason,Permission_Status,IsDeleted,TimeStamp,Emp_Id,YearSettings_Id, UnPlanned, CCMail,Permission_Hours,No_Of_Hours) 
	VALUES(cast(@EmployeeID as nvarchar(25)),cast(@Permission_Date as nvarchar(100)),@PermissionType,
	cast(@Permission_FromTime as nvarchar(100)),cast(@Permission_EndTime as nvarchar(100)),@Reason ,@strPermissionStatus,cast(@Isdeleted as nvarchar(5)),@GetUTCTime,@auEmpId ,@YearSettings_Id ,cast(@UnPlanned as nvarchar(25)),@CCMail,@Permission_Hours ,@Permission_Hours)
	
	SELECT P.Permission_Id,LD.Id AS LevelId,P.UnPlanned,Permission_Status as 'Status' FROM TA_Tbl_Permission P
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = P.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
	INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
	WHERE P.Permission_Id = (SELECT @@IDENTITY AS Permission_Id)
	end
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPrevPermission_Eastman]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <25-03-2019 04.20PM>
-- Description:	<Inserting Previous Permission details of the current application>
-- Proc_TA_InsertPrevPermission_Eastman 0,8,'22-Mar-2019','09:31:00','10:00:00','tes','22-Mar-2019'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertPrevPermission_Eastman]
	@Cur_Perm_ID bigint,
	@Prev_Perm_ID bigint,
	@Prev_Perm_date varchar(20),
	@Prev_Perm_ShiftTime varchar(20)=null,
	@Prev_Perm_InTime varchar(20)=null,
	@Prev_Perm_LateHours varchar(10)=null,
	@Prev_Perm_Reason varchar(500),
	@Prev_Perm_ReceivedDate varchar(20)=null
AS
BEGIN
	SET NOCOUNT ON;
	Insert into ta_tbl_PrevPermissionDetails_EastMan values
	(
		@Cur_Perm_ID,
		@Prev_Perm_ID,
		getdate(),
		@Prev_Perm_date,
		@Prev_Perm_ShiftTime,
		@Prev_Perm_InTime,
		@Prev_Perm_LateHours,
		@Prev_Perm_Reason,
		@Prev_Perm_ReceivedDate
	)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertProcessedData]
(
   @SwipeCardNo nvarchar(20),
   @Date nvarchar(15),
   @ShiftId int,
   @Attendance nvarchar(20) 
)
AS
 Insert Into TA_Tbl_ProcessedData (Employee_Code_Id, [Date], Shift_Id, InTime, OutTime, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, Attendance, WorkHrs, HrsLess,HrsExtra,LateInMins,EarlyOutMins,OtMins)
 Values(@SwipeCardNo,@Date,@ShiftId,'0','0','0','0','0','0','0','0','0',@Attendance,'0','0','0',0,0,0)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created On		:	27-Nov-2013
Descriptions	:	Inserting punch types directly from the device using window service (Collect Raw Data)
*/
CREATE proc [dbo].[Proc_TA_InsertPunchTypes_FromDevice]
as
begin
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
	BEGIN
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	--@sql2 for application db query
	DECLARE @sql2 nvarchar(max)
	--@sql1 for device db query
	DECLARE @sql1 nvarchar(max)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	--Creating temprary table for getting terminal data values 
	create table #Temp_PunchType
	(
	strName nvarchar(32),
	nTNAEvent int not null,
	ndeviceid nvarchar(10),
	TerminalId int
	)
	--**********************************************************
		IF((SELECT top 1 FileType FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)='RDBMS' and (SELECT top 1 BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=3)
			BEGIN
				SET @ConnectionString=(SELECT ConnectionString FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0 and FileType='RDBMS' and BrandId=3)
				--Create table To splitup the Server and database name
				--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
				IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
					BEGIN
						INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
						SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=2				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=3)				
						UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=4)
						--select * from Ta_tbl_DeviceServerDetails			
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=5)				
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						--select * from  Ta_tbl_DeviceServerDetails
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
					END			
				SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails	
				--exec sp_addlinkedserver @ServerName;
				--creating linked server and linkedserverlogin by Manjula.P on 06-Feb-2014
				if not exists(select * from sys.servers where name = N''+@ServerName+'')
				begin
					EXEC sp_addlinkedserver @server=@ServerName
				end
					declare @suser_sname nvarchar(256)
					set  @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N'False',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------				
				select * from Ta_tbl_DeviceServerDetails			
				CREATE TABLE #test(exist int,TableName varchar(500))
				Create table #DeviceDetailsMovedToTimecheck(name varchar(50))
				--TB_EVENT_LOG,	TB_TA_DEVICE_EVENT_KEY= in BioStar Device 
				--tb_userevent = in BioAdmin Device			
				set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''TB_EVENT_LOG'',''TB_TA_DEVICE_EVENT_KEY'',''tb_userevent'')'
				Insert into #test exec(@sql)
				--select * from #test				
				--It means the connected device checked whether its BioAdmin			
				if ((select COUNT(*) from #test where TableName ='tb_userevent')>0)
					begin						
						set @sql1=''
						set @sql1=' select distinct(RL.ndeviceid),RL.ndeviceid,RL.ndeviceid,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_reportslist RL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent  where RL.ndeviceid not in('
						set @sql2=' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 ) '						
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	                    SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType='RDBMS'),1,GETDATE(),0 from #Temp_PunchType
	                    update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	                    inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''
						set @sql1='select distinct(strName),UE.nIndex,ndeviceid,T.Terminal_Id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_reportslist RL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RL.nDeviceID and T.isDeleted=0 and isnumeric(Terminal_ReaderID)=1 where strName not in( '
						set @sql2=' select PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join  ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=P.Value  where P.Isdeleted=0  and T.Isdeleted=0 and P.Terminal_Id=T.Terminal_Id and P.Value=UE.nindex ) group by strName,UE.nIndex,ndeviceid,T.Terminal_Id'
						delete from #Temp_PunchType;
						insert into #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                   -- where nTNAEvent not in (select Value from TA_Tbl_PunchTypes)	              
					end
				--It means the connected device checked whether its BioStar
				else if((select COUNT(*) from #test where TableName in ('TB_EVENT_LOG','TB_TA_DEVICE_EVENT_KEY'))>1)
					begin						
						set @sql1=''
						set @sql1='select distinct(EL.nReaderIdn) as strName,EL.nReaderIdn,EL.nReaderIdn as ndeviceid,0  from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_EVENT_LOG EL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  '
						set @sql1=@sql1+'  where convert(varchar(20),EL.nReaderIdn) not in( '
						set @sql2=' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )order by ndeviceid '
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						--select * from #Temp_PunchType
						--Inserting trerminal id for punch type mapping with terminal if the device is not saved in db
						INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	                    SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType='RDBMS' and BrandId=3 and IsDeleted=0),1,GETDATE(),0 from #Temp_PunchType
	                    update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	                    inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''
						set @sql1='select distinct(sEventName) as strName,DEK.nKeyIdn,EL.nReaderIdn as ndeviceid,T.Terminal_Id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_EVENT_LOG EL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  '
						set @sql1=@sql1+'  inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=EL.nReaderIdn and T.Isdeleted=0 and isnumeric(Terminal_ReaderID)=1 where sEventName not in( '
						set @sql2=' select PunchType  from TA_Tbl_PunchTypes P  inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on  DEK.nReaderIdn=T.Terminal_ReaderID where P.Isdeleted=0 and T.Isdeleted=0 and P.Terminal_Id =T.Terminal_Id and P.PunchType=sEventName and P.Value=DEK.nKeyIdn ) group by sEventName,DEK.nKeyIdn ,EL.nReaderIdn,T.Terminal_Id'
						delete from #Temp_PunchType;
						insert into #Temp_PunchType						
						--select * from #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                    --where nTNAEvent not in (select Value from TA_Tbl_PunchTypes )	and TerminalId not in (select TerminalId from TA_Tbl_PunchTypes)              
					end
					delete from Ta_tbl_DeviceServerDetails
			end
	--Drop temp tables
	drop table #Temp_PunchType
	end	
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Karthikeyan.R
Created On		:	05-Mar-2016
Descriptions	:	Inserting punch types directly from the device using window service (Collect Raw Data)
exec Proc_TA_InsertPunchTypes_FromDevice_New @ConnString=N'Provider=SQLOLEDB.1;Data Source=angler97\sqlexpress;Initial Catalog=biostar;User Id=sa;pwd=angler123;'
*/
CREATE proc [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New] 
@ConnString as nvarchar(Max)
as
begin
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
	BEGIN
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	--@sql2 for application db query
	DECLARE @sql2 nvarchar(max)
	--@sql1 for device db query
	DECLARE @sql1 nvarchar(max)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	--Creating temprary table for getting terminal data values 
	create table #Temp_PunchType
	(
	ID int identity(1,1),
	strName nvarchar(32),
	nTNAEvent int not null,
	ndeviceid nvarchar(10),
	TerminalId int
	)
	--**********************************************************
				SET @ConnectionString=@ConnString
				--Create table To splitup the Server and database name
				--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
				IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
					BEGIN
						INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
						SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=2				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=3)				
						UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=4)
						--select * from Ta_tbl_DeviceServerDetails			
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=5)				
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						--select * from  Ta_tbl_DeviceServerDetails
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
					END			
				SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails	
				--exec sp_addlinkedserver @ServerName;
				--creating linked server and linkedserverlogin by Manjula.P on 06-Feb-2014
				if not exists(select * from sys.servers where name = N''+@ServerName+'')
				begin
					EXEC sp_addlinkedserver @server=@ServerName
				end
					declare @suser_sname nvarchar(256)
					set  @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N'False',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------				
				select * from Ta_tbl_DeviceServerDetails			
				CREATE TABLE #test(exist int,TableName varchar(500))
				Create table #DeviceDetailsMovedToTimecheck(name varchar(50))
				--TB_EVENT_LOG,	TB_TA_DEVICE_EVENT_KEY= in BioStar Device 
				--tb_userevent = in BioAdmin Device			
				set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''TB_EVENT_LOG'',''TB_TA_DEVICE_EVENT_KEY'',''tb_userevent'')'
				Insert into #test exec(@sql)
				--select * from #test				
				--It means the connected device checked whether its BioAdmin			
				if ((select COUNT(*) from #test where TableName ='tb_userevent')>0)
					begin						
						set @sql1=''
						set @sql1=' select distinct(RL.ndeviceid),RL.ndeviceid,RL.ndeviceid,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_reportslist RL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent  where RL.ndeviceid not in('
						set @sql2=' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 ) '						
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						--INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	     --               SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType='RDBMS'),1,GETDATE(),0 from #Temp_PunchType
	     --               update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	     --               inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''
						set @sql1='select distinct(strName),UE.nIndex,ndeviceid,T.Terminal_Id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_reportslist RL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RL.nDeviceID and T.isDeleted=0 and isnumeric(Terminal_ReaderID)=1 where strName not in( '
						set @sql2=' select PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join  ['+ @ServerName +'].['+ @DatabaseName+'].dbo.tb_userevent UE on UE.nIndex=P.Value  where P.Isdeleted=0  and T.Isdeleted=0 and P.Terminal_Id=T.Terminal_Id and P.Value=UE.nindex ) group by strName,UE.nIndex,ndeviceid,T.Terminal_Id'
						delete from #Temp_PunchType;
						insert into #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                   -- where nTNAEvent not in (select Value from TA_Tbl_PunchTypes)	              
					end
				--It means the connected device checked whether its BioStar
				else if((select COUNT(*) from #test where TableName in ('TB_EVENT_LOG','TB_TA_DEVICE_EVENT_KEY'))>1)
					begin						
						set @sql1=''
						set @sql1='select distinct(EL.nReaderIdn) as strName,EL.nReaderIdn,EL.nReaderIdn as ndeviceid,0  from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_EVENT_LOG EL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  '
						set @sql1=@sql1+'  where convert(varchar(20),EL.nReaderIdn) not in( '
						set @sql2=' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )order by ndeviceid '
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
	     --               update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	     --               inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''
						set @sql1='select distinct(sEventName) as strName,DEK.nKeyIdn,EL.nReaderIdn as ndeviceid,T.Terminal_Id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_EVENT_LOG EL inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  '
						set @sql1=@sql1+'  inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=EL.nReaderIdn and T.Isdeleted=0 and isnumeric(Terminal_ReaderID)=1 where sEventName not in( '
						set @sql2=' select PunchType  from TA_Tbl_PunchTypes P  inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_TA_DEVICE_EVENT_KEY DEK on  DEK.nReaderIdn=T.Terminal_ReaderID where P.Isdeleted=0 and T.Isdeleted=0 and P.Terminal_Id =T.Terminal_Id and P.PunchType=sEventName and P.Value=DEK.nKeyIdn ) group by sEventName,DEK.nKeyIdn ,EL.nReaderIdn,T.Terminal_Id'
						delete from #Temp_PunchType;
						insert into #Temp_PunchType						
						--select * from #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE(),'S'  from  #Temp_PunchType
	                    --Insert the punch type for the default terminal like 787 and 788
						declare @InTerminalID int
						declare @OutTerminalID int
						set @InTerminalID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=787)
						set @OutTerminalID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=788)
						INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select distinct @InTerminalID,strName,nTNAEvent,0,1,GETDATE(),'S'  from  #Temp_PunchType  inner join TA_Tbl_PunchTypes on TA_Tbl_PunchTypes.Value != #Temp_PunchType.nTNAEvent and #Temp_PunchType.strName != TA_Tbl_PunchTypes.PunchType  where strName like '%IN%' and Terminal_Id=@InTerminalID 
						INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select distinct @OutTerminalID,strName,nTNAEvent,0,1,GETDATE(),'S'  from  #Temp_PunchType inner join TA_Tbl_PunchTypes on TA_Tbl_PunchTypes.Value != #Temp_PunchType.nTNAEvent and #Temp_PunchType.strName != TA_Tbl_PunchTypes.PunchType  where strName like '%OUT%' and Terminal_Id=@OutTerminalID  
					end
					--select * from #Temp_PunchType
					delete from Ta_tbl_DeviceServerDetails
	--Drop temp tables
	drop table #Temp_PunchType
	end	
end
-------------------------------
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertRawDataDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Insert employees raw data details into raw data table with reason>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertRawDataDetails]
	@CLK_CARDID nvarchar(20),	
	@CLK_DEVICEID nvarchar(20),
	@CLK_DATE datetime,
	@CLK_TIME nvarchar(20),
	@CLK_TYPE nvarchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	IF(@CLK_DATE<=dbo.DateOnly(GETDATE()))
	BEGIN
		DECLARE @ReasonId int
		DECLARE @CLK_FLAG int
		DECLARE @CLK_PROCESS int
		SET @ReasonId=0
		SET @CLK_FLAG=0
		SET @CLK_PROCESS=0
		IF NOT EXISTS(SELECT SwipeCardNo from TA_Tbl_Employee where SwipeCardNo =@CLK_CARDID and Isdeleted=0)
		BEGIN
			SELECT @ReasonId=1,@CLK_FLAG=1,@CLK_PROCESS=0
		END
		if not exists(select * from TA_Tbl_Clk_RawData where CLK_CARDID=@CLK_CARDID and CLK_DEVICEID=@CLK_DEVICEID
		and CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=@CLK_TYPE)
		BEGIN
			
			if((Select Count(*) From TA_tbl_TerminalDatatype TD inner join TA_Tbl_Terminal T on T.TerminalDatatype_ID=TD.TerminalDatatype_ID where T.Terminal_ReaderID=@CLK_DEVICEID and TD.ISUTCTime=1)>0)
			Begin
				
				select @CLK_DATE
				Select @CLK_TIME
				Declare @UTC_CLKDate dateTime
				Declare @UTC_CLKTime nvarchar(10)

				Select @UTC_CLKDate=UTC_CLKDate,@UTC_CLKTime=UTC_CLKTime From [dbo].[Fn_TA_ConvertTimeZoneDT](Convert (Date ,@CLK_DATE),@CLK_TIME,@CLK_CARDID)
				
				INSERT INTO TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS,ReasonId,TimecheckDateTime) VALUES
				(@CLK_CARDID,@CLK_DEVICEID,@UTC_CLKDate,@UTC_CLKTime,@CLK_TYPE,@CLK_FLAG,@CLK_PROCESS,@ReasonId,GETDATE())
			End
			Else
			begin
				INSERT INTO TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS,ReasonId,TimecheckDateTime) VALUES
				(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,@CLK_TYPE,@CLK_FLAG,@CLK_PROCESS,@ReasonId,GETDATE())

			End

			
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertRawDataDetails_MailTriggers]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Insert employees raw data details into raw data table with reason>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertRawDataDetails_MailTriggers]
	@CLK_CARDID nvarchar(20),	
	@CLK_DEVICEID nvarchar(20),
	@CLK_DATE datetime,
	@CLK_TIME nvarchar(20),
	@CLK_TYPE nvarchar(20),
	@CLK_EVE nvarchar(10)=null
AS
BEGIN	
	SET NOCOUNT ON;
	IF(@CLK_DATE<=dbo.DateOnly(GETDATE()))
	BEGIN
		DECLARE @ReasonId int
		DECLARE @CLK_FLAG int
		DECLARE @CLK_PROCESS int
		SET @ReasonId=0
		SET @CLK_FLAG=0
		SET @CLK_PROCESS=0
		IF NOT EXISTS(SELECT SwipeCardNo from TA_Tbl_Employee where SwipeCardNo =@CLK_CARDID and Isdeleted=0)
		BEGIN
			SELECT @ReasonId=1,@CLK_FLAG=1,@CLK_PROCESS=0
		END
		if(@CLK_EVE<>'6402')
			begin
				if not exists(select * from TA_Tbl_Clk_RawData where CLK_CARDID=@CLK_CARDID and CLK_DEVICEID=@CLK_DEVICEID
				and CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=@CLK_TYPE)
				BEGIN
					INSERT INTO TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS,ReasonId,TimecheckDateTime) VALUES
					(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,@CLK_TYPE,@CLK_FLAG,@CLK_PROCESS,@ReasonId,GETDATE())

					declare @fromDate datetime,@Todate datetime=getdate()
					set @fromDate =DATEADD(DAY,-7,@Todate)
					if(cast(@CLK_DATE as date) between cast(@fromDate as date) and cast(@Todate as date))
						begin
							EXEC Proc_Ta_SaveorupdateEmployeedetails @tag='7AEM',@EmployeeCode=@CLK_CARDID
						end
				END
			end
		else
			begin
				declare @EmployeeName nvarchar(250)=''
				if not exists(select AutoID from ta_tbl_BlockedEmployeeLogs where EmployeeCodeID=@CLK_CARDID and PunchDate=@CLK_DATE and Timestamp between DATEADD(HOUR,-1,GETDATE()) and GETDATE())
					begin
						select @EmployeeName=Employee_FirstName + ' ' + isnull(Employee_LastName,'') from ta_tbl_employee where SwipeCardNo=@CLK_CARDID
						INSERT INTO [dbo].[ta_tbl_BlockedEmployeeLogs]([EmployeeCodeID],[PunchDate],[PunchTime],[DeviceID],[ToMailID],[CCMailID],[MailContent],[Timestamp],[isMailSent]) VALUES (@CLK_CARDID ,@CLK_DATE,@CLK_TIME,@CLK_DEVICEID,'karthikeyan.r@angleritech.com','manikandan.rr@angleritech.com;Sathishkumar.S@angleritech.com','Dear Admin, <br/><br/> The Employee ' + @EmployeeName + '(' +@CLK_CARDID + ') is blocked, but he / she made the punch. In the device ' + @CLK_DEVICEID + ' at ' + @CLK_TIME + '<br/><br/><br/><br/><b>Best Regards,<br/><br/>Timecheck</b><br/><br/><br/><br/>This is system generated mail' ,getdate(),0)
					end
				
			end
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertRawDataDetailsAPIPunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertRawDataDetailsAPIPunches]
	-- Add the parameters for the stored procedure here
	@CLK_CARDID nvarchar(20),	
	@CLK_DEVICEID nvarchar(20),
	@CLK_DATE datetime,
	@CLK_TIME nvarchar(20),
	@CLK_TYPE nvarchar(20),
	@ErrorLog nvarchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	
	INSERT INTO TA_Tbl_Clk_RawDataErrorLogForAPIInsert(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,ErrorMessage) VALUES
				(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,@CLK_TYPE,@ErrorLog)



END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   procedure [dbo].[Proc_TA_InsertShift]  
(
	@levelId int,
	@ShiftId int,
	@ShiftName nvarchar(50),  
	@ShiftShortName nvarchar(50),  
	@ShiftDescription nvarchar(255),  
	@ShiftStartTime nvarchar(10),  
	@ShiftEndTime nvarchar(10),  
	@Shift_FirstHalfStartTime nvarchar(10),  
	@Shift_FirstHalfEndTime nvarchar(10),  
	@Shift_SecondHalfStartTime nvarchar(10),  
	@Shift_SecondHalfEndTime nvarchar(10),  
	@ShiftGraceInTime nvarchar(10),  
	@ShiftGraceOutTime nvarchar(10),  
	@ShiftBreakStartTime1 nvarchar(10),  
	@ShiftBreakEndTime1 nvarchar(10),  
	@ShiftBreakStartTime2 nvarchar(10),  
	@ShiftBreakEndTime2 nvarchar(10),  
	@ShiftBreakStartTime3 nvarchar(10),  
	@ShiftBreakEndTime3 nvarchar(10),  
	@ShiftMinTimeOT nvarchar(50),  
	@ShiftMaxTimeOT nvarchar(50),  
	@ShiftWorkingDayOverTime float,  
	@ShiftTotalWorkingHours nvarchar(50),  
	@Shift_FirstHalfWorkingHours nvarchar(10),    
	@Shift_SecondHalfWorkingHours nvarchar(10),    
	@Emp_ID nvarchar(50),
	@DefaultShift int,  
	@ShiftType bit,
	@24HrsShift bit,
	@isStraightShift bit,
	@StraightPresentTime nvarchar(10),
	@BreakHours nvarchar(5),
	@empCategory int=1,
	@specialOvertime_start1 varchar(10),	
	@specialOvertime_start2 varchar(10),
	@MaxShiftWorkHours varchar(10)
	
)
AS  
BEGIN  
	Declare @DefShift int
	if(@specialOvertime_start1='')
	begin
		set @specialOvertime_start1=0
	end
	if(@specialOvertime_start2='')
	begin
		set @specialOvertime_start2=0
	end
	if exists(select DefaultShift from TA_Tbl_Shift where Level_Id=@levelId and DefaultShift=1)
		begin	
			if(@DefaultShift=1)
				begin
					update ta_tbl_shift set DefaultShift=0 where Level_Id =@levelId 
				end
		end
	if(@ShiftId=0)
	begin
		INSERT INTO TA_Tbl_Shift (Level_Id, Shift_Name, Shift_ShortName, Shift_Description,Shift_StartTime,Shift_EndTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_GraceInTime,
		Shift_GraceOutTime,Shift_BreakStartTime1,Shift_BreakEndTime1,Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_BreakStartTime3,Shift_BreakEndTime3,Shift_MinTimeOT,Shift_MaxTimeOT,Shift_WorkingDay_OverTime,Shift_TotalWorkingHours,Shift_FirstHalfWorkingHours,
		Shift_SecondHalfWorkingHours,Isdeleted,Emp_ID,DefaultShift,ShiftType,[24HrsShift],CreatedDate,isStraightShift,StraightPresentTime,BreakHours,empCategory,specialOvertime_start1,specialOvertime_start2,MaxShiftWorkHours)
		VALUES(cast(@levelId as nvarchar(25)),@ShiftName,@ShiftShortName,@ShiftDescription,@ShiftStartTime,@ShiftEndTime,@Shift_FirstHalfStartTime,
		@Shift_FirstHalfEndTime,@Shift_SecondHalfStartTime,@Shift_SecondHalfEndTime,@ShiftGraceInTime,@ShiftGraceOutTime,@ShiftBreakStartTime1,
		@ShiftBreakEndTime1,@ShiftBreakStartTime2,@ShiftBreakEndTime2,@ShiftBreakStartTime3,  
		@ShiftBreakEndTime3,@ShiftMinTimeOT ,@ShiftMaxTimeOT ,cast(@ShiftWorkingDayOverTime as nvarchar(25)),@ShiftTotalWorkingHours,
		@Shift_FirstHalfWorkingHours , @Shift_SecondHalfWorkingHours ,0,@Emp_ID,cast(@DefaultShift as nvarchar(25)),cast(@ShiftType as nvarchar(1)),cast(@24HrsShift as nvarchar(1)),cast(GETDATE()as nvarchar(25)),cast(@isStraightShift as nvarchar(1)),@StraightPresentTime,@BreakHours,@empCategory,@specialOvertime_start1,@specialOvertime_start2, @MaxShiftWorkHours)
	END
	ELSE
	BEGIN
		Declare @OldGraceShiftIn nvarchar(6)
		Declare @OldGraceShiftOut nvarchar(6)
		Declare @Shift_BreakStartTime1	nvarchar(10)
		Declare @Shift_BreakEndTime1	nvarchar(10)
		Declare @Shift_BreakStartTime2	nvarchar(10)
		Declare @Shift_BreakEndTime2	nvarchar(10)
		Declare @Shift_BreakStartTime3	nvarchar(10)
		Declare @Shift_BreakEndTime3	nvarchar(10)
		select @OldGraceShiftIn=Shift_GraceInTime,@OldGraceShiftOut=Shift_GraceOutTime,@Shift_BreakStartTime1=Shift_BreakStartTime1,
		@Shift_BreakEndTime1=Shift_BreakEndTime1, @Shift_BreakStartTime2=Shift_BreakStartTime2, @Shift_BreakEndTime2=Shift_BreakEndTime2,
		@Shift_BreakStartTime3=Shift_BreakStartTime3, @Shift_BreakEndTime3=Shift_BreakEndTime3 from TA_Tbl_Shift where Shift_Id=@ShiftId
		insert into ta_tbl_GraceDetails values(@ShiftId,@OldGraceShiftIn,@OldGraceShiftOut,  @Shift_BreakStartTime1,
		@Shift_BreakEndTime1,	@Shift_BreakStartTime2,	@Shift_BreakEndTime2,	@Shift_BreakStartTime3,	@Shift_BreakEndTime3,   GETDATE())	
		
		UPDATE TA_Tbl_Shift  SET Level_Id=cast(@levelId as nvarchar(25)), Shift_Name=@ShiftName, Shift_ShortName = @ShiftShortName, Shift_Description=@ShiftDescription,Shift_StartTime=@ShiftStartTime,
		Shift_EndTime=@ShiftEndTime,Shift_FirstHalf_StartTime=@Shift_FirstHalfStartTime,Shift_FirstHalf_EndTime=@Shift_FirstHalfEndTime,Shift_SecondHalf_StartTime=@Shift_SecondHalfStartTime,Shift_SecondHalf_EndTime=
		@Shift_SecondHalfEndTime,Shift_GraceInTime=@ShiftGraceInTime,Shift_GraceOutTime=@ShiftGraceOutTime,Shift_BreakStartTime1=@ShiftBreakStartTime1,Shift_BreakEndTime1=@ShiftBreakEndTime1,Shift_BreakStartTime2=
		@ShiftBreakStartTime2,Shift_BreakEndTime2=@ShiftBreakEndTime2,Shift_BreakStartTime3 =@ShiftBreakStartTime3,Shift_BreakEndTime3=@ShiftBreakEndTime3 ,Shift_MinTimeOT=  @ShiftMinTimeOT , Shift_MaxTimeOT= @ShiftMaxTimeOT ,
		Shift_WorkingDay_OverTime=cast(@ShiftWorkingDayOverTime as nvarchar(25)),Shift_TotalWorkingHours=@ShiftTotalWorkingHours,Shift_FirstHalfWorkingHours=@Shift_FirstHalfWorkingHours,Shift_SecondHalfWorkingHours=
		@Shift_SecondHalfWorkingHours,Emp_ID= @Emp_ID,DefaultShift=cast(@DefaultShift as nvarchar(25)),ShiftType= cast(@ShiftType as nvarchar(1)) ,ModifiedDate= cast(GETDATE() as nvarchar(25))  ,isStraightShift=cast(@isStraightShift as nvarchar(25)),StraightPresentTime=@StraightPresentTime,
		BreakHours=@BreakHours,empCategory=@empCategory ,
		specialOvertime_start1=@specialOvertime_start1,		
		specialOvertime_start2=@specialOvertime_start2,
		MaxShiftWorkHours = @MaxShiftWorkHours
		,[24HrsShift] = cast(@24HrsShift as nvarchar(1))-- aded by velumani observed on ADNIP support on 31-jan-2020
		WHERE Shift_Id=cast(@ShiftId as nvarchar(25))	   
	END
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_InsertShiftAllocation 2014,8,1,'05/02/2011 09:07:50 AM','05/01/2011',
--declare @p6 xml
--set @p6=convert(xml,N'<DocumentElement><Table><EmpID>25</EmpID><EmployeeId>787</EmployeeId><EmployeeName>Manikandan Rajendran</EmployeeName><LoginEmployeeId>1</LoginEmployeeId><OverLapped>false</OverLapped></Table></DocumentElement>')
--exec Proc_TA_InsertShiftAllocation @Year=2014,@Month=8,@UserId=1,@EntryDate=N'08/25/2019 11:49:55 AM',@DateShift=N'8/1/2014',@xml=@p6
--Select * from TA_Tbl_PermanentShiftAllocation Where EmployeeId=25 and Month=8
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftAllocation] 
(
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nVarchar(25),
   @DateShift nVarchar(25),
   @xml xml
)
AS
BEGIN
	  --create table #TempEmployeeDetails(EmployeeID int)
	  Declare @Index int
	  Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into TA_Tbl_PermanentShiftAllocation (EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift)
		  select EmpID,cast(@Year as nvarchar),cast(@Month as nvarchar),cast(@UserId as nvarchar),@EntryDate,@DateShift 
		  from OpenXML(@Index, '/DocumentElement/Table')
		  With (EmpID Bigint 'EmpID') 
		  where not exists (select EmployeeId  FROM TA_Tbl_PermanentShiftAllocation WHERE EmployeeId = EmpID AND [Year] = @Year AND [Month] = @Month)
	  Exec sp_xml_removedocument @Index
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftExchange]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_InsertShiftExchange  
Description		:	To Insert the Shift Exchange Employees
Tables Included	:	TA_Tbl_ShiftExchange
Created By			:	Sasireka  
Created On			:	13-Jan-2009 
Modified By		:	A.K.T.MOORTHI
Modified On		:	08-Jan-2014
Description		:	Reprocess The Selected Date.
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_InsertShiftExchange](
	@levelid INT,
	@Date DATETIME,
	@Employee1_Id INT,
	@Employee1_ActualShiftId INT,
	@Employee2_Id INT,
	@Employee2_ActualShiftId INT,
	@Emp_id INT,
	@EntryDate NVARCHAR(15),
	@YearSettingsId INT)
AS
BEGIN
	INSERT INTO TA_Tbl_ShiftExchange(Level_Id, [Date], Employee1_Id, Employee1_ActualShift, Employee2_Id, Employee2_ActualShift, Emp_Id, [TimeStamp], YearSettings_Id)
		VALUES(CAST(@levelId AS NVARCHAR(25)), CAST(@date AS NVARCHAR(20)), CAST(@Employee1_Id AS NVARCHAR(20)), CAST(@Employee1_ActualShiftId AS NVARCHAR(20)), CAST(@Employee2_Id AS NVARCHAR(20)), CAST(@Employee2_ActualShiftId AS NVARCHAR(20)), CAST(@Emp_id AS NVARCHAR(20)), CAST(@EntryDate AS NVARCHAR(20)), CAST(@YearSettingsId AS NVARCHAR(20)))
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData PD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = PD.Employee_Code_Id 
	WHERE PD.[Date] = @Date AND E.Employee_Id IN (@Employee1_Id, @Employee2_Id)
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = CD.Clk_EmpId
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND (CD.Clk_Date = @Date OR CD.Clk_InDate = @Date OR CD.Clk_OutDate = @Date)
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' FROM TA_Tbl_ManualTimeEntry ME
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = ME.ManualTimeEntry_Employee_Id
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND ((ME.ManualTimeEntry_InDate = @Date) OR (ME.ManualTimeEntry_OutDate = @Date))
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = RD.CLK_CARDID
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND RD.CLK_DATE = @Date
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- ALTER  date: <Create Date,,30-June-2007>
-- Description:	<Description,,Inserting Shift Roaster>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftPattern]
(@companyId int,@PatternName nvarchar(50),@Nodays int,@Day1_ShiftId int,@Day2_ShiftId int,@Day3_ShiftId int,@Day4_ShiftId int,
 @Day5_ShiftId int,@Day6_ShiftId int,@Day7_ShiftId int,@Day8_ShiftId int,@Day9_ShiftId int,@Day10_ShiftId int,@Day11_ShiftId int,@Day12_ShiftId int,
 @Day13_ShiftId int,@Day14_ShiftId int,@Day15_ShiftId int,@Day16_ShiftId int,@Day17_ShiftId int,@Day18_ShiftId int,@Day19_ShiftId int,@Day20_ShiftId int,
 @Day21_ShiftId int,@Day22_ShiftId int,@Day23_ShiftId int,@Day24_ShiftId int,@Day25_ShiftId int,@Day26_ShiftId int,@Day27_ShiftId int,@Day28_ShiftId int,
 @Day29_ShiftId int,@Day30_ShiftId int,@Day31_ShiftId int,@Employee_Id int)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
--	INSERT INTO TA_Tbl_ShiftPattern(Pattern_Name,Shift_days,Day1_Shift,Day2_Shift,Day3_Shift,Day4_Shift,Day5_Shift ,Day6_Shift,Day7_Shift,Day8_Shift,
--								Day9_Shift,Day10_Shift,Day11_Shift,Day12_Shift,Day13_Shift,Day14_Shift,Day15_Shift,Day16_Shift,Day17_Shift,
--								Day18_Shift,Day19_Shift,Day20_Shift,Day21_Shift,Day22_Shift,Day23_Shift,Day24_Shift,Day25_Shift,Day26_Shift,
--								Day27_Shift,Day28_Shift,Day29_Shift,Day30_Shift,Day31_Shift,Emp_Id,Isdeleted) VALUES (@PatternName,
--								@Nodays,@Day1_ShiftId,@Day2_ShiftId,@Day3_ShiftId,@Day4_ShiftId,@Day5_ShiftId,@Day6_ShiftId,@Day7_ShiftId,
--								@Day8_ShiftId,@Day9_ShiftId,@Day10_ShiftId,@Day11_ShiftId,@Day12_ShiftId,@Day13_ShiftId,@Day14_ShiftId,	
--								@Day15_ShiftId,@Day16_ShiftId,@Day17_ShiftId,@Day18_ShiftId,@Day19_ShiftId,@Day20_ShiftId,@Day21_ShiftId,
--								@Day22_ShiftId,@Day23_ShiftId,@Day24_ShiftId,@Day25_ShiftId,@Day26_ShiftId,@Day27_ShiftId,@Day28_ShiftId,
--								@Day29_ShiftId,@Day30_ShiftId,@Day31_ShiftId,@Employee_Id,@Isdel)
set @sql = 'INSERT INTO TA_Tbl_ShiftPattern(Level_Id,Pattern_Name,Shift_days,Day1_Shift,Day2_Shift,Day3_Shift,Day4_Shift,Day5_Shift ,Day6_Shift,Day7_Shift,Day8_Shift,
                                            Day9_Shift,Day10_Shift,Day11_Shift,Day12_Shift,Day13_Shift,Day14_Shift,Day15_Shift,Day16_Shift,Day17_Shift,
                                            Day18_Shift,Day19_Shift,Day20_Shift,Day21_Shift,Day22_Shift,Day23_Shift,Day24_Shift,Day25_Shift,Day26_Shift,
                                            Day27_Shift,Day28_Shift,Day29_Shift,Day30_Shift,Day31_Shift,Emp_Id,Isdeleted)
                                            VALUES('+cast(@companyId as nvarchar(25))+',N'''+@PatternName+''','+cast(@Nodays as nvarchar(25))+','+cast(@Day1_ShiftId as nvarchar(25))+','+cast(@Day2_ShiftId as nvarchar(25))+',
                                            '+cast(@Day3_ShiftId as nvarchar(25))+','+cast(@Day4_ShiftId as nvarchar(25))+','+cast(@Day5_ShiftId as nvarchar(25))+','+cast(@Day6_ShiftId as nvarchar(25))+',
                                            '+cast(@Day7_ShiftId as nvarchar(25))+','+cast(@Day8_ShiftId as nvarchar(25))+','+cast(@Day9_ShiftId as nvarchar(25))+','+cast(@Day10_ShiftId as nvarchar(25))+',
                                            '+cast(@Day11_ShiftId as nvarchar(25))+','+cast(@Day12_ShiftId as nvarchar(25))+','+cast(@Day13_ShiftId as nvarchar(25))+','+cast(@Day14_ShiftId as nvarchar(25))+',
                                            '+cast(@Day15_ShiftId as nvarchar(25))+','+cast(@Day16_ShiftId as nvarchar(25))+','+cast(@Day17_ShiftId as nvarchar(25))+','+cast(@Day18_ShiftId as nvarchar(25))+',
                                            '+cast(@Day19_ShiftId as nvarchar(25))+','+cast(@Day20_ShiftId as nvarchar(25))+','+cast(@Day21_ShiftId as nvarchar(25))+','+cast(@Day22_ShiftId as nvarchar(25))+',
                                            '+cast(@Day23_ShiftId as nvarchar(25))+','+cast(@Day24_ShiftId as nvarchar(25))+','+cast(@Day25_ShiftId as nvarchar(25))+','+cast(@Day26_ShiftId as nvarchar(25))+',
                                            '+cast(@Day27_ShiftId as nvarchar(25))+','+cast(@Day28_ShiftId as nvarchar(25))+','+cast(@Day29_ShiftId as nvarchar(25))+','+cast(@Day30_ShiftId as nvarchar(25))+',
                                            '+cast(@Day31_ShiftId as nvarchar(25))+','+cast(@Employee_Id as nvarchar(25))+','+cast(@Isdel as nvarchar(25))+')'
exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftRoaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,30-June-2007>
-- Description:	<Description,,Inserting Shift Pattern>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftRoaster]
(@companyId int,@RoasterName nvarchar(25),@NoOfPatterns int,@Pattern1 int,@Pattern2 int,@Pattern3 int,@Pattern4 int,
 @Pattern5 int,@Pattern6 int,@Pattern7 int,@Pattern8 int,@Pattern9 int,@Pattern10 int,@Employee_Id int)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
--	INSERT INTO TA_Tbl_ShiftRoaster(ShiftRoaster_Name,NumberOfPatterns,Pattern1,Pattern2,Pattern3,Pattern4,Pattern5 ,Pattern6,Pattern7,Pattern8,
--								Pattern9,Pattern10,Emp_Id,Isdeleted) VALUES (@RoasterName,
--								@NoOfPatterns,@Pattern1,@Pattern2,@Pattern3,@Pattern4,@Pattern5,@Pattern6,@Pattern7,
--								@Pattern8,@Pattern9,@Pattern10,@Employee_Id,@Isdel)
    set @sql = 'INSERT INTO TA_Tbl_ShiftRoaster(Level_Id,ShiftRoaster_Name,NumberOfPatterns,Pattern1,Pattern2,Pattern3,Pattern4,Pattern5 ,Pattern6,Pattern7,Pattern8,Pattern9,Pattern10,Emp_Id,Isdeleted) 
                VALUES('+cast(@companyId as nvarchar(25))+',N'''+@RoasterName+''','+cast(@NoOfPatterns as nvarchar(25))+','+cast(@Pattern1 as nvarchar(25))+','+cast(@Pattern2 as nvarchar(25))+','+cast(@Pattern3 as nvarchar(25))+',
                       '+cast(@Pattern4 as nvarchar(25))+','+cast(@Pattern5 as nvarchar(25))+','+cast(@Pattern6 as nvarchar(25))+','+cast(@Pattern7 as nvarchar(25))+','+cast(@Pattern8 as nvarchar(25))+',
                       '+cast(@Pattern9 as nvarchar(25))+','+cast(@Pattern10 as nvarchar(25))+','+cast(@Employee_Id as nvarchar(25))+','+cast(@Isdel as nvarchar(25))+')'
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_InsertSMSLogDetails 3,'Rajendran','103-Manikandan-03:00,104-Anbu-03:00',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetails]
	-- Add the parameters for the stored procedure here
	@TemplateID int,
	@Receivers varchar(250),
	@ExceptionEmployees varchar(max),
	@Status int,
	@Message varchar(max),
	@ShiftID int,
	@StatusMessage varchar(max),
	@NextTriggeringTime varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Insert into TA_Tbl_SMSLogDetails values(@TemplateID,CONVERT(datetime, CONVERT(varchar(10),getdate(),111)),@Receivers,@NextTriggeringTime,@Status,@StatusMessage,@ShiftID,@Message,GETDATE())
	Declare @id int
	set @id=@@IDENTITY
	if(@ExceptionEmployees!='')
	begin
		Insert into TA_Tbl_SMSLogChild 
		select @id,Value from dbo.Split(@ExceptionEmployees,',')
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(100),
	@Receivers varchar(250),
	@EmployeeID varchar(50),
	@Status bit,
	@Message varchar(max),	
	@StatusMessage varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @TemplateID int
	select @TemplateID=id from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName and Status=1
    -- Insert statements for procedure here
	Insert into TA_Tbl_SMSLogDetails values(@TemplateID,CONVERT(datetime, CONVERT(varchar(10),getdate(),111)),@Receivers,'',@Status,@StatusMessage,0,@Message,GETDATE())
	Declare @id int
	set @id=@@IDENTITY
	Insert into TA_Tbl_SMSLogChild 
	select @id,@EmployeeID	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSpousedetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_InsertSpousedetails] 
(
	@EmpID INT=0,
	@spousename NVARCHAR(50),
	@spousedob NVARCHAR(15),
	@EmployeeID INT=0
)
AS
BEGIN
	declare @sql as nvarchar(3000)
	IF (@spousedob='')
	BEGIN
		SET @spousedob=NULL
	END
	set @sql = 'INSERT INTO TA_Tbl_EmpChildrenDetails(Emp_ID,Spouse_Child,Name,DOB,Isdeleted,Employee_ID) 
	VALUES ('+cast(@EmpID as nvarchar(25))+',''S'',N'''+@spousename+''',N'''+@spousedob+''',0,'+cast(@EmployeeID as nvarchar(25))+')'
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_InsertTA_Tbl_LIC_Details  
Description : insert into TA_Tbl_LIC_Details for license information    
Tables Included : TA_Tbl_LIC_Details  
Created By : Christopher S 
Created On : 19-Mar-2008  
Modified By :  
Modified On :  
*/
-- Proc_TA_InsertTA_Tbl_LIC_Details '','','','','','','','','','','','','','','',''
CREATE PROCEDURE [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details] 
	-- Add the parameters for the stored procedure here
	@customerId nvarchar(200),		
	@packageId nvarchar(200),
	@packageVersion nvarchar(200),
	@noOfConcurrentUser nvarchar(200),
	@noOfEmployee nvarchar(200),
    @noOfTerminal nvarchar(200),
	@macAddress nvarchar(200),	
	@licenseGenerationDate nvarchar(200),
	@expiryDate nvarchar(200),
	@module nvarchar(200),
	@module1 nvarchar(200),
	@module2 nvarchar(200),
	@module3 nvarchar(200),
	@module4 nvarchar(200),
	@module5 nvarchar(200),
    @pageStatusFalse nvarchar(1000)
AS
DECLARE @query as nvarchar(4000)
SET @query = ''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_LIC_Details
	IF(@pageStatusFalse<>'')
		BEGIN
			SET @query = 'DELETE FROM TA_Tbl_userRights WHERE pageId IN ('+@pageStatusFalse+')'
			EXEC (@query)
		END        
     DELETE FROM TA_Tbl_Page
	INSERT INTO TA_Tbl_LIC_Details(CustomerId, PackageId, PackageVersion, NoOfConcurrentUser, NoOfEmployee, NoOfTerminal, MACAddress, LicenseGenerationDate, ExpiryDate, Module, Module1, Module2, Module3, Module4, Module5) VALUES(@customerId, @packageId, @packageVersion, @noOfConcurrentUser, @noOfEmployee, @noOfTerminal, @macAddress, @licenseGenerationDate, @expiryDate, @module, @module1, @module2, @module3, @module4, @module5)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTATblPage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_InsertTATblPage  
Description : insert into TA_Tbl_Page for licensed modules    
Tables Included : TA_Tbl_Page  
Created By : Christopher S 
Created On : 17-Mar-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InsertTATblPage]
	-- Add the parameters for the stored procedure here
	@pageId float,
	@displayName nvarchar(100),
	@path nvarchar(200),
	@parentId int,
	@orderBy float
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @pageCount as int
	SET @pageCount = (SELECT COUNT(*) FROM TA_Tbl_Page WHERE pageId = @pageId)
	IF(@pageCount=0)
		BEGIN
			INSERT INTO TA_Tbl_Page(pageId, displayName, path, parentId, orderBy) VALUES(@pageId, @displayName, @path, @parentId, @orderBy)
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTaxPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth S>
-- Create date: <Create Date,,28-Nov-2022>
-- Description:	<Description,, Poyroll Tds Value Insert>
 -- select * From TA_Tbl_TaxMasterDetails
-- exec Proc_TA_InsertTaxPolicy @tag='P',@TaxPolicyID=127
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertTaxPolicy] 
	-- Add the parameters for the stored procedure here

	@tag char(3),
	@TaxPolicyName nvarchar(30)=null,
	@EmployeeCategory INT=null,
	@EmployeeType INT =null,
	@Gender VARCHAR(10)=null,
	@companyID int=null,
	@Employee_Id INT=null,
	@TdsSlabCount int=null,
	@ProfSlabCount int=null,
	@TaxPolicyID int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	if(@tag='I')
	Begin
		Insert into TA_Tbl_TaxMasterDetails (TaxPolicyName,companyId,EmployeeCategory,EmployeeType,Gender,isDeleted,Created_By,Created_DateTime,Modify_DateTime,isTdsflag,isProfessflag,TdsSlabCount) Values
		(@TaxPolicyName,@companyID,@EmployeeCategory,@EmployeeType,@Gender,0,@Employee_Id,CURRENT_TIMESTAMP,null,Case when @TdsSlabCount=0 then 0 Else 1 End, Case when @ProfSlabCount=0 then 0 Else 1 End,Case when @TdsSlabCount='' then 0 Else @TdsSlabCount End)
		Select TaxPolicy_Id as PolicyID From TA_Tbl_TaxMasterDetails order by TaxPolicy_Id desc
	End

	Else IF(@tag='U')
	Begin
		
		Update TA_Tbl_TaxMasterDetails set TaxPolicyName=@TaxPolicyName,EmployeeCategory=@EmployeeCategory,EmployeeType=@EmployeeType,Gender=@Gender,companyid=@companyID,TdsSlabCount=@TdsSlabCount,Modify_DateTime=CURRENT_TIMESTAMP where TaxPolicy_Id=@TaxPolicyID
		Select TaxPolicy_Id as PolicyID From TA_Tbl_TaxMasterDetails order by TaxPolicy_Id desc
	End

	Else If(@tag='CP')
	Begin
		
		Select TaxPolicyName From TA_Tbl_TaxMasterDetails where TaxPolicyName=@TaxPolicyName

	END

	Else if(@tag='SL')
	Begin
		
		if(isNull(@TaxPolicyID,0)=0)
		begin
			
			Select TaxPolicy_Id,TaxPolicyName,1 as flag From TA_Tbl_TaxMasterDetails  
		End
		Else
		Begin
			Select TaxPolicy_Id From TA_Tbl_TaxMasterDetails where TaxPolicy_Id= @TaxPolicyID
		End

	End

	Else IF(@tag='P')
	Begin
				SELECT MD.TaxPolicy_Id,MD.TaxPolicyName,MD.companyid ,MD.EmployeeType,MD.EmployeeCategory, MD.Gender,MD.TdsSlabCount,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,1 as flag,CompanyName=ISNULL(LD.name,'') into #tempTaxPolicy 
					FROM TA_Tbl_TaxMasterDetails MD
					Left Outer join Ta_Tbl_levelDetails LD on MD.companyid=LD.id where MD.TaxPolicy_Id=@TaxPolicyID


					Update #tempTaxPolicy set flag=0 from #tempTaxPolicy TL inner join TA_Tbl_Emp_TaxPolicy ETP on TL.TaxPolicy_Id=ETP.TaxPolicy_Id
					
					select * from #tempTaxPolicy	
					
					Select TS.Tds_SlabNo,TS.Tds_RangeFrom,TS.Tds_RangeTo,TS.Tds_Percentage,TS.Tds_CessPercentage into #tempTdsSlab From TA_Tbl_TDSSlab TS Inner Join TA_Tbl_TaxMasterDetails TM on TS.Tax_PolicyId=TM.TaxPolicy_Id where TS.Tax_PolicyId=@TaxPolicyID

					Select * From #tempTdsSlab

					Select TP.Prof_SlabName,TP.Prof_RangeFrom,TP.Prof_RangeTO,TP.Prof_Amount,TP.IsPercentage into #tempProfSlab From TA_Tbl_ProfSlab TP Inner Join TA_Tbl_TaxMasterDetails TM on TP.Tax_PolicyId=TM.TaxPolicy_Id where TP.Tax_PolicyId=@TaxpolicyID

					Select * From #tempProfSlab

					-- Drop Table #tempTdsSlab
					-- Drop Table #tempTaxPolicy
					-- Drop Table #tempProfSlab
	End

	Else if(@tag='D')
	Begin
		if(@TaxPolicyID!=' ')
		begin
			Delete From TA_Tbl_TaxMasterDetails where TaxPolicy_Id=@TaxPolicyID

			Delete From TA_Tbl_TDSSlab where Tax_PolicyId=@TaxPolicyID

			Delete From TA_Tbl_ProfSlab where Tax_PolicyId=@TaxPolicyID

			select '1' as D_count
		End
		else
		begin
			select '0' as D_count
		end
	End
	
END



GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation]
(
   @EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nvarchar(15),
   @DateShift nvarchar(15)
)
 AS
BEGIN
declare @sql nvarchar(3000)
	set @sql='INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES (''' + cast(@EmpId as nvarchar(25)) + ''',''' + cast(@Year as nvarchar(50)) + ''',''' + cast(@Month as nvarchar(50)) + ''',''' + cast(@UserId as nvarchar(50)) + ''',N''' + @EntryDate + ''',N''' + @DateShift + ''')'
Exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]
(
   --@EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nvarchar(15),
   @DateShift nvarchar(15),
   @xml xml
)
 AS
BEGIN
 Declare @Index int
	  Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into TA_Tbl_TemporaryShiftAllocation (EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift)
		  select EmpID,cast(@Year as nvarchar),cast(@Month as nvarchar),cast(@UserId as nvarchar),@EntryDate,@DateShift 
		  from OpenXML(@Index, '/DocumentElement/Table')
		  With (EmpID Bigint 'EmpID') 
		  where not exists (select EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = EmpID AND [Year] = @Year AND [Month] = @Month)
	  Exec sp_xml_removedocument @Index
--if not exists(SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month)
--BEGIN
--	declare @sql nvarchar(3000)
--		set @sql='INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES (''' + cast(@EmpId as nvarchar(25)) + ''',''' + cast(@Year as nvarchar(50)) + ''',''' + cast(@Month as nvarchar(50)) + ''',''' + cast(@UserId as nvarchar(50)) + ''',N''' + @EntryDate + ''',N''' + @DateShift + ''')'
--	Exec(@sql)
--END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertTempShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate Varchar(15),
   @DateShift Varchar(15)
)
 AS
BEGIN
               INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES (@EmpId,@Year,@Month,@UserId,@EntryDate,@DateShift)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempWeekday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Manjula.P
Modified On		:	27-Dec-2013
Descriptions	:	Adding ShiftId parameter in TA_Tbl_TemWeekday tables and procedures
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertTempWeekday]
(
@TempWeekdayFromDate nvarchar(20),
@TempWeekdayToDate nvarchar(20),
@ClosingTime nvarchar(15),
@Reason nvarchar(255),
@Employee_Id int,
@XMLdata xml,
@TempWeeklyoffId int,
---Added by Manjula.P on 27-Dec-2013 for adding shiftId parameter
@ShiftId nvarchar(max)
)
AS
BEGIN
	declare @sql nvarchar(500)
	SET NOCOUNT ON;
	declare @TempId int
	DECLARE @Index int
	if(@TempWeeklyoffId  <>0)
		BEGIN
			select TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason from TA_Tbl_TemWeekday 
			where TempWeekday_Id=@TempWeeklyoffId		
			select LevelId from Ta_Tbl_Temporary_WeeklyOff_Levels where TempWeekday_Id=@TempWeeklyoffId		
		END
	ELSE
		BEGIN
			INSERT INTO TA_Tbl_TemWeekday(TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason,Emp_Id,Isdeleted,ShiftId) 
			VALUES(@TempWeekdayFromDate,@TempWeekdayToDate,@ClosingTime,@Reason,@Employee_Id,0,@ShiftId)
			set @TempId= (select @@Identity)	
			set @Index = 0 
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO Ta_Tbl_Temporary_WeeklyOff_Levels
			select @TempId, xm.LevelId from OPENXML(@Index, '/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels')
			with (LevelId int 'LevelId') as xm
			exec sp_xml_removedocument @Index
			--UPDATE TA_Tbl_ProcessedData SET ProcessFlag=0 FROM TA_Tbl_ProcessedData P 
			--INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON P.LevelId=WL.LevelId 
			--inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id
			--WHERE WL.TempWeekday_Id=@TempId and P.date between TW.TempWeekday_FromDate
			--and TempWeekday_ToDate			
			Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
			select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
			inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
			INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId 
			inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id
			WHERE WL.TempWeekday_Id=@TempId) as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
			and TemEmployee.TempWeekday_ToDate			
			select '1' 		
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDatatype]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
/********************************************************************
    Purpose  - Inserting and Updating Terminal DataTypes
    Author     - Kumuthini.L 
   Proc_TA_InsertTerminalDatatype	'U',40,'RDBMS-001','RDBMS','','','',0,'','','','',2,'','','','','',0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,'Provider=SQLOLEDB.1;Data Source=Angler39\sqlexpress;Initial Catalog=BioAdminDataSQL1;User Id=epic;pwd=epic;','tb_reportslist','','',2,'','','','','','ndeviceid','nuserid',1,'','','dtDateTime','nTNAEvent','nEvent','susername',0,'mm/dd/yyyy hh:mm:ss ttsdf','','',0,1,55,1,'10/13/2008 15:53:05 PM'
**********************************************************************/
CREATE PROCEDURE 	[dbo].[Proc_TA_InsertTerminalDatatype]
(
	@type CHAR(1),
	@TerminalDatatypeId INT=0,
	@RawDataFormat NVARCHAR(25),
	@FileType NVARCHAR(15), 
	@FileSourcePath NVARCHAR(2000), 
	@FileBackupPath NVARCHAR(2000), 
	@FileBackupType NVARCHAR(10), 
	@NoOfFields INT, 
	@Delimiter CHAR(5),  
	@StringEnclosedBy CHAR(5),  
	@Del_ReaderNo NVARCHAR(10),  
	@Del_CardNo NVARCHAR(10),  
	@Del_DateTimeBit int,  
	@Del_Date NVARCHAR(10),  
	@Del_Time NVARCHAR(10),  
	@Del_DateTime NVARCHAR(10),  
	@Del_Type NVARCHAR(10),  
	@Del_TransIdentifier NVARCHAR(10),
	@FL_ReaderNoFrom INT,  
	@FL_ReaderNoTo INT,   
	@FL_CardNoFrom INT,  
	@FL_CardNoTo INT,  
	@FL_DateTimeBit INT,  
	@FL_DateFrom INT,  
	@FL_DateTo INT,  
	@FL_TimeFrom INT,  
	@FL_TimeTo INT,  
	@FL_DateTimeFrom INT,  
	@FL_DateTimeTo INT,  
	@FL_TypeFrom INT,  
	@FL_TypeTo INT,  
	@FL_TransIdentifierFrom INT,  
	@FL_TransIdentifierTo INT,  
	@ConnectionString  NVARCHAR(2000),  
	@TableName NVARCHAR(50),  
	@MDB_ReaderNo NVARCHAR(25),  
	@MDB_CardNo NVARCHAR(25),  
	@MDB_DateTimeBit INT,  
	@MDB_Date NVARCHAR(25),   
	@MDB_Time NVARCHAR(25),  
	@MDB_DateTime NVARCHAR(25),  
	@MDB_Type NVARCHAR(25), 
	@MDB_TransIdentifier NVARCHAR(25), 
	@RDBMS_ReaderNo NVARCHAR(25),  
	@RDBMS_CardNo NVARCHAR(25),  
	@RDBMS_DateTimeBit INT,
	@RDBMS_Date NVARCHAR(25), 
	@RDBMS_Time NVARCHAR(25),
	@RDBMS_DateTime NVARCHAR(25), 
	@RDBMS_Type NVARCHAR(25), 
	@RDBMS_TransIdentifier NVARCHAR(25), 
	@RDBMS_MDB_Flag NVARCHAR(25),
	@IsEmployeeIdBit INT,
	@DateTimeFormat NVARCHAR(40),
	@DateFormat NVARCHAR(15),
	@TimeFormat NVARCHAR(15),
	@IsEncryptedBit INT,
	@TransactionIdentifierBit INT,
	@TransactionIdentifierValue NVARCHAR(50),
	@Empid  INT,
	@BrandType varchar(500),
	@IsFreeScan varchar(500),
	@IsUTC int=0
)
AS
BEGIN
	declare @EntryDate as datetime
	set @EntryDate=getdate()
	DECLARE @sql AS NVARCHAR(2000)
	IF (@type='I')
	BEGIN
	  declare @BrandId as int
	  set @BrandId=(select BrandID from TA_Tbl_TerminalBrand where KeyValue=@BrandType)  	  
	  SET @sql='INSERT INTO TA_tbl_TerminalDatatype (Raw_Data_Format,FileType,File_SourcePath,File_BackupPath,File_BackupType,Delimiter_NoOfFields,Delimiter_Delimiter,Delimiter_StringEnclosedBy,Delimiter_ReaderNo,'
	  SET @sql=@sql + 'Delimiter_CardNo,Delimiter_DateTimeBit,Delimiter_Date,Delimiter_Time,Delimiter_DateTime,Delimiter_Type,Delimiter_TransactionIdentifier,FixedLength_ReaderNoFrom,FixedLength_ReaderNoTo,FixedLength_CardNoFrom,'
	  SET @sql=@sql + ' FixedLength_CardNoTo,FixedLength_DateTimeBit,FixedLength_DateFrom,FixedLength_DateTo,FixedLength_TimeFrom,FixedLength_TimeTo,FixedLength_DateTimeFrom,FixedLength_DateTimeTo,FixedLength_TypeFrom,'
	  SET @sql=@sql + ' FixedLength_TypeTo,FixedLength_TransactionIdentifierFrom,FixedLength_TransactionIdentifierTo,ConnectionString,TableName,MDB_ReaderNo,MDB_CardNo,MDB_DateTimeBit,MDB_Date,MDB_Time,MDB_DateTime,'
	  SET @sql=@sql + ' MDB_Type,MDB_TransactionIdentifier,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_Date,RDBMS_Time,RDBMS_DateTime,RDBMS_Type,RDBMS_TransactionIdentifier,RDBMS_MDB_Flag,IsEmployeeId,DateTimeFormat,DateFormat,TimeFormat,IsEncrypted,'
	  SET @sql=@sql + ' TransactionIdentifierBit,TransactionIdentifierValue,Emp_Id,[TimeStamp],IsDeleted,BrandID,IsFreeScan,ISUTCTime) VALUES( ' 
	  SET @sql=@sql + ' N''' + @RawDataFormat + ''',N''' + @FileType + ''',N''' + @FileSourcePath + ''',N''' + @FileBackupPath + ''','''  
	  SET @sql=@sql + @FileBackupType + ''',' + cast(@NoOfFields as nvarchar(20)) + ',''' + @Delimiter + ''',''' +  @StringEnclosedBy + ''', N''' + @Del_ReaderNo + ''', N''' + @Del_CardNo + ''', ' 
	  SET @sql=@sql + cast(@Del_DateTimeBit as nvarchar(20)) + ',N''' + @Del_Date + ''',N''' + @Del_Time + ''' '
	  SET @sql=@sql + ',N'''  + @Del_DateTime + ''',N''' + @Del_Type + ''',''' + @Del_TransIdentifier +''' '
	  SET @sql=@sql + ','+ cast(@FL_ReaderNoFrom as nvarchar(20)) + ',' + cast(@FL_ReaderNoTo as nvarchar(20)) + ',' + cast(@FL_CardNoFrom as nvarchar(20)) + ',' + cast(@FL_CardNoTo as nvarchar(20)) + ',' + cast(@FL_DateTimeBit as nvarchar(20)) + ',' + cast(@FL_DateFrom as nvarchar(20)) + ',' + cast(@FL_DateTo as nvarchar(20)) + ',' + cast(@FL_TimeFrom as nvarchar(20)) + ', '
	  SET @sql=@sql + cast(@FL_TimeTo as nvarchar(20)) + ',' + cast(@FL_DateTimeFrom as nvarchar(20)) + ',' + cast(@FL_DateTimeTo as nvarchar(20))+ ',' + cast(@FL_TypeFrom as nvarchar(20)) + ',' + cast(@FL_TypeTo as nvarchar(20)) + ',' + cast(@FL_TransIdentifierFrom as nvarchar(20)) + ',' + cast(@FL_TransIdentifierTo as nvarchar(20)) +',N''' + @ConnectionString + ''',N''' + @TableName + ''',N''' + @MDB_ReaderNo + ''',N''' + @MDB_CardNo + ''',' + cast(@MDB_DateTimeBit as nvarchar(20)) + ',N''' + @MDB_Date + ''',N''' +  @MDB_Time + ''',  '
	  SET @sql=@sql + 'N''' + @MDB_DateTime + ''',N''' + @MDB_Type + ''',''' + @MDB_TransIdentifier + ''',N''' + @RDBMS_ReaderNo + ''',N''' + @RDBMS_CardNo + ''',' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + ',N''' + @RDBMS_Date + ''', N''' + @RDBMS_Time + ''',N''' + @RDBMS_DateTime + ''',N''' + @RDBMS_Type + ''',''' + @RDBMS_TransIdentifier + ''',''' + @RDBMS_MDB_Flag + ''',' + cast(@IsEmployeeIdBit as nvarchar(5)) + ',''' + @DateTimeFormat + ''',''' + @DateFormat + ''',''' + @TimeFormat + ''',' + cast(@IsEncryptedBit as nvarchar(5)) + ',' + cast(@TransactionIdentifierBit as nvarchar(10)) + ',''' + @TransactionIdentifierValue +''',' + cast(@Empid as nvarchar(20)) + ',''' + cast(@EntryDate as nvarchar(20)) + ''',0,''' + cast(@BrandId as nvarchar(20)) + ''',''' + cast(@IsFreeScan as nvarchar(4))+ ''','+cast(@IsUTC as nvarchar(4))+')'
	END
	ELSE IF (@type='U')
	BEGIN		
		SET @sql='UPDATE TA_tbl_TerminalDatatype SET File_SourcePath=N''' + @FileSourcePath + ''',File_BackupPath=N''' + @FileBackupPath + ''',File_BackupType=''' + @FileBackupType + ''',
		Delimiter_NoOfFields=' + cast(@NoOfFields as nvarchar(20)) + ',Delimiter_Delimiter=N''' + @Delimiter + ''',Delimiter_StringEnclosedBy=N''' +  @StringEnclosedBy + ''',Delimiter_ReaderNo=N''' + @Del_ReaderNo + ''',
		Delimiter_CardNo=N''' + @Del_CardNo + ''',Delimiter_DateTimeBit=' + cast(@Del_DateTimeBit as nvarchar(20)) + ',Delimiter_Date=N''' + @Del_Date + ''',Delimiter_Time=N''' + @Del_Time + ''',Delimiter_DateTime=N''' + @Del_DateTime + ''',
		Delimiter_Type=N''' + @Del_Type + ''',Delimiter_TransactionIdentifier=''' + @Del_TransIdentifier + ''',FixedLength_ReaderNoFrom=' + cast(@FL_ReaderNoFrom as nvarchar(20)) + ',FixedLength_ReaderNoTo=' + cast(@FL_ReaderNoTo as nvarchar(20)) + ',
		FixedLength_CardNoFrom=' + cast(@FL_CardNoFrom as nvarchar(20)) + ',FixedLength_CardNoTo=' + cast(@FL_CardNoTo as nvarchar(20)) + ',FixedLength_DateTimeBit=' + cast(@FL_DateTimeBit as nvarchar(20)) + ',
		FixedLength_DateFrom=' + cast(@FL_DateFrom as nvarchar(20)) + ',FixedLength_DateTo=' + cast(@FL_DateTo as nvarchar(20)) + ',FixedLength_TimeFrom=' + cast(@FL_TimeFrom as nvarchar(20)) + ',
		FixedLength_TimeTo=' + cast(@FL_TimeTo as nvarchar(20)) + ',FixedLength_DateTimeFrom=' + cast(@FL_DateTimeFrom as nvarchar(20)) + ',FixedLength_DateTimeTo=' + cast(@FL_DateTimeTo as nvarchar(20))+ ',
		FixedLength_TypeFrom=' + cast(@FL_TypeFrom as nvarchar(20)) + ',FixedLength_TypeTo=' + cast(@FL_TypeTo as nvarchar(20)) +',FixedLength_TransactionIdentifierFrom=' + cast(@FL_TransIdentifierFrom as nvarchar(20)) + ',
		FixedLength_TransactionIdentifierTo=' + cast(@FL_TransIdentifierTo as nvarchar(20)) +',ConnectionString=N''' + @ConnectionString + ''',TableName=N''' + @TableName + ''',MDB_ReaderNo=N''' + @MDB_ReaderNo + ''',
		MDB_CardNo=N''' + @MDB_CardNo + ''',MDB_DateTimeBit=' + cast(@MDB_DateTimeBit as nvarchar(20)) + ',MDB_Date=N''' + @MDB_Date + ''',MDB_Time=N''' +  @MDB_Time + ''',MDB_DateTime= N''' + @MDB_DateTime + ''',
		MDB_Type=N''' + @MDB_Type + ''',MDB_TransactionIdentifier=''' + @MDB_TransIdentifier + ''',RDBMS_ReaderNo=N''' + @RDBMS_ReaderNo + ''',RDBMS_CardNo=N''' + @RDBMS_CardNo + ''',
		RDBMS_DateTimeBit=' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + ',RDBMS_Date=N''' + @RDBMS_Date + ''',RDBMS_Time=N''' + @RDBMS_Time + ''',RDBMS_DateTime=N''' + @RDBMS_DateTime + ''',
		RDBMS_Type=N''' + @RDBMS_Type + ''',RDBMS_TransactionIdentifier=''' + @RDBMS_TransIdentifier + ''',RDBMS_MDB_Flag=''' + @RDBMS_MDB_Flag + ''',IsEmployeeId=' + cast(@IsEmployeeIdBit as nvarchar(5)) + ',DateTimeFormat=''' + @DateTimeFormat + ''',DateFormat=''' + @DateFormat + ''',TimeFormat=''' + @TimeFormat + ''',IsEncrypted = ' + cast(@IsEncryptedBit as nvarchar(5)) + ',
		TransactionIdentifierBit=' + cast(@TransactionIdentifierBit as nvarchar(20)) + ',TransactionIdentifierValue=''' + @TransactionIdentifierValue + ''',Emp_Id=' + cast(@Empid as nvarchar(20)) + ',IsFreeScan=' + cast(@IsFreeScan as nvarchar(4)) + ',
		[TimeStamp]=''' + cast(@EntryDate as nvarchar(20)) + ''',ISUTCTime='+cast(@IsUTC as nvarchar(4))+'WHERE TerminalDatatype_ID= ' + cast(@TerminalDatatypeId as nvarchar(20)) + ' and Raw_Data_Format=N''' + @RawDataFormat + ''' and FileType=N''' + @FileType + ''''
	END
	EXEC(@sql)
	if(@IsFreeScan=1)
		begin
		declare @TerminalAutoID int
		declare @EntranceIdentity int
		Declare @RawDataId int
		Declare @LevelId int
		--If "IS Free Scan" is "Yes" then the IN and OUT punch type create automatically add by karthikeyan.R
		if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID='787' and P.IsDeleted=0 and P.PunchType='In')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) 
						VALUES(@TerminalAutoID,'In',0,0,1,GETDATE(),'A')
					end
			end
		if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID='788' and P.IsDeleted=0 and P.PunchType='Out')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,'Out',1,0,1,GETDATE(),'A')
					end
			end  
		End	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE 	[dbo].[Proc_TA_InsertTerminalDetails]
(
	@type CHAR(1),
	@TerminalId INT=0,
	@TerminalReaderId NVARCHAR(20)='',
	@TerminalName NVARCHAR(50)='',
	@TerminalDescription NVARCHAR(255)='',
	@RawDataFormat int=0,
	@Emp_Id int
)
AS
BEGIN
	Declare @EntranceIdentity int
	Declare @TerminalAutoId int
	Declare @RawDataId int
	Declare @LevelId int
	IF (@type='I')
	BEGIN
		DECLARE @sql nvarchar(2000)
		SET @sql='INSERT INTO TA_Tbl_Terminal (Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,IsDeleted) 
		VALUES (''' + cast(@TerminalReaderId as nvarchar(20)) +''',N''' + @TerminalName + ''',N''' + @TerminalDescription + ''',' + cast(@RawDataFormat as nvarchar(20)) + ','''+cast(@Emp_Id as nvarchar(10))+''',0)'
		EXEC(@sql)			
		--Dummy values for manual time entry			
		set @RawDataId=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
		set @LevelId=(select top 1 id from Ta_Tbl_levelDetails where IsDeleted=0 and parentId=0)
		if not exists(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)
			begin			
				insert into TA_Tbl_Terminal values('787','787','787',@RawDataId,GETDATE(),1,0)
				select @TerminalAutoId=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0
				insert into TA_Tbl_Entrance values('TimecheckPhase','TimecheckPhase',@LevelId,1,1,0,GETDATE(),1,0)			
				select @EntranceIdentity=Entrance_Id from TA_Tbl_Entrance where Entrance_Name='TimecheckPhase' and IsDeleted=0
				insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,'In')	
				insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,'Out')
			end
		--Commented by Manikandan.RR on 06Feb2020 07:59 PM due to some issue related to freescan logic
		--if not exists(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
		--	BEGIN
		--		INSERT INTO TA_Tbl_Terminal values('788','788','788',@RawDataId,GETDATE(),1,0)			
		--		select @TerminalAutoId=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0
		--		select @EntranceIdentity=Entrance_Id from TA_Tbl_Entrance where Entrance_Name='TimecheckPhase' and IsDeleted=0
		--		insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,'Out')
		--	END
		declare @IsFreeScan int
		set @IsFreeScan=(select IsFreeScan from TA_tbl_TerminalDatatype where TerminalDatatype_ID=@RawDataFormat)
		if(@IsFreeScan=1)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID='787' and P.IsDeleted=0 and P.PunchType='In')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787' and IsDeleted=0)						
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,'Shift In',0,0,1,GETDATE(),'A')
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,'Shift Out',1,0,1,GETDATE(),'A')
					end
				--if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID='788' and P.IsDeleted=0 and P.PunchType='Out')
				--	begin
				--		set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='788' and IsDeleted=0)
				--		INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,'Shift Out',1,0,1,GETDATE(),'A')
				--	end
			end
	END
	-- update
	ELSE IF (@type='U')
	BEGIN
		set @sql='UPDATE TA_Tbl_Terminal 
		SET Terminal_Name=N''' + @TerminalName + ''' ,Terminal_ReaderID=''' + cast(@TerminalReaderId as nvarchar(20)) + ''',Terminal_Description=N''' + @TerminalDescription + ''',TerminalDatatype_ID=' + cast(@RawDataFormat as nvarchar(20)) + ',Emp_ID = '''+cast(@Emp_Id as nvarchar(10))+'''
		WHERE Terminal_Id=' + cast(@TerminalId as nvarchar(20)) + ''
		EXEC(@sql) 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]
	@TaskID		bigint,
	@projectID	bigint,
	@DefinedHours nvarchar(10),
	@TaskDescription nvarchar(4000),
	@SpentHours nvarchar(10),
	@TaskSubmittedBy bigint,
	@Status nvarchar(10),
	@ShiftDate nvarchar(50),
	@flag varchar(2)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@flag='U')
	BEGIN
		UPDATE Ta_tbl_TaskProgressDetails set	TaskDescription=@TaskDescription,
												SpentHours=@SpentHours,
												TaskModifiedDate=GETDATE(),
												TaskModifiedBy=@TaskSubmittedBy,
												status=@Status
		WHERE TaskID=@TaskID and ProjectID=@projectID and TaskSubmittedBy=@TaskSubmittedBy
	END
	ELSE
	BEGIN
		INSERT INTO Ta_tbl_TaskProgressDetails
		(	
			TaskID,
			ProjectID,
			ShiftDate,
			TaskHours,
			TaskDescription,
			SpentHours,
			TaskSubmittedDate,
			TaskSubmittedBy,
			Status
		) 
		VALUES
		(
			@TaskID,
			@ProjectID,
			@ShiftDate,
			@DefinedHours,
			@TaskDescription,
			@SpentHours,
			GETDATE(),
			@TaskSubmittedBy,
			@Status
		)		
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTrace]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertTrace]
(
	@PageName as nvarchar(100),
	@ErrDescription as nvarchar(2000)
)
AS
BEGIN
	Insert into Ta_Tbl_Trace (PageName,ErrDescription,DateofError) values (@PageName,@ErrDescription,getDate())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTransferEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertTransferEmployee]
	@Emp_AutoID int,
	@Trnsfr_frm varchar(20),
	@Trnsfr_To varchar(20),
	@Trnsfr_EtyDteTme varchar(20),
	@Trnsfr_Dte varchar(20),
	@Etry_RsdBy int,
	@NwDsgtonID int,
	@NwReprtngTo int,
	@NwApprvlAuthrty int,
	@Remarks varchar(500),
	@IsImprtd int,
	@Trnsfr_status varchar(10),
	@flag char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF(@flag='I')
	BEGIN
		INSERT INTO ta_tbl_transfer(Emp_AutoID, Trnsfr_frm, Trnsfr_To, Trnsfr_EtyDteTme, Trnsfr_Dte, Etry_RsdBy, NwDsgtonID, NwReprtngTo, NwApprvlAuthrty, Remarks, IsImprtd, Trnsfr_status)values
		(@Emp_AutoID,@Trnsfr_frm,@Trnsfr_To,@Trnsfr_EtyDteTme,@Trnsfr_Dte,@Etry_RsdBy,@NwDsgtonID,@NwReprtngTo,@NwApprvlAuthrty,@Remarks,@IsImprtd,@Trnsfr_status)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	18-Jul-2013
Descriptions	:	Adding Employee Leave Type details for Employee Master
*/
CREATE proc [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]
(
	@EmployeeId int,
	@LeaveTypeId int,
	@PreviousYearBalance decimal(18,1),
	@NoOffLeaveAvailed decimal(18,1),
	@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	DECLARE @Rowcount INT
	SET @Rowcount=0;
	SELECT @Rowcount = EmployeeId FROM TA_Tbl_Emp_LeaveTypeDetails 
	WHERE EmployeeId=@EmployeeId and LeaveTypeId=@LeaveTypeId and YearSettingsId=@YearSettingsId
	print @Rowcount
	if(@Rowcount > 0)
		BEGIN
			UPDATE TA_Tbl_Emp_LeaveTypeDetails set PreviousYearBalance=@PreviousYearBalance,NoOffLeaveAvailed=@NoOffLeaveAvailed
			WHERE EmployeeId=@EmployeeId and LeaveTypeId=@LeaveTypeId and YearSettingsId=@YearSettingsId
		END
	ELSE
		BEGIN
			INSERT INTO TA_Tbl_Emp_LeaveTypeDetails(EmployeeId,LeaveTypeId,PreviousYearBalance,NoOffLeaveAvailed,YearSettingsId,IsDeleted)
			VALUES(@EmployeeId,@LeaveTypeId,@PreviousYearBalance,@NoOffLeaveAvailed,@YearSettingsId,0)
		END
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogin]
(
	@UserName VARCHAR(15)	
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @CountUser INT
	DECLARE @Employee_Id INT
	DECLARE @UTCDateTime Datetime
	
	SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName = @UserName
	if(@UserName='admin')
	begin
	
	Set @UTCDateTime = getdate()
	
	end 
	
	else
	begin
		
		Select @Employee_Id=Employee_Id from TA_Tbl_Employee Where Employee_Code_Id = @UserName
		Select @UTCDateTime=[dbo].[GetUTCTimeZoneDateTime](@Employee_Id)
	
	end


	SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName=@UserName
	IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_Login
		(UserName,LastLoginTime)
		VALUES
		(@UserName, @UTCDateTime)
	END
	ELSE
	BEGIN
		UPDATE  TA_Tbl_Login SET LastLoginTime=@UTCDateTime,LastLogoutTime=null WHERE UserName=@UserName
	END
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogout]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

-- Proc_TA_InsertUpdate_LastLogout '18000008,18000074'
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogout]
(
	@UserName VARCHAR(2000)	='admin'
)
AS
DECLARE @CountUser INT
DECLARE @Employee_Id INT
DECLARE @UTCDateTime Datetime

SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName = @UserName
if(@UserName='admin')
begin

Set @UTCDateTime = getdate()

end 

else
begin
	
	Select @Employee_Id=Employee_Id from TA_Tbl_Employee Where Employee_Code_Id = @UserName
	Select @UTCDateTime=[dbo].[GetUTCTimeZoneDateTime](@Employee_Id)

end



IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_Login
		(
		   UserName,LastLogoutTime
		)
       		VALUES 
		(	
		   @UserName, @UTCDateTime
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_Login SET LastLogoutTime=@UTCDateTime WHERE UserName = @UserName
	END

	
	
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LoginLock]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_LoginLock] 
(
	@UserName VARCHAR(1000),
	@IsActive int		
)
AS
DECLARE @CountUser INT
DECLARE @Employee_Id INT
DECLARE @UTCDateTime Datetime


SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName = @UserName
if(@UserName='admin')
begin

Set @UTCDateTime = getdate()

end 

else
begin
	
	Select @Employee_Id=Employee_Id from TA_Tbl_Employee Where Employee_Code_Id = @UserName
Select @UTCDateTime=[dbo].[GetUTCTimeZoneDateTime](@Employee_Id)

end

SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_LockLogin WHERE UserName=@UserName

IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_LockLogin
		(
		   UserName,LockedTime,IsActive
		)
       		VALUES 
		(	
		   @UserName, @UTCDateTime,@IsActive
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_LockLogin
		SET LockedTime=@UTCDateTime,IsActive=@IsActive
  		WHERE UserName=@UserName
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name : Proc_TA_InsertUpdate_TempPayrollProcessDetails  
-- Purpose        : Used to store the details for payroll in temporary table  
-- Author         : Kumuthini.L  
-- Created Date   : 18-May-09  
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]  
(  
   @MonthClosure_Id int,  
   @EmpId Varchar(20),  
   @HrsWork Varchar(20),  
   @HrsOT Varchar(20),  
   @NormOT Varchar(20),  
   @OffOT Varchar(20),  
   @HolOT Varchar(20),  
   @EarlyOut Varchar(20),  
   @LateIn Varchar(20),  
   @WorkHrs Varchar(20),  
   @HrsLess Varchar(20),  
   @HrsExtra Varchar(20),  
   @LeaveDays numeric(18,1),  
   @AbsentDays numeric(18,1),  
   @PresentDays numeric(18,1),  
   @Holidays numeric(18,1),  
   @LOPDays numeric(18,1),  
   @UserId numeric(18,1),  
   @ProcessDateTime Varchar(20)  
)  
AS  
BEGIN  
  DECLARE @Count AS INT  
  SET @Count = 0    
  DELETE FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
  -- Fetch the record count by passing the month closure id and employee id  
  --SET @Count = (SELECT COUNT(*) FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId)  
  SET @Count =0
  IF(@Count = 0)  
    BEGIN  
       -- If the record count is 0, then INSERT the Details  
       INSERT INTO TA_Tbl_TempPayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut,LateIn,WorkHrs,HrsLess,HrsExtra,LeaveDays,AbsentDays,PresentDays,Holidays,LOPDays,[Emp_Id],[TimeStamp])   
       VALUES (@MonthClosure_Id,@EmpId,@HrsWork,@HrsOT,@NormOT,@OffOT,@HolOT,@EarlyOut,@LateIn,@WorkHrs,@HrsLess,@HrsExtra,@LeaveDays,@AbsentDays,@PresentDays,@Holidays,@LOPDays,@UserId,@ProcessDateTime)  
    END  
--  ELSE  
--    BEGIN  
--  
--        -- If the record count is not 0, then UPDATE the Details  
--       UPDATE TA_Tbl_PayrollProcessDetails SET HrsWork = @HrsWork,HrsOT = @HrsOT,NormOT = @NormOT,OffOT = @OffOT,HolOT = @HolOT,EarlyOut = @EarlyOut,LateIn = @LateIn,WorkHrs = @WorkHrs,  
--       HrsLess = @HrsLess,HrsExtra = @HrsExtra,LeaveDays = @LeaveDays,AbsentDays = @AbsentDays,PresentDays = @PresentDays,Holidays = @Holidays,LOPDays=@LOPDays,[Emp_Id] = @UserId,[TimeStamp] = @ProcessDateTime   
--       WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId  
--  
--    END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateActiveLanguage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name	:	Proc_TA_InsertUpdateActiveLanguage
Description	:	Set Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	16-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_InsertUpdateActiveLanguage] 
@Language_Id int
as
begin
	set nocount on
	update TA_Tbl_MultiLingual set IsActive=0
	Update TA_Tbl_MultiLingual set IsActive=1 where Language_Id=@Language_Id
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateAPIConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_InsertUpdateAPIConfiguration @tag='S'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateAPIConfiguration]
	-- Add the parameters for the stored procedure here
	@tag char(2)=null,
	@Apiurl varchar(2000)='',
	@userName varchar(200)=null,
	@Password varchar(200)=null,
	@syncFlag varchar(2)=null,
	@WhatsAppSID nvarchar(Max)=null,
	@WhatsApp_authToken nvarchar(Max)=null,
	@WhatsApp_SenderNumber nvarchar(50)=null,
	@EmpId nvarchar(10)=null


AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here

	if((select Count(*) From TA_Tbl_APIConfig)>0 and @tag!='S')
	Begin
		if(@Apiurl!='' and @Apiurl!='undefined' and @tag='IA')
		Begin
			
			Update TA_Tbl_APIConfig set APIURL=@Apiurl,BiostarUsername=@userName,BiostarPassword=@Password,syncEmp=@syncFlag,ModifyDate=GETDATE() 
		End
		Else
		Begin
			
			print @tag
			Update TA_Tbl_APIConfig set WhatsAPP_SID=@WhatsAppSID,WhatsApp_authToken=@WhatsApp_authToken,WhatsApp_SenderNumber=@WhatsApp_SenderNumber,ModifyDate=GETDATE() 
		End

	End
	Else IF(@tag='S')
	Begin
		
		select APIURL,BiostarUsername,BiostarPassword, syncEmp,WhatsAPP_SID,WhatsApp_authToken,WhatsApp_SenderNumber  from TA_Tbl_APIConfig
		--CONVERT(varchar(20),syncEmp)as
	End
	Else
	Begin

		Insert into TA_Tbl_APIConfig (APIURL,BiostarUsername,BiostarPassword,syncEmp,WhatsAPP_SID,WhatsApp_authToken,WhatsApp_SenderNumber,createdBy,createdDate,ModifyDate) values(@Apiurl,@userName,@Password,@syncFlag,@WhatsAppSID,@WhatsApp_authToken,@WhatsApp_SenderNumber,@EmpId,Convert(varchar(20),getDate()),Convert(varchar(20),getDate()))
	End
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateApprovalSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Prabakaran.P
-- Create date: 11-Sep-09
-- Description:	
-- Modifed By :		K.Gopinath
-- Create date: 01-02-2014
-- Description:	Modified to add OD as seperate column
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateApprovalSettings]
@intCompanyId int,  
@intPattern int,  
@intRoster int, 
@intOTApproval int,  
@intLeaveSanction int,  
@intPermissionSanction int, 
@intManualEntry int,
@intOnDutyEntry int,
@Approval int,
@Emp_Id int,
@webClockInOut bit,
@ShiftRequisition int
AS
BEGIN
	declare @CompanyCount as int
	set @CompanyCount=(select count(*) from TA_Tbl_ApprovalSettings where CompanyId=@intCompanyId)
	if (@CompanyCount=0)	
		Begin
			Insert into TA_Tbl_ApprovalSettings 
			(CompanyId,Pattern, Roster,OTApproval,LeaveSanction,PermissionSanction,ManualEntry,ODEntry,Emp_Id,Approval,webClockInOut,ShiftRequisition) 
			values (@intCompanyId,@intPattern,@intRoster,@intOTApproval,@intLeaveSanction,@intPermissionSanction,@intManualEntry,@intOnDutyEntry,@Emp_Id,@Approval,@webClockInOut,@ShiftRequisition)
		End
	Else
		Begin
			update TA_Tbl_ApprovalSettings set
			CompanyId=@intCompanyId,
			Pattern = @intPattern,
			Roster = @intRoster,
			OTApproval = @intOTApproval,
			LeaveSanction=@intLeaveSanction,
			PermissionSanction=@intPermissionSanction,
			ManualEntry=@intManualEntry,
			ODEntry=@intOnDutyEntry,
			Approval=@Approval,
			Emp_Id=@Emp_Id,
			webClockInOut=@webClockInOut,
			ShiftRequisition = @ShiftRequisition

			where CompanyId=@intCompanyId
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	Karthikeyan.R
-- Modified Date	:	05-Aug-2015
-- Description		:	Add four Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs,ARMISWorkHrs) in Insert and update Query
/*
	EXEC [Proc_TA_InsertUpdateCategory] 'U', 'Permanent', 1, 1, 0, 48.0, 8.0, 8.0
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory]
	@Opr NVARCHAR(1),
	@Category NVARCHAR(50),
	@EmpID INT,
	@CategoryID INT,
    @IsFlexible BIT = 0,
    @MonToSatWorkHrs nvarchar(20),
    @WeekDayWorkHrs nvarchar(20)
AS
BEGIN
	IF(@Opr = 'I')	
	BEGIN
		INSERT INTO TA_Tbl_Category(CategoryName, IsDeleted, EmpId, IsFlexible, MonToSat_WorkHrs, WeekDay_WorkHrs) 
			VALUES (@Category, 0, @EmpID, @IsFlexible, @MonToSatWorkHrs, @WeekDayWorkHrs)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_Category SET
			CategoryName = @Category,
			EmpId = @EmpID,
			IsFlexible = @IsFlexible,
			MonToSat_WorkHrs = @MonToSatWorkHrs,
			WeekDay_WorkHrs = @WeekDayWorkHrs
		WHERE CategoryId = @CategoryID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	30-Mar-2013
-- Description		:	Add Three Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs) in Insert and update Query
/*
	EXEC [Proc_TA_InsertUpdateCategory] 'U', 'Permanent', 1, 1, 0, 48.0, 8.0, 8.0
*/
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory_Angler]
	@Opr NVARCHAR(1),
	@Category NVARCHAR(50),
	@EmpID INT,
	@CategoryID INT,
    @IsFlexible BIT = 0,
    @MonToSatWorkHrs NUMERIC(18, 1),
    @SatWorkHrs NUMERIC(18, 1),
    @WeekDayWorkHrs NUMERIC(18, 1),
    @ARMISWorkHrs NUMERIC(18, 1)
AS
BEGIN
	IF(@Opr = 'I')	
	BEGIN
		INSERT INTO TA_Tbl_Category(CategoryName, IsDeleted, EmpId, IsFlexible, MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs, ARMIS_WorkHrs) 
			VALUES (@Category, 0, @EmpID, @IsFlexible, @MonToSatWorkHrs, @SatWorkHrs, @WeekDayWorkHrs, @ARMISWorkHrs)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_Category SET
			CategoryName = @Category,
			EmpId = @EmpID,
			IsFlexible = @IsFlexible,
			MonToSat_WorkHrs = @MonToSatWorkHrs,
			Sat_WorkHrs = @SatWorkHrs,
			WeekDay_WorkHrs = @WeekDayWorkHrs,
			ARMIS_WorkHrs = @ARMISWorkHrs
		WHERE CategoryId = @CategoryID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCompanyGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateCompanyGroup]
@CompanyGroup as varchar(500)
AS
BEGIN
	declare @Count as int
	set @Count = (select count(*) from TA_Tbl_CompanyGroup)
	if (@count=0)
		Begin
			insert into TA_Tbl_CompanyGroup (CompanyGroup) values (@CompanyGroup)
		End
	Else
		Begin
			update Ta_Tbl_CompanyGroup set CompanyGroup=@CompanyGroup
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateDelete_CCGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Fetches the Organization,Designation and UserGroup details for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateDelete_CCGroup] 
(
@LevelId int,
@DesignationId int,
@MailTo_SecondLevel_Planned int,
@MailTo_SecondLevel_UnPlanned int,
@Parameter varchar(2)
)
AS
BEGIN
	SET NOCOUNT ON;
if(@Parameter='I')
	BEGIN
	  insert into TA_Tbl_CCMailGroup values (@LevelId,@DesignationId,@MailTo_SecondLevel_Planned,@MailTo_SecondLevel_UnPlanned)
	  select @@Identity as CCMailGroupId
	END
if(@Parameter='U')
	BEGIN
	  update TA_Tbl_CCMailGroup set MailTo_SecondLevel_Planned=@MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned=@MailTo_SecondLevel_UnPlanned
	  where LevelId=@LevelId and DesignationId=@DesignationId
	  select 0 as CCMailGroupId
	END   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_InsertUpdateEmailScheduleDetails 'Test',41,'Daily','Monday','Monday','Monday',1,1,1,'10:30 AM',1,1,1,'PortableDocFormat',1
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]
(
	@ScheduleName varchar(250),
	@ReportId int,
	@Frequency varchar(20),
	@DayToSend varchar(10),
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateToSend int,
	@DateFrom int,
	@DateTo int,
	@TimeToSend varchar(20),
	@EmployeeId int,
	@EmailSendType int,
	@Authentication int,
	@FileType varchar(20),
	@Enabled int,
	@ScheduleId int,
	@Type varchar(2),
	@ReportName varchar(50),
	@ToWhom int,
	@TimeSendOption int=null,
	@Reminder_afterDays int=null
)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@Type = 'I')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_EmailSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0)
		BEGIN		
			INSERT INTO TA_Tbl_EmailSchedule (ScheduleName,ReportId,Frequency,DayToSend,DayFrom,DayTo,DateToSend,DateFrom,DateTo,TimeToSend,EmployeeId,EmailSendType,Authentication,FileType,Enabled,IsDeleted,ReportName,ToWhom,TimeSendOption,Reminder_afterDays)
			VALUES(@ScheduleName,@ReportId,@Frequency,@DayToSend,@DayFrom,@DayTo,@DateToSend,@DateFrom,@DateTo,@TimeToSend,@EmployeeId,@EmailSendType,@Authentication,@FileType,@Enabled,0,@ReportName,@ToWhom,@TimeSendOption,@Reminder_afterDays)
			SELECT CAST(@@IDENTITY AS INT) AS InsertedId
		END
		ELSE
		BEGIN
			SELECT 0
		END
	END
	ELSE IF(@Type = 'U')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_EmailSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0 and ScheduleId<>@ScheduleId)
		BEGIN
			UPDATE TA_Tbl_EmailSchedule SET ScheduleName = @ScheduleName,ReportId = @ReportId,Frequency = @Frequency,DayToSend = @DayToSend,
			DayFrom = @DayFrom,DayTo = @DayTo,DateToSend = @DateToSend, DateFrom = @DateFrom, DateTo = @DateTo, TimeToSend=@TimeToSend,
			EmployeeId = @EmployeeId, EmailSendType = @EmailSendType, Authentication = @Authentication, FileType = @FileType, Enabled = @Enabled,IsDeleted =0,
			ReportName=@ReportName,ToWhom=@ToWhom,TimeSendOption=@TimeSendOption,
			Reminder_afterDays=@Reminder_afterDays
			where ScheduleId = @ScheduleId 
			SELECT 1
		END
		ELSE 
		BEGIN
		    SELECT 0
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]
(
	@ScheduleId int,
	@Filters varchar(max),
	@ReportType varchar(25),
	@Type varchar(2),
	@CompanyId int
)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type  = 'I')
		BEGIN
			insert into TA_Tbl_EmailScheduleFilters (ScheduleId,Filters,ReportType,CompanyId) values (@ScheduleId,@Filters,@ReportType,@CompanyId)
		END
	else
		BEGIN
			update TA_Tbl_EmailScheduleFilters set Filters=@Filters, ReportType=@ReportType,
			CompanyId= @CompanyId where ScheduleId=@ScheduleId
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailTemplate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailTemplate]
(
	@ScheduleId int,
	@Subject varchar(300),
	@EmailContent varchar(max),
	@Type varchar(2)
)
AS
BEGIN
	SET NOCOUNT ON;
    IF(@Type  = 'I')
		BEGIN
			INSERT INTO TA_Tbl_EmailTemplate (ScheduleId,Subject,EmailContent) VALUES (@ScheduleId,@Subject,@EmailContent)
		END
	ELSE
		BEGIN
		    UPDATE TA_Tbl_EmailTemplate SET subject= @Subject, EmailContent = @EmailContent WHERE ScheduleId = @ScheduleId
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateFTPConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 17-Aug-2011
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertUpdateFTPConfiguration] 
(
 @Address varchar(250),
 @UserName varchar(100),
 @Password varchar(100),
 @Port varchar(15)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
   if((select count(*) from TA_Tbl_FTPConfiguration) = 0)
   Begin
      insert into TA_Tbl_FTPConfiguration (Address,UserName,Password,Port) values (@Address,@UserName,@Password,@Port)
   End
   else
   Begin
      update TA_Tbl_FTPConfiguration set Address = @Address,UserName = @UserName,Password = @Password,Port = @Port
   End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateInDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- If Records does not Exist, the Insert the IN Record
-- Else Update the Clock Details Table with In Record with Minimum Clk_OutTime
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertUpdateInDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@gstrClockDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Top 1 Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inClk_EmpId 
	AND (Clk_InTime = '' OR Clk_InTime IS NULL) AND Clk_OutDate <> '' AND Clk_OutDate IS NOT NULL AND 
	Clk_OutDeviceId IN (@strOutDeviceId)
	AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND Clk_Date= @gstrClockDate AND IsVoid=0
	ORDER BY (Clk_OutDate+Clk_OutTime) ASC
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateLeaveSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- =============================================
-- Author		:  Kumuthini.L
-- Create date		: 19-Apr-08
-- Description		: Insert Update Leave Setting Details
-- Procedure Name	: Proc_TA_InsertUpdateLeaveSettings 12.5,7.5,35,6
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateLeaveSettings]		
(
	@CompanyId INT,
	@Approval INT,
	@FirstLevelIntimation INT,
	@SecondLevelIntimation INT,
	@ApprovalCC varchar(8000),
	@DailyReportTO varchar(8000),
	@DailyReportCC varchar(8000)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @RecCount AS INT
	SET @RecCount = (SELECT COUNT(*)  FROM TA_Tbl_LeaveSettings WHERE  CompanyId=@CompanyId)
	IF (@RecCount=0)
		BEGIN
			INSERT  INTO TA_Tbl_LeaveSettings (CompanyId,Approval,FirstLevelIntimation,SecondLevelIntimation,ApprovalCC,ToMail_DailyReport,CCMail_DailyReport) 
			VALUES (@CompanyId,@Approval,@FirstLevelIntimation,@SecondLevelIntimation,@ApprovalCC,@DailyReportTO,@DailyReportCC)
		END
	ELSE
		BEGIN
			UPDATE TA_Tbl_LeaveSettings SET Approval=@Approval,FirstLevelIntimation=@FirstLevelIntimation,SecondLevelIntimation=@SecondLevelIntimation,
			ApprovalCC=@ApprovalCC,ToMail_DailyReport=@DailyReportTO,CCMail_DailyReport=@DailyReportCC Where CompanyId=@CompanyId	
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateMusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_InsertUpdateMusterRoll '787','2014-10-15','Present','Present',10,10,10
---- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertUpdateMusterRoll]
	-- Add the parameters for the stored procedure here
	@Employeecodeid VARCHAR(50),
	@Date DATETIME,
	@FNAttendance VARCHAR(50),
	@ANAttendance VARCHAR(50),
	@LateInMins INT,
	@EarlyOutMins INT,
	@OTMins INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @SQLInsert VARCHAR(MAX)
	DECLARE @SQLUpdate VARCHAR(MAX)
	DECLARE @SQLDate VARCHAR(MAX)
	DECLARE @SQLMonth int
	DECLARE @SQLYear int
	set @SQLMonth=DATEPART(M,@Date)
	set @SQLYear=DATEPART(YEAR,@Date)	
	set @SQLDate=DATEPART(d,@Date)
	set @SQLInsert='Insert into musterRoll(Employeecodeid,Month,Year,TotalEarlyExit,TotalLateEntry,TotalExtraHours'
	set @SQLUpdate='Update musterRoll set '
    -- Insert statements for procedure here
	IF EXISTS(SELECT * FROM musterRoll WHERE MONTH=@SQLMonth AND YEAR=@SQLYear AND Employeecodeid=@Employeecodeid)
		BEGIN
			set @SQLUpdate=@SQLUpdate+'FNDay'+ @SQLDate + '='''+SUBSTRING(@FNAttendance,0,2)+''','
			set @SQLUpdate=@SQLUpdate+'ANDay'+ @SQLDate + '='''+SUBSTRING(@ANAttendance,0,2)+''''
			set @SQLUpdate=@SQLUpdate+' WHERE MONTH='''+convert(varchar(10),@SQLMonth) +''' AND YEAR='''+convert(varchar(10),@SQLYear) +''' AND Employeecodeid='''+@Employeecodeid+''''
			select @SQLUpdate
			execute (@SQLUpdate)
		END
	ELSE
		BEGIN
			set @SQLInsert=@SQLInsert+',FNDay'+ @SQLDate + ',ANDay'+ @SQLDate + ') values('+@Employeecodeid+','+convert(varchar(20),@SQLMonth)+','+
			convert(varchar(10),@SQLYear)+','+
			ISNULL(convert(varchar(10),@EarlyOutMins),'0')+','+ISNULL(convert(Varchar(20),@LateInMins),'0')+','+convert(varchar(10),@OTMins)+','''+SUBSTRING(@FNAttendance,0,2)+''','''+SUBSTRING(@ANAttendance,0,2)+''')'
			select @SQLInsert
			execute (@SQLInsert)
		END	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpDateMyProfileDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Rajkumar.J
-- Create date: 08-05-2021
-- Description:	procedure to insert MyProfiles details 
-- exec 48,'1086','Rajkumar','','','','',
-- exec Proc_Ta_InsertUpDateMyProfileDetails @tag=N'A', @myprofileID=N'1'
-- exec Proc_Ta_InsertUpDateMyProfileDetails @tag=N'E',@myprofileID=N'20'
-- Proc_Ta_InsertUpDateMyProfileDetails @tag=N'E',@Employee_Id=N'40'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertUpDateMyProfileDetails]
	-- Add the parameters for the stored procedure here
	@tag nvarchar(10),
	@myprofileID bigint=null,
	@Employee_Id int =0,
	@SwipeCardNo nvarchar(50) = null,
	@Employee_FirstName nvarchar(50) = null,
	@Employee_MiddleName nvarchar(50) = null,
	@Employee_LastName nvarchar(50) = null,
	@Father_name nvarchar(50) = null,
	@Mother_name nvarchar(50) = null,
	@DateofBirth nvarchar(100) = null,
	@DateofBirth_Record nvarchar(100) = null,
	@Blood_Group nvarchar(10) = null,
	@EmailId nvarchar(100) = null,
	@Personal_mailid nvarchar(100) = null,
	@Contact_Address nvarchar(255) = null,
	@Permanent_Address nvarchar(255) = null,
	@Phone_Number nvarchar(50) = null,
	@Mobile_Number nvarchar(50) = null,	
	@Marital_status nvarchar(10) = null,
	@Nationality nvarchar(50) = null,
	@Religion int = 0,
	@Country int = null,
	@State int = null,
	@City int = null,
	@District nvarchar(50) = null,
	@Status nvarchar(50) = null,
	@login_EmployeeID int=null,
	@LevelId varchar(2000)=null,
	@EmployeeId varchar(100)=null,
	@EmployeeName varchar(50)=null,  
	@EmpCategory int=null, 
	@EmpType int=null,
	@FromDate varchar(20)=null,    
	@ToDate varchar(20) =null,
	@UserGroupName varchar(250)=null,
	@ParentID int=null ,
	@Path varchar(200)=null,
	@Remarks varchar(100)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	SET NOCOUNT ON;
	if(@tag='I')
		begin
			INSERT INTO [dbo].[Ta_Tbl_MyProfileDetails] ([Employee_Id] ,[SwipeCardNo] ,[Employee_FirstName] ,[Employee_MiddleName] ,[Employee_LastName] ,[Father_name] ,[Mother_name] ,[DateofBirth] ,[DateofBirth_Record] ,[Blood_Group] ,[EmailId] ,[Personal_mailid] ,[Contact_Address] ,[Permanent_Address] ,[Phone_Number] ,[Mobile_Number] ,[Marital_status] ,[Nationality] ,[Religion] ,[Country] ,[State] ,[City] ,[District] ,[Status] ,[ModifiedDate],[IsPath]) VALUES
           (@Employee_Id, @SwipeCardNo, @Employee_FirstName, @Employee_MiddleName, @Employee_LastName, @Father_name, @Mother_name, Case when Cast(@DateofBirth as date)='1900-01-01' then null Else @DateofBirth End , Case when Cast(@DateofBirth_Record as date)='1900-01-01' then null Else @DateofBirth_Record End, @Blood_Group, @EmailId, @Personal_mailid, @Contact_Address, @Permanent_Address, @Phone_Number, @Mobile_Number, @Marital_status, @Nationality, @Religion, @Country, @State, @City, @District, 'Pending' , getdate(),@Path)

		   Update TA_Tbl_Employee set IsMyProfileRqrd=MP.myprofileID From TA_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id=MP.Employee_Id
		   Select '1'
		end
	else if(@tag='U')
		begin
			UPDATE [dbo].[Ta_Tbl_MyProfileDetails] SET [SwipeCardNo] = @SwipeCardNo,[Employee_FirstName] = @Employee_FirstName,[Employee_MiddleName] = @Employee_MiddleName,[Employee_LastName] = @Employee_LastName,[Father_name] = @Father_name,[Mother_name] = @Mother_name,[DateofBirth] = @DateofBirth ,[DateofBirth_Record] = @DateofBirth_Record ,[Blood_Group] = @Blood_Group ,[EmailId] = @EmailId ,[Personal_mailid] = @Personal_mailid ,[Contact_Address] = @Contact_Address ,[Permanent_Address] = @Permanent_Address ,[Phone_Number] = @Phone_Number ,[Mobile_Number] = @Mobile_Number ,[Marital_status] = @Marital_status ,[Nationality] = @Nationality ,[Religion] = @Religion,[Country] = @Country,[State] = @State ,[City] = @City ,[District] = @District,[Status] = @Status,[ModifiedDate] = getdate(),[IsPath]=@Path where myprofileID = @myprofileID 
			Select '1'

		end
	else if(@tag='S')
		Begin
			SELECT [myprofileID] ,[Employee_Id] ,[SwipeCardNo] ,[Employee_FirstName] ,[Employee_MiddleName] ,[Employee_LastName] ,[Father_name] ,[Mother_name] ,[DateofBirth] ,[DateofBirth_Record] ,[Blood_Group] ,[EmailId] ,[Personal_mailid] ,[Contact_Address] ,[Permanent_Address] ,[Phone_Number] ,[Mobile_Number] ,[Marital_status] ,[Nationality] ,[Religion] ,[Country] ,[State] ,[City] ,[District] ,[Status] ,[ModifiedDate] FROM [dbo].[Ta_Tbl_MyProfileDetails] where ((@Employee_Id IS NULL OR @Employee_Id='0') OR Employee_Id = @Employee_Id)
			and ((@Status IS NULL OR @Status='') OR Status = @Status)
			and ((@myprofileID IS NULL OR @myprofileID='0') OR myprofileID = @myprofileID)
		end
	else if(@tag='E')
		begin
			SELECT MP.[myprofileID] ,MP.[Employee_Id] ,MP.[SwipeCardNo] ,MP.[Employee_FirstName] ,MP.[Employee_MiddleName] ,MP.[Employee_LastName] ,MP.[Father_name] ,MP.[Mother_name] ,Case when Cast(MP.[DateofBirth] as date)='1900-01-01' then null Else Mp.[DateofBirth] End as DateofBirth ,Case when Cast(MP.[DateofBirth_Record] as date)='1900-01-01' then null Else MP.[DateofBirth_Record] End as DateofBirth_Record ,MP.[Blood_Group] ,MP.[EmailId] ,MP.[Personal_mailid] ,MP.[Contact_Address] ,MP.[Permanent_Address] ,MP.[Phone_Number] ,MP.[Mobile_Number] ,MP.[Marital_status] ,MP.[Nationality] ,MP.[Religion] as ReligionId ,MP.[Country] ,MP.[State] ,MP.[City] as Native_Place ,MP.[District] ,MP.[Status] ,MP.[ModifiedDate],'1' as MyProfileUpdate ,Look.Title AS CityName,Look1.Title AS Statename,Look2.Title AS Countryname,MP.Remarks
			FROM [dbo].[Ta_Tbl_MyProfileDetails] MP 
			LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=MP.City
			LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=MP.State  
			LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=MP.Country  
			where ((@Employee_Id IS NULL OR @Employee_Id='0') OR MP.Employee_Id = @Employee_Id)
			and ((@Status IS NULL OR @Status='') OR MP.Status = @Status)
			and ((@myprofileID IS NULL OR @myprofileID='0') OR MP.myprofileID = @myprofileID)

			select
			case when E.SwipeCardNo = MP.SwipeCardNo then 0 else 1 end as SwipeCardNo,
			case when E.Employee_FirstName = MP.Employee_FirstName then 0 else 1 end as Employee_FirstName,
			case when E.Employee_MiddleName =MP.Employee_MiddleName then 0 else 1 end as Employee_MiddleName,
			case when E.Employee_LastName = MP.Employee_LastName then 0 else 1 end as Employee_LastName,
			case when E.Father_name = MP.Father_name  then 0 else 1 end as Father_name,
			case when E.Mother_name = MP.Mother_name then 0 else 1 end as Mother_name,
			case when E.Blood_Group = MP.Blood_Group then 0 else 1 end as Blood_Group,
			Case when (E.DateofBirth Is Null AND MP.DateofBirth Is Null) then 0 else 
			(case when E.DateofBirth = MP.DateofBirth then 0 else 1 end) End as DateofBirth,
			Case when (E.DateofBirth_Record Is Null AnD MP.DateofBirth_Record Is Null) then 0 else
			case when E.DateofBirth_Record = MP.DateofBirth_Record then 0 else 1 end End as DateofBirth_Record,
			case when E.EmailId = MP.EmailId then 0 else 1 end as EmailId,
			case when E.Personal_mailid = MP.Personal_mailid then 0 else 1 end as Personal_mailid,
			case when E.Contact_Address = MP.Contact_Address then 0 else 1 end as Contact_Address,
			case when E.Permanent_Address = MP.Permanent_Address then 0 else 1 end as Permanent_Address,
			case when E.Country = MP.Country then 0 else 1 end as Country,
			case when E.State = MP.State then 0 else 1 end as State,
			case when E.Native_Place = MP.City then 0 else 1 end as Native_Place,
			case when E.District = MP.District then 0 else 1 end as District,
			case when E.Phone_Number = MP.Phone_Number then 0 else 1 end as Phone_Number,
			case when E.Mobile_Number = MP.Mobile_Number then 0 else 1 end as Mobile_Number,
			case when E.Marital_status = MP.Marital_status then 0 else 1 end as Marital_status,
			case when E.Nationality = MP.Nationality then 0 else 1 end as Nationality,
			case when E.Religion = MP.Religion then 0 else 1 end as ReligionId,
			MP.Status
			from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id  where ((@Employee_Id IS NULL OR @Employee_Id='0') OR MP.Employee_Id = @Employee_Id)
			and ((@Status IS NULL OR @Status='') OR MP.Status = @Status)

			and ((@myprofileID IS NULL OR @myprofileID='0') OR MP.myprofileID = @myprofileID)
			
			
			SELECT E.Employee_Code_Id ,MP.[Employee_FirstName],MP.[Employee_MiddleName] ,MP.[Employee_LastName],Mp.SwipeCardNo, MP.[Father_name],MP.[Mother_name],Case when Cast(MP.[DateofBirth] as date)='1900-01-01' then null Else Mp.[DateofBirth] End as DateofBirth ,Case when Cast(MP.[DateofBirth_Record] as date)='1900-01-01' then '' Else MP.[DateofBirth_Record] End as DateofBirth_Record ,MP.[Blood_Group],MP.[EmailId] ,MP.[Personal_mailid],MP.[Contact_Address] ,MP.[Permanent_Address] ,MP.[Phone_Number] ,MP.[Mobile_Number] ,MP.[Marital_status],MP.[Nationality] ,R.Name as [Religion] ,Look2.Title AS CountryName ,Look1.Title AS StateName ,Look.Title AS CityName ,MP.[District] ,MP.[Status],
			
			Case when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, MP.ModifiedDate,@dateFormat),' ','-')
			Else CONVERT(VARCHAR,MP.ModifiedDate,@dateFormat) End as ModifiedDate,Mp.[isPath]

			FROM [dbo].[Ta_Tbl_MyProfileDetails] MP 
			inner join TA_Tbl_Employee E on E.Employee_Id=MP.Employee_Id
			LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=MP.City
			LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=MP.State  
			LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=MP.Country  
			LEFT OUTER JOIN TA_Tbl_Religion R on MP.Religion=R.ID
			where ((@Employee_Id IS NULL OR @Employee_Id='0') OR MP.Employee_Id = @Employee_Id)
			and ((@Status IS NULL OR @Status='') OR MP.Status = @Status)
			and ((@myprofileID IS NULL OR @myprofileID='0') OR MP.myprofileID = @myprofileID) order by modify_date desc

			--Select * From Ta_Tbl_MyProfileDetails
			--declare @SQLQuery nvarchar(MAX)='Select'
			--select
			--@SQLQuery = @SQLQuery + (
			--case when E.SwipeCardNo = MP.SwipeCardNo then '' else 'MP.SwipeCardNo,' end 
			--+ case when E.Employee_FirstName = MP.Employee_FirstName then '' else 'MP.Employee_FirstName,' end 
			--+ case when E.Employee_MiddleName =MP.Employee_MiddleName then '' else 'MP.Employee_MiddleName,' end 
			--+ case when E.Employee_LastName = MP.Employee_LastName then '' else 'MP.Employee_LastName,' end 
			--+ case when E.Father_name = MP.Father_name  then '' else 'MP.Father_name,' end 
			--+ case when E.Mother_name = MP.Mother_name then '' else 'MP.Mother_name,' end 
			--+ case when E.Blood_Group = MP.Blood_Group then '' else 'MP.Blood_Group,' end
			--+ case when E.DateofBirth = MP.DateofBirth then '' else 'MP.DateofBirth,' end
			--+ case when E.DateofBirth_Record = MP.DateofBirth_Record then '' else 'MP.DateofBirth_Record,' end
			--+ case when E.EmailId = MP.EmailId then '' else 'MP.EmailId,' end
			--+ case when E.Personal_mailid = MP.Personal_mailid then '' else 'MP.Personal_mailid,' end
			--+ case when E.Contact_Address = MP.Contact_Address then '' else 'MP.Contact_Address,' end
			--+ case when E.Permanent_Address = MP.Permanent_Address then '' else 'MP.Permanent_Address,' end
			--+ case when E.Country = MP.Country then '' else 'MP.Country,' end
			--+ case when E.State = MP.State then '' else 'MP.State,' end 
			--+ case when E.Native_Place = MP.City then '' else 'MP.City,' end
			--+ case when E.District = MP.District then '' else 'MP.District,' end
			--+ case when E.Phone_Number = MP.Phone_Number then '' else 'MP.Phone_Number,' end
			--+ case when E.Mobile_Number = MP.Mobile_Number then '' else 'MP.Mobile_Number,' end
			--+ case when E.Marital_status = MP.Marital_status then '' else 'MP.Marital_status,' end
			--+ case when E.Nationality = MP.Nationality then '' else 'MP.Nationality,' end
			--+ case when E.Religion = MP.Religion then '' else 'MP.Religion,' end) + ' MP.Status from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id where MP.Employee_Id= '+ cast(MP.Employee_Id as nvarchar(10)) + ' AND MP.myprofileID= ' + cast(MP.myprofileID as nvarchar(20)) + ' AND MP.Status= ''' + cast(MP.Status as nvarchar(50)) +''''
			--from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id  where ((@Employee_Id IS NULL OR @Employee_Id='0') OR MP.Employee_Id = @Employee_Id)
			--and ((@Status IS NULL OR @Status='') OR MP.Status = @Status)
			--and ((@myprofileID IS NULL OR @myprofileID='0') OR MP.myprofileID = @myprofileID)

			--Select @SQLQuery= 'Select ' + @SQLQuery
			--print(@SQLQuery)
			--EXECute(@SQLQuery)

		end
	else if(@tag='SS')
		begin
			create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
			create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
			create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
			create table #LevelRights(LevelId int)
			insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
			declare @isReportingto as int
			select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
			create table #EmployeeIds(EmpAutoId int)
			if(@EmployeeId!='')
			begin
				Select @EmployeeId=Employee_Id From TA_Tbl_Employee where Employee_Code_Id=@EmployeeId
			End
			
			--print @EmployeeId
			if(@isReportingto=1)
			begin
				if(@Status!='Forwarded')
				BEGIN
					insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@login_EmployeeID) as EmpAutoId  
				END
				insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@login_EmployeeID) as EmpAutoId
				delete from #EmployeeIds where EmpAutoId=@login_EmployeeID
			end
			--Employee Level insert in Temporary table
			insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
			(
				select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
				inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 
				and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
				and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
				and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
				group by EmployeeId
			) ELevel
			inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
			AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	
			--Employee Type insert in Temporary table
			insert into #EmpType 
			select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from 
			(
				select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
				inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 
				and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
				and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
				and(ISNULL(@EmpType,0)=0 or et.TypeId=@EmpType)
				and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
				group by EmployeeId
			) EmpType
			inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
			AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	
			--select * from #EmpType
			--Employee Category insert in Temporary table
			insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from 
			(
				select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
				inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 
				and((isnull(@EmployeeId,'')='' or emp.Employee_Id=@EmployeeId))
				and(isnull(@EmployeeName,'')='' or (emp.Employee_FirstName + ' ' + isnull(emp.Employee_LastName,'''') like @EmployeeName+'%'))
				and(ISNULL(@EmpCategory,0)=0 or ec.CategoryId=@EmpCategory)
				and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
				group by EmployeeId
			) EmpCategory
			inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
			AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
			--select * from #EmpCategory
			Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	
			Insert Into #TempPermissionDetails 
			select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
			from ta_tbl_employee E
			inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
			inner join #LevelRights on #LevelRights.LevelId=el.levelID
			where Isdeleted=0 and Employee_Status=1	

			SELECT MP.[myprofileID] ,MP.[Employee_Id] ,MP.[SwipeCardNo] ,MP.[Employee_FirstName] ,MP.[Employee_MiddleName] ,MP.[Employee_LastName] ,MP.[Father_name] ,MP.[Mother_name] ,MP.[DateofBirth] ,MP.[DateofBirth_Record] ,MP.[Blood_Group] ,MP.[EmailId] ,MP.[Personal_mailid] ,MP.[Contact_Address] ,MP.[Permanent_Address] ,MP.[Phone_Number] ,MP.[Mobile_Number] ,MP.[Marital_status] ,MP.[Nationality] ,MP.[Religion] as ReligionId ,MP.[Country] ,MP.[State] ,MP.[City] as Native_Place ,MP.[District] ,MP.[Status] ,
			Case when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, MP.ModifiedDate,@dateFormat),' ','-')
			Else CONVERT(VARCHAR,MP.ModifiedDate,@dateFormat) End as ModifiedDate,MP.Remarks,'1' as MyProfileUpdate from TA_TBL_Employee E
			inner join Ta_Tbl_MyProfileDetails MP on  E.Employee_Id=MP.Employee_Id
			Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id
			Inner join #EmpType on #EmpType.employeeid = E.Employee_Id
			Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id
			Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID
			inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id
			where E.Isdeleted=0 and mp.ModifiedDate between @FromDate and @ToDate 
			and ((@Status IS NULL OR @Status='' OR @Status='All') OR MP.Status = @Status)
		end
	else if(@tag='A')
		begin
			declare @SQLQuery nvarchar(MAX)='Update E set '
			select
			@SQLQuery = @SQLQuery + (
			case when E.SwipeCardNo = MP.SwipeCardNo then '' else 'E.SwipeCardNo=MP.SwipeCardNo,' end 
			+ case when E.Employee_FirstName = MP.Employee_FirstName then '' else 'E.Employee_FirstName=MP.Employee_FirstName,' end 
			+ case when E.Employee_MiddleName =MP.Employee_MiddleName then '' else 'E.Employee_MiddleName=MP.Employee_MiddleName,' end 
			+ case when E.Employee_LastName = MP.Employee_LastName then '' else 'E.Employee_LastName=MP.Employee_LastName,' end 
			+ case when E.Father_name = MP.Father_name  then '' else 'E.Father_name = MP.Father_name,' end 
			+ case when E.Mother_name = MP.Mother_name then '' else 'E.Mother_name = MP.Mother_name,' end 
			+ case when E.Blood_Group = MP.Blood_Group then '' else 'E.Blood_Group = MP.Blood_Group,' end
			+ case when E.DateofBirth = MP.DateofBirth then '' else 'E.DateofBirth = MP.DateofBirth,' end
			+ case when E.DateofBirth_Record = MP.DateofBirth_Record then '' else 'E.DateofBirth_Record = MP.DateofBirth_Record,' end
			+ case when E.EmailId = MP.EmailId then '' else 'E.EmailId = MP.EmailId,' end
			+ case when E.Personal_mailid = MP.Personal_mailid then '' else 'E.Personal_mailid = MP.Personal_mailid,' end
			+ case when E.Contact_Address = MP.Contact_Address then '' else 'E.Contact_Address = MP.Contact_Address,' end
			+ case when E.Permanent_Address = MP.Permanent_Address then '' else 'E.Permanent_Address = MP.Permanent_Address,' end
			+ case when E.Country = MP.Country then '' else 'E.Country = MP.Country,' end
			+ case when E.State = MP.State then '' else 'E.State = MP.State,' end 
			+ case when E.Native_Place = MP.City then '' else 'E.Native_Place = MP.City,' end
			+ case when E.District = MP.District then '' else 'E.District = MP.District,' end
			+ case when E.Phone_Number = MP.Phone_Number then '' else 'E.Phone_Number = MP.Phone_Number,' end
			+ case when E.Mobile_Number = MP.Mobile_Number then '' else 'E.Mobile_Number =MP.Mobile_Number,' end
			+ case when E.Marital_status = MP.Marital_status then '' else 'E.Marital_status =MP.Marital_status,' end
			+ case when E.Nationality = MP.Nationality then '' else 'E.Nationality = MP.Nationality,' end
			+ case when E.Religion = MP.Religion then '' else 'E.Religion = MP.Religion,' end) + ' from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id where MP.Employee_Id= '+ cast(MP.Employee_Id as nvarchar(10)) + ' AND MP.myprofileID= ' + cast(MP.myprofileID as nvarchar(20))
			from Ta_Tbl_Employee E inner join Ta_Tbl_MyProfileDetails MP on E.Employee_Id = MP.Employee_Id  where ((@Employee_Id IS NULL OR @Employee_Id='0') OR MP.Employee_Id = @Employee_Id)
			and ((@Status IS NULL OR @Status='') OR MP.Status = @Status)
			and ((@myprofileID IS NULL OR @myprofileID='0') OR MP.myprofileID = @myprofileID)

			Select @SQLQuery= Replace(@SQLQuery, ', from' ,' from')
			print(@SQLQuery)
			update Ta_Tbl_MyProfileDetails set Status='Approved',Remarks=@Remarks where myprofileID=@myprofileID
			EXECute(@SQLQuery)
			Select '1'
		end
	else if(@tag='R')
		begin
			update Ta_Tbl_MyProfileDetails set Status='Rejected',Remarks=@Remarks where myprofileID=@myprofileID
			Select '1'
		end
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateOracleDBDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateOracleDBDetails]
	@HostName varchar(100),
	@Port varchar(5),
	@ServiceName varchar(100),
	@UserName varchar(100),
	@Pwd varchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	IF NOT EXISTS(SELECT HostName FROM Ta_tbl_OracleDBConfiguration)
	BEGIN
		Insert into Ta_tbl_OracleDBConfiguration values(@HostName,@Port,@ServiceName,@UserName,@Pwd)
	END
	ELSE
	BEGIN
		Update Ta_tbl_OracleDBConfiguration set HostName=@HostName,port=@Port,servicename=@ServiceName,username=@UserName,pwd=@Pwd
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for Armis
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0
	)  
AS  
declare @ArmisConfigCount int
SELECT @ArmisConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Armis
if @ArmisConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Armis(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,getdate())    
		select @@identity
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Armis SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,Datetime=getdate()    	
    	select ArmisID from ta_tbl_NoOfDaysDeduction_Armis
    	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for LateEntry
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0,
		@StartTime6 int,
		@EndTime6 int,
		@Day6 FLOAT=0
	)  
AS  
declare @LateEntryConfigCount int  
SELECT @LateEntryConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Lateentry
if @LateEntryConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Lateentry(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,getdate())    
		select @@identity   
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Lateentry SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,Datetime=getdate()
    	select LateEntryID from ta_tbl_NoOfDaysDeduction_Lateentry
    	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for WorkHours
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0,
		@StartTime6 int,
		@EndTime6 int,
		@Day6 FLOAT=0
	)  
AS  
declare @WorkHrsConfigCount int  
SELECT @WorkHrsConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_WorkHrs
if @WorkHrsConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_WorkHrs(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,getdate())   
		select @@identity    
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_WorkHrs SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,Datetime=getdate()
    	select WorkhrsID from ta_tbl_NoOfDaysDeduction_WorkHrs
    	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for Angler
Modified on	:	21-Feb-08
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]  
	(
		@StartTime1 nvarchar(20),
		@EndTime1 nvarchar(20),
		@Day1 decimal,
		@StartTime2 nvarchar(20),
		@EndTime2 nvarchar(20),
		@Day2 decimal,
		@StartTime3 nvarchar(20),
		@EndTime3 nvarchar(20),
		@Day3 decimal,
		@StartTime4 nvarchar(20),
		@EndTime4 nvarchar(20),
		@Day4 decimal,
		@StartTime5 nvarchar(20),
		@EndTime5 nvarchar(20),
		@Day5 decimal,
		@StartTime6 nvarchar(20),
		@EndTime6 nvarchar(20),
		@Day6 decimal,
		@StartTime7 nvarchar(20),
		@EndTime7 nvarchar(20),
		@Day7 decimal,
		@StartTime8 nvarchar(20),
		@EndTime8 nvarchar(20),
		@Day8 decimal,
		@StartTime9 nvarchar(20),
		@EndTime9 nvarchar(20),
		@Day9 decimal,
		@StartTime10 nvarchar(20),
		@EndTime10 nvarchar(20),
		@Day10 decimal
	)  
AS  
declare @ArmisConfigCount int  
declare @LateEntryConfigCount int  
declare @WorkHrsConfigCount int  
SELECT @ArmisConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Armis
SELECT @LateEntryConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Lateentry
SELECT @WorkHrsConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_WorkHrs
if @ArmisConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Armis(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,StartTime7,EndTime7,Day7,StartTime8,EndTime8,Day8,
		StartTime9,EndTime9,Day9,StartTime10,EndTime10,Day10) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,@StartTime7,@EndTime7,@Day7,@StartTime8,@EndTime8,@Day8,
		@StartTime9,@EndTime9,@Day9,@StartTime10,@EndTime10,@Day10)       
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Armis SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day5,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,
    	StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,StartTime7=@StartTime7,EndTime7=@EndTime7,Day7=@Day7,StartTime8=@StartTime8,EndTime8=@EndTime8,Day8=@Day8,
    	StartTime9=@StartTime9,EndTime9=@EndTime9,Day9=@Day9,StartTime10=@StartTime10,EndTime10=@EndTime10,Day10=@Day10
    	END
if @LateEntryConfigCount=0   
	BEGIN 
	    	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis  
	--	INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)       
	END    
else    
    BEGIN  
        	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis 
	--	UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno where YearSettingId=@YearSettingId 
	END 
if @WorkHrsConfigCount=0   
	BEGIN
	    	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis   
	--	INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)       
	END    
else    
    BEGIN  
        	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis 
	--	UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno where YearSettingId=@YearSettingId 
	END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePolicyConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <15-Oct-2021>
-- Description:	<Inserting Policy Configuration Details. This is specifically for Samsung Project. As per this only API's will block the cards>
-- Proc_TA_InsertUpdatePolicyConfiguration
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePolicyConfiguration]
	@Daily_Rrd	bit,
	@Daily_Hrs	int,
	@Day_Rqrd	bit,
	@Day_Value	int,
	@Weekly_Rqrd	bit,
	@Weekly_Hrs	int,
	@Quarterly_Rqrd	bit,
	@Quarterly_Hrs	int,
	@Cont_Absent	bit,	
	@Cont_Value	int,
	@ApprFolderPath varchar(max),
	@CreatedBy	int,
	@EmpAPI1 varchar(max),
	@EmpAPI2 varchar(max),
	@EmpAPI3 varchar(max),
	@BlockAPI varchar(max),
	@LogDownloadAPI varchar(max),
	@userName varchar(50),
	@pwd varchar(50),
	@dataProcessDate varchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	IF EXISTS(select Pol_Config_id from ta_tbl_policyconfiguration)
	BEGIN
		UPDATE ta_tbl_policyconfiguration SET
		Daily_Rrd=@Daily_Rrd,
		Daily_Hrs=@Daily_Hrs,
		Day_Rqrd=@Day_Rqrd,
		Day_Value=@Day_Value,
		Weekly_Rqrd=@Weekly_Rqrd,
		Weekly_Hrs=@Weekly_Hrs,
		Quarterly_Rqrd=@Quarterly_Rqrd,
		Quarterly_Hrs=@Quarterly_Hrs,
		Cont_Absent=@Cont_Absent,
		Cont_Value=@Cont_Value,		
		ModifiedDate=GETDATE(),		
		ModifiedBy=@CreatedBy,
		ApproFolderPath=@ApprFolderPath,
		EmpAPI1 =@EmpAPI1,
		EmpAPI2 =@EmpAPI2,
		EmpAPI3=@EmpAPI3,
		BlockAPI =@BlockAPI,
		LogDownloadAPI=@LogDownloadAPI,
		username=@userName,
		password=@pwd,
		DataProcessDate=@dataProcessDate
		UPDATE [dbo].[ta_tbl_BiostarAPIDetails] 
		SET [APIURL] = @BlockAPI,[BiostarUsername] = @userName,[BiostarPassword] = @pwd,[Modifyby] = @Createdby,[Modifydate] = GETDATE() 
		--WHERE APIID=@APIID
	END
	ELSE
	BEGIN
		INSERT INTO ta_tbl_policyconfiguration 
		(
			Daily_Rrd,
			Daily_Hrs,
			Day_Rqrd,
			Day_Value,
			Weekly_Rqrd,
			Weekly_Hrs,
			Quarterly_Rqrd,
			Quarterly_Hrs,
			Cont_Absent,
			Cont_Value,
			CreatedDate,
			CreatedBy,
			ApproFolderPath,
			EmpAPI1,
			EmpAPI2,
			EmpAPI3,
			BlockAPI,
			LogDownloadAPI,
			username,
			password,
			DataProcessDate
		)
		VALUES
		(
			@Daily_Rrd,
			@Daily_Hrs,
			@Day_Rqrd,
			@Day_Value,
			@Weekly_Rqrd,
			@Weekly_Hrs,
			@Quarterly_Rqrd,
			@Quarterly_Hrs,
			@Cont_Absent,
			@Cont_Value,
			GETDATE(),
			@CreatedBy,
			@ApprFolderPath,
			@EmpAPI1,
			@EmpAPI2,
			@EmpAPI3,
			@BlockAPI,
			@LogDownloadAPI,
			@userName,
			@pwd,
			@dataProcessDate
		)
		INSERT INTO [dbo].[ta_tbl_BiostarAPIDetails]([APIURL],[BiostarUsername],[BiostarPassword],[isMainAPI],[Createdby],[createdDate]) 
		VALUES(@BlockAPI,@userName,@pwd,0,@Createdby,GETDATE())
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateProject]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<P.Velumani>
-- Create date: <03-Jan-2020>
-- Description:	<Insert and Update of Project information stored into database through this procedure>
-- [Proc_TA_InsertUpdateProject]0,'Coimabtore Project','PR001','a','','','','yet to start',0,1,1,12,
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateProject]
	@ProjectId bigint,
	@Project_Name varchar(250),
	@Project_Code varchar(15),
	@Client_Name varchar(150),
	@Project_Description varchar(500),
	@Project_StartTime datetime,
	@Project_EndTime datetime,
	@Project_Status varchar(15),
	@IsDeleted bit,
	@userId bigint,
	@LevelID int,
	@ManDays varchar(10),
	@ManHours varchar(10),
	@TableXML XML =NULL
AS
BEGIN
	SET NOCOUNT ON;
		DECLARE @Index INT 
		set @Index= 0
		declare @Error nvarchar(Max)
		EXEC sp_xml_preparedocument @Index OUTPUT, @TableXML
		declare @TaskList table(TaskID int, TaskName nvarchar(250),Hours varchar(20))
		INSERT INTO @TaskList (TaskID,TaskName,Hours)
		select * from OPENXML(@Index, '/NewDataSet/TaskDetails')
		WITH(TaskID nvarchar(10) 'TaskID',TaskName nvarchar(250) 'TaskName',Hours varchar(20) 'Hours') 
		if(@ProjectId = 0)
			Begin
				insert into TA_Tbl_Project(Project_Name,Project_Code,Client_Name,Project_Description,Project_StartTime,Project_EndTime,Project_Status,IsDeleted,Created_By,Created_On,LevelID,Mandays,ManHours) values (@Project_Name,@Project_Code,@Client_Name, @Project_Description,@Project_StartTime,@Project_EndTime,@Project_Status,@IsDeleted,@userId,getdate(),@LevelID,@Mandays,@ManHours)
				 set @ProjectId = SCOPE_IDENTITY()
				 insert into TA_tbl_ProjectTaskList(ProjectID,TaskName,TaskHours) 
				 Select @ProjectId,TaskName,Hours from @TaskList
			End
		else 
			Begin
				update TA_Tbl_Project 
				set
				Project_Name = @Project_Name,
				Project_Code = @Project_Code,
				Client_Name = @Client_Name, 
				Project_Description = @Project_Description,
				Project_StartTime = @Project_StartTime,
				Project_EndTime = @Project_EndTime,
				Project_Status = @Project_Status,
				IsDeleted = @IsDeleted,
				Modified_By = @userId,
				Modified_On = getdate(),
				LevelID=@LevelID,
				Mandays=@Mandays,
				ManHours=@ManHours
				where Project_Id = @ProjectId
				delete from TA_tbl_ProjectTaskList where ProjectID=@ProjectId
				insert into TA_tbl_ProjectTaskList(ProjectID,TaskName,TaskHours) 
				Select @ProjectId,TaskName,Hours from @TaskList
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateType]
	@Opr as nvarchar(1),
	@Type as nvarchar(50),
	@EmpID as int,
	@TypeID as int,
	@IsFlexible as bit =False,
	@Isdisply_MyProf int
AS
BEGIN
	IF (@Opr='I')
	BEGIN
		INSERT INTO Ta_tbl_Type (TypeName,IsDeleted,EmpId,IsFlexible,Isdisply_MyProf) values (@Type,0,@EmpID,@IsFlexible,@Isdisply_MyProf)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_Type set TypeName=@Type,EmpId = @EmpID,IsFlexible=@IsFlexible,Isdisply_MyProf=@Isdisply_MyProf where TypeId=@TypeID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateWhatsAppScheduleDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_InsertUpdateWhatsAppScheduleDetails 'Test',41,'Daily','Monday','Monday','Monday',1,1,1,'10:30 AM',1,1,1,'PortableDocFormat',1
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateWhatsAppScheduleDetails]
(
	@ScheduleName varchar(250),
	@ReportId int,
	@Frequency varchar(20),
	@DayToSend varchar(10),
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateToSend int,
	@DateFrom int,
	@DateTo int,
	@TimeToSend varchar(20),
	@EmployeeId int,
	@WhatsAppSendType int,
	@FileType varchar(20),
	@Enabled int,
	@ScheduleId int,
	@Type varchar(2),
	@ReportName varchar(50),
	@ToWhom int,
	@TimeSendOption int=null,
	@Reminder_afterDays int=null
)
AS
BEGIN

	SET NOCOUNT ON;
	IF(@Type = 'I')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_WhatsAppSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0)
		BEGIN		
			INSERT INTO TA_Tbl_WhatsAppSchedule (ScheduleName,ReportId,Frequency,DayToSend,DayFrom,DayTo,DateToSend,DateFrom,DateTo,TimeToSend,EmployeeId,WhatsAppSendType,FileType,Enabled,IsDeleted,ReportName,ToWhom,TimeSendOption,Reminder_afterDays)
			VALUES(@ScheduleName,@ReportId,@Frequency,@DayToSend,@DayFrom,@DayTo,@DateToSend,@DateFrom,@DateTo,@TimeToSend,@EmployeeId,@WhatsAppSendType,@FileType,@Enabled,0,@ReportName,@ToWhom,@TimeSendOption,@Reminder_afterDays)
			SELECT CAST(@@IDENTITY AS INT) AS InsertedId
		END
		ELSE
		BEGIN
			SELECT 0
		END
	END
	ELSE IF(@Type = 'U')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_WhatsAppSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0 and ScheduleId<>@ScheduleId)
		BEGIN
			UPDATE TA_Tbl_WhatsAppSchedule SET ScheduleName = @ScheduleName,ReportId = @ReportId,Frequency = @Frequency,DayToSend = @DayToSend,
			DayFrom = @DayFrom,DayTo = @DayTo,DateToSend = @DateToSend, DateFrom = @DateFrom, DateTo = @DateTo, TimeToSend=@TimeToSend,
			EmployeeId = @EmployeeId, WhatsAppSendType = @WhatsAppSendType, FileType = @FileType, Enabled = @Enabled,IsDeleted =0,
			ReportName=@ReportName,ToWhom=@ToWhom,TimeSendOption=@TimeSendOption,
			Reminder_afterDays=@Reminder_afterDays
			where ScheduleId = @ScheduleId 
			SELECT 1
		END
		ELSE 
		BEGIN
		    SELECT 0
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateWhatsAppScheduleFilters]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateWhatsAppScheduleFilters]
(
	@ScheduleId int,
	@Filters varchar(max),
	@ReportType varchar(25),
	@Type varchar(2),
	@CompanyId int
)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type  = 'I')
		BEGIN
			insert into TA_Tbl_WhatsAppScheduleFilters (ScheduleId,Filters,ReportType,CompanyId) values (@ScheduleId,@Filters,@ReportType,@CompanyId)
		END
	else
		BEGIN
			update TA_Tbl_WhatsAppScheduleFilters set Filters=@Filters, ReportType=@ReportType,
			CompanyId= @CompanyId where ScheduleId=@ScheduleId
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUserName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_InsertUserName 'U',1,'SuperAdmin',0,0,0,'1','04/05/2012 4:11:13 PM',1
-- =============================================
-- Proc_TA_InsertUserName 'U',1,'??????',0,1,0,'1',''
-- Author:		senthil
-- ALTER  date: 13-Aug-07
-- Description:	Inserting/Updating usergroups name
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_InsertUserName]
	(
		@opr varchar(1),
		@groupId int,
		@groupName nvarchar(250),
		@isdeleted bit,
		@IndividualUsers bit,
		@hasSpecialRights bit,
		@emp_id nvarchar(100),
		@timestamp datetime,
		@ReportsBasedOn bit,
		@AllowLeaveApprovalPastEntry bit
	)
AS
BEGIN
	--Insert
	declare @sql as nvarchar(2000)
	if (@opr='I')
		Begin
			--insert into ta_tbl_usergroup (groupname,isDeleted,Emp_id) values (@groupname,0,@emp_Id)
			set @sql = 'insert into ta_tbl_usergroup (groupname,isDeleted,Emp_id,IndividualUsers,hasSpecialRights,ReportsBasedOn,AllowLeaveApprovalPastEntry) values (N''' +  @groupname + ''',0, ' + @emp_Id +',' + cast(@IndividualUsers as nvarchar(5)) + ',' + cast(@hasSpecialRights as nvarchar(5)) + ',' + cast(@ReportsBasedOn as nvarchar(5)) + ',' + cast(@AllowLeaveApprovalPastEntry as nvarchar(5)) + ')'
exec(@sql)
		End
	--Update
	if (@opr='U')
		Begin
			--update ta_tbl_usergroup set groupname=@groupname,isDeleted=0,Emp_id=emp_id,timestamp=getDate() where groupId=@groupId
			set @sql = 'update ta_tbl_usergroup set groupname=N'''+ @groupname + ''', isDeleted=0,Emp_id=' + @emp_id + ',timestamp=getDate(), IndividualUsers=' + cast(@IndividualUsers as nvarchar(5)) +',ReportsBasedOn=' + cast(@ReportsBasedOn as nvarchar(5)) +',AllowLeaveApprovalPastEntry=' + cast(@AllowLeaveApprovalPastEntry as nvarchar(5)) +', hasSpecialRights=' + cast(@hasSpecialRights as nvarchar(5)) +' where groupname != ''SuperAdmin'' And  groupId=' + cast (@groupId as nvarchar)
			exec(@sql)
		End
	--Delete
	if (@opr='D')
		Begin
			update ta_tbl_usergroup set isdeleted=1,timestamp=getdate() where groupname !='SuperAdmin' and groupId=@groupId
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertWhatsAppNumberForMessageTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertWhatsAppNumberForMessageTriggering] 
	-- Add the parameters for the stored procedure here
	@WhatsAppScheduleId int,
	@WhatsAppType varchar(5),
	@MobileNumber varchar(250)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	if((Select Count(*) From TA_tbl_WhatsAppNumberForTriggeringMessage where ScheduleId=@WhatsAppScheduleId and MobileNum=@MobileNumber)!=1)
	Begin
		insert into TA_tbl_WhatsAppNumberForTriggeringMessage (ScheduleId,WhatsAppType,MobileNum) values (@WhatsAppScheduleId,@WhatsAppType,@MobileNumber)
	End

	
END

--Select * From TA_tbl_WhatsAppNumberForTriggeringMessage
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertWhatsAppScheduleStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertWhatsAppScheduleStatus] 
	-- Add the parameters for the stored procedure here
	@ScheduleId int,
	@DurationFrom datetime,
	@DurationTo datetime,
	@SentDate datetime,
	@Status int,
	@To_Mail varchar(20)=null,
	@EmailID varchar(max)=null,
	@ErrorMessage nvarchar(max)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  IF(@ErrorMessage!='MailSendSuccessfully')
    BEGIN    
		INSERT INTO TA_tbl_WhatsAppScheduleStatus VALUES 
		(@ScheduleId,@DurationFrom,@DurationTo,GETDATE(),@Status,@To_Mail,@EmailID,@ErrorMessage)
	END
	--IF(@Status=1)
	--BEGIN
	--	IF EXISTS(SELECT ScheduleId FROM TA_Tbl_WhatsAppSchedule where ScheduleId=@ScheduleId and Reminder_afterDays!=0)
	--	BEGIN
	--		Declare @reminderDate int
	--		SELECT @reminderDate=Reminder_afterDays FROM TA_Tbl_WhatsAppSchedule where ScheduleId=@ScheduleId 
	--		--IF(@reminderDate!=0)
	--		--BEGIN
	--		--	IF NOT EXISTS(SELECT ScheduledID FROM Ta_Tbl_EmailScheduleReminder where ScheduledID=@ScheduleId and CONVERT(varchar(11),ReminderDate)=CONVERT(varchar(11),dateadd(d,@reminderDate,GETDATE())))
	--		--	BEGIN
	--		--		INSERT INTO Ta_Tbl_EmailScheduleReminder VALUES(@ScheduleId,DATEADD(d,@reminderDate,@SentDate),0,@DurationFrom,@DurationTo)
	--		--	END
	--		--END
	--		IF(@ErrorMessage='MailSendSuccessfully')
	--		BEGIN
	--			UPDATE TA_Tbl_EmailSchedulereminder SET STATUS=1 where ScheduledID=@ScheduleId and CONVERT(varchar(11),reminderdate)=CONVERT(varchar(11),getdate())
	--		END
	--	END
	--END
END

--Select * From TA_tbl_WhatsAppScheduleStatus


--Select * From TA_tbl_EmailScheduleStatus

--Delete From TA_tbl_EmailScheduleStatus where  id in(175,176)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- Author:  Arun vinoth    
-- ALTER  date: 09 Aug 07    
-- Description: Insert Year closure table 
-- Modified by : Prabakaran.P
-- Modified on : 24-Mar-08   
--	Modified By		:	Manjula.P
--	Modified Date	:	26-Jul-2013
--	Descriptions	:	Changing decimal to deciaml(18,2) datatype for current quota.
--	Proc_TA_InsertYearclosure 'I',1,21,1,9.5,1
-- =============================================    
CREATE  PROCEDURE [dbo].[Proc_TA_InsertYearclosure]     
	@Type CHAR,    
	@OrgLevelId INT,    
	@Employee_Id INT,    
	@LeaveTypeID INT,    
	@Current_Quota DECIMAL(18,2),    
	@auEmpId INT
AS    
BEGIN    
	SET NOCOUNT ON;    
	Declare @Year_SettingID INT    
	Declare @Count INT    
	Declare @YearClosure VARCHAR(50)    
	IF (@Type='U')    
	BEGIN     
		
		UPDATE Ta_Tbl_Yearclosure SET Current_Quota=0,Available_Leaves=0 WHERE LeaveTypeID=@LeaveTypeID AND Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id    
	END    
	select @Year_SettingID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
	select @Count=count(YearClosureId) from Ta_Tbl_Yearclosure Where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID
	if (@Count=1)
	BEGIN
		Update Ta_Tbl_Yearclosure set	Current_Quota=@Current_Quota ,
										Available_Leaves=@Current_Quota + isnull(Carry_PrevYear,0)-isnull(Leave_Taken,0),Time_Stamp=getdate()      
		where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID     
	end
	else if (@Count=0)    
	begin
		
		Declare @UTCTimestamp varchar(20)

		Select @UTCTimestamp=dbo.GetUTCTimeZoneDateTime(@auEmpId) 

		Insert into Ta_Tbl_Yearclosure(Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID,Time_Stamp)    
		values (@Year_SettingID,@OrgLevelId,@Employee_Id,@LeaveTypeID,@Current_Quota,@Current_Quota,@auEmpId,@UTCTimestamp)    
	end
END  

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================    
-- Author	:  Prabakaran.P   
-- ALTER  date	:     
-- Description	: Insert New Leave Types in Year closure table 
-- Modified by 	: Manjula.P
-- Modified on 	:  26-Jul-2013
-- Descriptions	:	Changing decimal to deciaml(18,2) datatype for current quota.
-- =============================================    
CREATE   PROCEDURE [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]     
 -- Add the parameters for the stored procedure here    
 @OrgLevelId INT,    
 @Employee_Id INT,    
 @LeaveTypeID INT,    
 @Current_Quota DECIMAL(18,2),    
 @auEmpId INT    
AS    
BEGIN    
SET NOCOUNT ON;    
Declare @Year_SettingID INT    
Declare @Count INT    
Declare @YearClosure VARCHAR(50)    
	Set @Year_SettingID=(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)    
	Set @Count=(select count(YearClosureId) from Ta_Tbl_Yearclosure    
   	Where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID )    
if (@Count<=0)    
	begin
		Insert into Ta_Tbl_Yearclosure     
 		(Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID)    
 		values (@Year_SettingID,@OrgLevelId,@Employee_Id,@LeaveTypeID,@Current_Quota,@Current_Quota,@auEmpId)    
	end   
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   Procedure [dbo].[Proc_TA_InsertYearSetting]  
	@StartMonth varchar(30),  
	@StartYear varchar(30),  
	@EndMonth varchar(30),  
	@EndYear varchar(30), 
	@FromDate varchar(30),
	@ToDate varchar(30), 
	@Employee_Id int,
	@isTimezone bit
as  
Begin
	set nocount on
	declare @RecordExiststing as int  
	SELECT @RecordExiststing=count(*) FROM TA_Tbl_YearSetting
	if @RecordExiststing=0  
	begin  
		update TA_Tbl_YearSetting set IsActive=0  
		Insert into TA_Tbl_YearSetting(StartMonth,StartYear,EndMonth,EndYear,FromDate,ToDate,Emp_Id,IsActive,isTimezoneEnable)  
		values(@StartMonth,@StartYear, @EndMonth,@EndYear,@FromDate,@ToDate,@Employee_Id,1,@isTimezone)  
	end 
	else
	begin
		Insert into TA_Tbl_YearSetting(StartMonth,StartYear,EndMonth,EndYear,FromDate,ToDate,Emp_Id,IsActive,isTimezoneEnable)  
		values(@StartMonth,@StartYear, @EndMonth,@EndYear,@FromDate,@ToDate,@Employee_Id,0,@isTimezone)  
	end 
	DECLARE @HolidayCount INT
	DECLARE @YearSettingId int
	SELECT @YearSettingId=scope_identity()
	SELECT @HolidayCount=Count(*)FROM TA_Tbl_HolidaySettings WHERE YearSettingId=@YearSettingId
	IF @HolidayCount=0  
	BEGIN  
		INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(10,10,@YearSettingId)  
	END
	select @YearSettingId as YearSettingsID
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsrtTrnsfrDtls]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsrtTrnsfrDtls]
	@Emp_AutoID bigint,
	@Trnsfr_frm int,
	@Trnsfr_To int,
	@Trnsfr_EtyDteTme datetime,
	@Trnsfr_Dte datetime,
	@Etry_RsdBy int, 
	@NwDsgtonID int,
	@NwReprtngTo int,
	@NwApprvlAuthrty int,
	@Remarks varchar(500)='',
	@IsImprtd int=0,
	@Trnsfr_status varchar(10)='Approved'
AS
BEGIN	
	SET NOCOUNT ON;
	INSERT INTO TA_TBL_TRANSFER VALUES(@Emp_AutoID,@Trnsfr_frm,@Trnsfr_To,@Trnsfr_EtyDteTme,@Trnsfr_Dte,@Etry_RsdBy,@NwDsgtonID,@NwReprtngTo,@NwApprvlAuthrty
	,@Remarks,@IsImprtd,@Trnsfr_status)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_IsAuditTrailSaved]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_IsAuditTrailSaved  
Description : select from TA_Tbl_AuditTable to check whether is Audit Trail is saved before
Tables Included : TA_Tbl_AuditTable
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_IsAuditTrailSaved] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_AuditTable
END
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_LateEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[proc_TA_LateEntry]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(18) 
)
AS
BEGIN
	declare @sqlQuery as varchar(1500)
	declare @shfTime as dateTime
	set @shfTime = (select Shift_StartTime from ta_tbl_shift where shift_id = @shift)	
	declare @graceTime as decimal
	set @graceTime = (select shift_graceOutTime from ta_tbl_shift where shift_id=@shift)
	set @sqlQuery = ''	
	set @sqlQuery = @sqlQuery + ' select ta_tbl_Employee.LevelId,CONVERT(nvarchar(20),''' + cast( convert( nvarchar(20),@shfTime,108) as nvarchar(50))   + ''' ,108) as shiftIn	, dbo.TA_Tbl_Employee.Employee_Code_Id, CONVERT(nvarchar(20),dbo.TA_Tbl_ProcessedData.Date,101) as date,TA_Tbl_ProcessedData.InTime,ta_tbl_processeddata.shift_id,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_ProcessedData.LateIn,TA_Tbl_ProcessedData.Reason,(dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + dbo.TA_Tbl_Employee.Employee_LastName) as empname  , dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName  FROM  dbo.TA_Tbl_ProcessedData '
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.Employee_Id INNER JOIN'
	set @sqlQuery = @sqlQuery + ' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id INNER JOIN'
	set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' where ta_tbl_processeddata.LateIn <> ''0'' and ta_tbl_processeddata.LateIn <> ''00:00:00'' and ta_tbl_processedData.LateIn is not null' 
	set @sqlQuery = @sqlQuery + ' And     (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
	set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 
	set @sqlQuery = @sqlQuery + ' and (DATEDIFF(mi, CONVERT(datetime,dbo.TA_Tbl_ProcessedData.LateIn,101), CONVERT(datetime,''' + cast (@shfTime as nvarchar(50)) + ''', 101)) > ' + cast (@graceTime as nvarchar(20)) + ')'
	if not(@EmployeeName='' or @EmployeeName='0')
	begin
		set @sqlQuery = @sqlQuery + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
	end
	if not (@empId='' or @empId='0')
	begin
		set @sqlQuery = @sqlQuery + ' and ta_tbl_processedData.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
	end
	if not(@LevelID='' or @LevelID='0')
	begin
		set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.LevelId = ' + cast (@LevelId as nvarchar(50)) 
	end
	set @sqlQuery = @sqlQuery + ' order by dbo.TA_Tbl_ProcessedData.Date'
	Exec(@sqlQuery)		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveAvailedinMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_LeaveAvailedinMonth 500
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <10-Apr-2012>
-- Description:	<Leave availed in the month wise>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LeaveAvailedinMonth] 
	@LeaveApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @FromDate datetime
	Declare @ToDate datetime
    Declare @EmployeeId int
    select @EmployeeId=Employee_Id from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplicationId
    create table #TempLeave(EmployeeId int,LeaveApplication_Id int,Leave_FromDate datetime,Leave_ToDate datetime,MonthName varchar(25),NumberofDays float)
    insert into #TempLeave
    select LA.Employee_Id,LeaveApplication_Id,Leave_FromDate,Leave_ToDate,DATENAME(month,Leave_FromDate),sum(NumberOfDays) from TA_Tbl_LeaveApplication LA
    inner join TA_Tbl_YearSetting YS on LA.YearSettings_Id=YS.YearSettings_Id where Employee_Id=@EmployeeId and YS.IsActive=1 and LA.IsDeleted=0
    and LA.Status='Approved' and LA.Type <> 'Comp Off' group by Leave_FromDate,Leave_ToDate,DATENAME(month,Leave_FromDate),LeaveApplication_Id,LA.Employee_Id
    create table #TempLeave1(EmployeeId int,LeaveApplication_Id int,Leave_FromDate datetime,Leave_ToDate datetime,MonthName varchar(25),NumberofDays float)
    insert into #TempLeave1
    select LA.Employee_Id, LA.LeaveApplication_Id,LA.Leave_FromDate,LA.Leave_ToDate,DATENAME(month,LA.Leave_FromDate),ISNULL(SUM(TL.NumberofDays),0.0)
    from TA_Tbl_LeaveApplication LA left outer join #TempLeave TL on LA.Employee_Id=TL.EmployeeId and DATENAME(MONTH,LA.Leave_FromDate)=TL.MonthName
    where LA.LeaveApplication_Id=@LeaveApplicationId   group by 
    LA.LeaveApplication_Id,LA.Leave_FromDate,LA.Leave_ToDate,DATENAME(month,LA.Leave_FromDate),LA.Employee_Id
    create table #Month(Monthname varchar(30),Monthvalue int)
    insert into #Month values('January',1)
    insert into #Month values('February',2)
    insert into #Month values('March',3)
    insert into #Month values('April',4)
    insert into #Month values('May',5)
    insert into #Month values('June',6)
    insert into #Month values('July',7)
    insert into #Month values('August',8)
    insert into #Month values('September',9)
    insert into #Month values('October',10)
    insert into #Month values('November',11)
    insert into #Month values('December',12)
   select MonthName, NumberofDays from(select distinct #TempLeave1.MonthName, NumberofDays,Monthvalue from #TempLeave1 inner join #Month
	on #TempLeave1.MonthName=#Month.Monthname) A order by A.Monthvalue
	drop table #TempLeave1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveBalanceImport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Execute [Proc_TA_LeaveBalanceImport]
'<dsLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>659</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1>15.5</LeaveType1>
  </TblLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>956</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1 />
    <LeaveType2>16.5</LeaveType2>
  </TblLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>787</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1 />
    <LeaveType2 />
    <LeaveType3>18.5</LeaveType3>
  </TblLeaveBalance>
</dsLeaveBalance>'

*/
CREATE PROCEDURE [dbo].[Proc_TA_LeaveBalanceImport]
	@LeaveBalanceData XML = NULL
AS
BEGIN
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX))		
	DELETE FROM ImportFromExcel
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @LeaveBalanceData
	INSERT INTO ImportFromExcel	
	SELECT	ROW_NUMBER()over(order by EmployeeID),
			EmployeeID,
			convert(float,isnull(LeaveType1,0.0)),
			convert(float,isnull(LeaveType2,0.0)),
			convert(float,isnull(LeaveType3,0.0)),
			convert(float,isnull(LeaveType4,0.0)),
			convert(float,isnull(LeaveType5,0.0)),
			convert(float,isnull(LeaveType6,0.0)),
			convert(float,isnull(LeaveType7,0.0)),
			convert(float,isnull(LeaveType8,0.0)),
			convert(float,isnull(LeaveType9,0.0)),
			convert(float,isnull(LeaveType10,0.0)),
			convert(float,isnull(LeaveType11,0.0)),
			convert(float,isnull(LeaveType12,0.0)),
			convert(float,isnull(LeaveType13,0.0)),
			convert(float,isnull(LeaveType14,0.0)),
			convert(float,isnull(LeaveType15,0.0))		
	FROM OPENXML (@XMLParams, '/dsLeaveBalance/TblLeaveBalance', 2) WITH 
	(		
		[Sl.No]	int,
		EmployeeID	varchar(50),
		LeaveType1	varchar(50),
		LeaveType2	varchar(50),
		LeaveType3	varchar(50),
		LeaveType4	varchar(50),
		LeaveType5	varchar(50),
		LeaveType6	varchar(50),
		LeaveType7	varchar(50),
		LeaveType8	varchar(50),
		LeaveType9	varchar(50),
		LeaveType10 varchar(50),
		LeaveType11 varchar(50),
		LeaveType12 varchar(50),
		LeaveType13 varchar(50),
		LeaveType14 varchar(50),
		LeaveType15 varchar(50)
	) Tbl
	--LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employeeid
	--AND E.IsDeleted = 0 AND E.Employee_Status = 1
	Execute Proc_TA_BulkImportPrevLeaveBalance;
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_LeaveBonusAbsentees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-2007
-- Description:	Absentess reports
-- Proc_Ta_LeaveBonusAbsentees '04/04/2008','04/30/2009','','','1,2,3,4',0,0,'SuperAdmin',3
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_Ta_LeaveBonusAbsentees]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
	SET NOCOUNT ON;
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT dbo.TA_Tbl_EmployeeLevel.LevelID, dbo.TA_Tbl_EmployeeDesignation.DesignationId, dbo.TA_Tbl_Employee.Employee_Code_Id, CONVERT(nvarchar(20), '
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_ProcessedData.Date, 101) AS date, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + SPACE(1)' 
		set @sqlQuery = @sqlQuery + ' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') AS empname, dbo.TA_Tbl_ProcessedData.Attendance, replace(dbo.TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,' 
		set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, ta_tbl_shift.Shift_ShortName'
		set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_ProcessedData INNER JOIN'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.SwipeCardNo'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		Set @sqlQuery = @sqlQuery + ' inner JOIN dbo.TA_Tbl_Shift ON dbo.TA_Tbl_Shift.Shift_ID = dbo.TA_Tbl_ProcessedData.Shift_ID  '
 	        Set @sqlQuery = @sqlQuery + ' inner JOIN dbo.TA_Tbl_EmployeeBonusLeave ON dbo.TA_Tbl_EmployeeBonusLeave.EmployeeId = dbo.ta_tbl_Employee.Employee_Id  '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' WHERE (dbo.TA_Tbl_ProcessedData.Attendance = ''Absent'' OR dbo.TA_Tbl_ProcessedData.Attendance =''LA'' OR dbo.TA_Tbl_ProcessedData.Attendance = ''AL'' OR dbo.TA_Tbl_ProcessedData.LeaveCode = ''LOP'') AND (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0)AND (dbo.TA_Tbl_Employee.Report_Exclude = 0)'		
		set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
		set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
		if not(@EmployeeName='' or @EmployeeName='0')
			begin
				set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
			end
		if not (@empId='' or @empId='0')
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
			end
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryId = ' +cast(@employeeCategory as nvarchar(8))
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' +cast(@employeeType as nvarchar(8))
			end		
		if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlQuery = @sqlQuery + ' and (#EmpLevel.LevelId IN (' + @LevelId + '))' 
			end			
		set @sqlQuery = @sqlQuery + ' order by TA_Tbl_ProcessedData.Employee_Code_Id,dbo.TA_Tbl_ProcessedData.Date'
		exec(@sqlQuery)
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveTypeExist]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_LeaveTypeExist]
(
  @LeaveId BigInt,
  @LeaveType VarChar(50), 
  @LeaveDescription VarChar(10)
) 
AS
Set NoCount On
IF @LeaveId = 'Add'
	Begin
		SELECT ISNULL(COUNT(@LeaveId),0) FROM tbl_TA_LeaveType WHERE LeaveType = @LeaveType 
	End
Else If @LeaveId='Modify'
	Begin
		SELECT ISNULL(COUNT(@LeaveId),0) FROM tbl_TA_LeaveType WHERE  LeaveType = @LeaveType  AND LeaveDescription <>@LeaveDescription
	End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeavSancAuthority]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Proc_TA_LeavSancAuthority 3
CREATE    PROCEDURE [dbo].[Proc_TA_LeavSancAuthority]
@TitleID INT 
AS
BEGIN
	SELECT e.Employee_Id,(e.Employee_FirstName + ' - ' +(e.Employee_Code_Id)) as Employee_FirstName FROM TA_Tbl_Employee e
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	WHERE EDesig.DesignationId IN 
	(
		SELECT t.TitleId FROM Ta_Tbl_Title t inner join ta_tbl_grade g on t.gradeid=g.grade_id 
		where g.isdeleted=0 and g.grade_Level  <= (SELECT g.grade_Level 
		FROM Ta_Tbl_Title t inner join ta_tbl_grade g on t.gradeid=g.grade_id  where TitleId = @TitleID and g.isdeleted=0)
	) 
	And EDesig.EffectiveDate = (select top 1 EffectiveDate from Ta_Tbl_employeeDesignation where EmployeeID=E.Employee_ID and  EffectiveDate <= getDate() 
	order by EffectiveDate desc )
	AND e.Isdeleted=0 and e.Employee_Firstname<>'Administrator' and e.InActive_Status=0   ORDER BY e.Employee_FirstName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Insert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_Levels_Insert] 
(
	@levelName nvarchar(100),
	@parentLevelId int,
	@emp_id nvarchar(20)
)
AS
Begin
	declare @sql as nvarchar(1000)	
	--insert into Ta_Tbl_level (levelname,parentLevelId) values(@levelname,@parentLevelId);
	declare @recCount as int
	set @recCount = (select count(*) from ta_tbl_level where levelname=@levelName and isdeleted=0)
	if (@recCount=0)
	begin
		set @sql = 'insert into Ta_Tbl_level (levelname,parentLevelId,emp_id) values(N''' + @levelname + ''',' + cast(@parentLevelId as nvarchar(25)) + ',' + @emp_id + ')'	
		exec(@sql)
	end
	select @recCount as recCount	
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Modify]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Levels_Modify]
	(
	@levelId int,
	@levelName varchar(100),
	--@parentLevelId int,
	@description varchar(255),
	@city varchar(100),
	@state varchar(100),
	@country varchar(100),
	@zip varchar(50),
	@phone1 varchar(50),
	@phone2 varchar(50),
	@fax varchar(50),
	@mobile varchar(50),
	@email varchar(100),
	@web varchar(100)
)
AS
Begin
	update ta_tbl_level set levelname=@levelName where levelid=@levelID;
	declare @levId int;
	set @levId = (select levelid from ta_tbl_levelDetails where levelid=@levelId );
	if (@levId is null or @levID='')
		Begin
			insert into Ta_tbl_levelDetails (levelid,description,city,state,country,zip,phone1,phone2,fax1,fax2,email,webaddress) values (@levelId,@description,@city,@state,@country,@zip,@phone1,@phone2,@fax,@mobile,@email,@web);
		End
	else
		Begin
			update Ta_tbl_levelDetails set description=@description,city=@city,state=@state,country=@country,zip=@zip,phone1=@phone1,phone2=@phone2,fax1=@fax,fax2=@mobile,email=@email,webaddress=@web where levelId=@levelid
		End	
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ListofProjects]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <04-Jan-2020>
-- Description:	<Prjoect List page fields getting using this procedure>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ListofProjects]
@UserId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @UsergroupId bigint
	declare @UsergroupName varchar(25)
	select @UsergroupId = isnull(UserGroup_Id,0) from TA_Tbl_Employee where Employee_Id = @UserId
	select @UsergroupName = isnull(groupName,'') from TA_Tbl_Usergroup where groupId= @UsergroupId

	select isnull(Project_Id,0) as Project_Id,
	isnull(Project_Code,'') as Project_Code,
	isnull(Project_Name,'') as Project_Name,
	Project_StartTime,
	Project_EndTime,
	isnull(Project_Status,'') as Project_Status,
	(case when (@UsergroupName = 'SuperAdmin' and Project_Status = 'Completed') then 1 else 0 end) as IsDeleteAllowed,
	case when LevelID is not null and LevelID<>0 then (Select name from Ta_Tbl_levelDetails l where l.id=TA_Tbl_Project.LevelID) else '' end as LevelName,
	Mandays,ManHours
	From TA_Tbl_Project
	where (IsDeleted = 0)

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadEmployeeBasedOnReportingto]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoadEmployeeBasedOnReportingto]
	-- Add the parameters for the stored procedure here
	@EmployeeID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	select distinct * from (
    -- Insert statements for procedure here
	Select Employee_Id, (isnull(Employee_FirstName,'') + ' ' + isnull(Employee_LastName,'')) as EmployeeName from TA_Tbl_Employee where Employee_Id=@EmployeeID
	union all
	Select Employee_Id, (isnull(Employee_FirstName,'') + ' ' + isnull(Employee_LastName,'')) as EmployeeName from TA_Tbl_Employee where Reporting_To=@EmployeeID
	union all
	Select Employee_Id, (isnull(Employee_FirstName,'') + ' ' + isnull(Employee_LastName,'')) as EmployeeName from TA_Tbl_Employee where Leave_Sanc_Authority=@EmployeeID) A


END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadFirstYearLeaveQuota]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	19-Jul-2013
Descriptions	:	for selecting leave quota for the employee
Proc_TA_LoadFirstYearLeaveQuota 2,42
*/
CREATE proc [dbo].[Proc_TA_LoadFirstYearLeaveQuota]
(
@YearsettingsId int,
@EmployeeId int
)
as
begin
	SET NOCOUNT ON;
	declare @CurrentYear as int;
	declare @getFirstPreviousYearCount as int;
	declare @EndYear as int;
	declare @CountPolicy as int;
	set @EndYear=0;
	set @getFirstPreviousYearCount=0;
	set @CurrentYear=0;
	set @CountPolicy=0;
	set @CurrentYear=(select StartYear from TA_Tbl_YearSetting where YearSettings_Id=@YearsettingsId and IsActive=1)
	set @EndYear=(select EndYear from TA_Tbl_YearSetting where YearSettings_Id=@YearsettingsId and IsActive=1)
	set @getFirstPreviousYearCount=(select COUNT(*) from TA_Tbl_YearSetting where StartYear<@CurrentYear and EndYear<@EndYear)
	set @CountPolicy=(select COUNT(*) from TA_Tbl_Employee E
			inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on ELPD.EmpID=E.Employee_Id
			inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELPD.Policy_ID
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELPD.LeaveType_Id
			left join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=ELPD.Policy_ID and LPD.LeaveType_Id=LT.LeaveType_Id
			inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.LeaveTypeId=LT.LeaveType_Id and ELT.EmployeeId=E.Employee_Id
			where E.Employee_Id=@EmployeeId)
	if(@getFirstPreviousYearCount=0)
		begin
			if(@CountPolicy>0)
				begin
				select LT.LeaveType_Id as Id,LT.LeaveType as 'Leave Type',(ELT.PreviousYearBalance+LPD.MaxDays_avail)-(ELT.NoOffLeaveAvailed) as 'Number of Days' from TA_Tbl_Employee E
				inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on ELPD.EmpID=E.Employee_Id
				inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELPD.Policy_ID
				inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELPD.LeaveType_Id
				left join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=ELPD.Policy_ID and LPD.LeaveType_Id=LT.LeaveType_Id
				inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.LeaveTypeId=LT.LeaveType_Id and ELT.EmployeeId=E.Employee_Id
				where E.Employee_Id=@EmployeeId
				end
			else
				begin
				select LT.LeaveType_Id as Id,LT.LeaveType as 'Leave Type',(ELT.PreviousYearBalance+0)-(ELT.NoOffLeaveAvailed) as 'Number of Days' from TA_Tbl_Employee E
				inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.EmployeeId=E.Employee_Id
				inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELT.LeaveTypeId
				where E.Employee_Id=@EmployeeId
				end
		end
	else
		begin
			select 0 as Id
		end
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadingPunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_LoadingPunchTypes '2 OutTermi','In'
-- select * from ta_tbl_punchtypes
-- =============================================
-- Author:		<Angeswaran.S>
-- Create date: <14-Mar-2012>
-- Description:	<Loading the PunchType based on the terminal>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoadingPunchTypes] 
	@TerminalReaderId varchar(20),
	@TerminalType varchar(10)
AS
BEGIN	
		SET NOCOUNT ON;
		Declare @TerminalId int
		set @TerminalId =(select terminal_Id from ta_tbl_terminal where Terminal_ReaderId=''+ @TerminalReaderId+'')
		if(@TerminalType='Out')
			begin
				if(@TerminalReaderId='18000000')
					begin
						select distinct P.PunchType_Id,T.Terminal_Name+ '-' + PunchType as PunchType from ta_tbl_punchtypes P
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in 
						('Out','Shift Out','Break Out','Lunch Out','Official Out','In Duty') 
						AND P.Isdeleted = 0
					end
				else
					begin
						select PunchType_Id,T.Terminal_Name+ '-' + P.PunchType as PunchType from ta_tbl_punchtypes  P inner join 
						(select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Type='Out' and	entrance_id in 
						(select Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@TerminalId)) as A on P.Terminal_Id=A.Reader_Id 
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in  
						('Out','Shift Out','Break Out','Lunch Out','Official Out','In Duty') AND P.Isdeleted = 0
					end
			end
		else if(@TerminalType='In')
			begin
				if(@TerminalReaderId='18000000')
					begin
						select distinct P.PunchType_Id,T.Terminal_Name+ '-' + PunchType as PunchType from ta_tbl_punchtypes P
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in 
						('In','Shift In','Break In','Lunch In','Official In','Out Duty') AND P.Isdeleted = 0
					end
				else
					begin
						select PunchType_Id,T.Terminal_Name+ '-' + P.PunchType as PunchType from ta_tbl_punchtypes  P inner join 
						(select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Type='In' and	entrance_id in 
						(select Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@TerminalId)) as A on P.Terminal_Id=A.Reader_Id 
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in  
						('In','Shift In','Break In','Lunch In','Official In','Out Duty') AND P.Isdeleted = 0
					end
			end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadLeaveTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manjula.P>
-- Create date: <18-Jul-2013>
-- Description:	<Loading the leave Types for the Employee Master>
--	Proc_TA_LoadLeaveTypes 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoadLeaveTypes] 
	@YearSettignsId INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @CurrentYear AS INT;
	DECLARE @getFirstPreviousYearCount AS INT;
	DECLARE @EndYear AS INT;
	SET @EndYear=0;
	SET @getFirstPreviousYearCount=0;
	SET @CurrentYear=0;
	SELECT @CurrentYear=StartYear,@EndYear=EndYear FROM TA_Tbl_YearSetting WHERE YearSettings_Id=@YearSettignsId and IsActive=1
	--SELECT @getFirstPreviousYearCount=COUNT(*) FROM TA_Tbl_YearSetting WHERE StartYear<@CurrentYear and EndYear<@EndYear
	--IF(@getFirstPreviousYearCount=0)
	--BEGIN
		SELECT LeaveType_Id as Emp_LeaveType_Id,LeaveType,LeaveDescription=LeaveDescription + ' ('+LeaveType+')' FROM ta_tbl_leaveType WHERE isdeleted=0
	--END
	--ELSE
	--BEGIN
	--	SELECT 0 as Emp_LeaveType_Id;
	--END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadShiftByLevelsId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	26-Dec-2013
Descriptions	:	Getting shifts based on selected levels in temp weekday
Proc_TA_LoadShiftByLevelsId '1,2,3,12,4,16,11,14,13,18,20,22,24'
*/
CREATE proc [dbo].[Proc_TA_LoadShiftByLevelsId]
(
@LevelIds nvarchar(max)
)
as
begin
	declare @SchemaName as varchar(200);
	set @SchemaName=(SELECT top 1 specific_schema FROM INFORMATION_SCHEMA.Routines where specific_name='Func_TA_GetParentIds')
	declare @SQLQuery as nvarchar(max);
	set @SQLQuery='select ['+@SchemaName+'].Func_TA_GetParentIds('''+cast(@LevelIds as varchar(250))+''')  ';
	create table #Temp
	(
	LevelId varchar(250)
	)
	insert into #Temp
	exec(@SQLQuery);
	select @LevelIds= (select LevelId from #Temp);
	select Shift_Id,Shift_ShortName+' :'+Shift_StartTime+' To '+Shift_EndTime as Shift_ShortName,
	cast(Shift_StartTime as datetime) as Shift_StartTime,
	case when Shift_EndTime like '%AM' then DATEADD(DAY,1,cast(Shift_EndTime as datetime))
	else cast (Shift_EndTime as datetime) end as Shift_EndTime
	from TA_Tbl_Shift
	where Level_Id in (select Value from dbo.Split(@LevelIds,','))
	drop table #Temp
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoanHandling]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoanHandling] 

	-- Add the parameters for the stored procedure here
	@tag char(3),
	@EmployeeAutoID int,
	@LoanID int,
	@CreditAmount bigint,
	@Date nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	SET NOCOUNT ON;

    -- Insert statements for procedure here
	if(@tag='I')
	Begin
		Insert into TA_Tbl_LoanTransaction (LoanID,TransactionDate,CreditedAmount,Balance_Amount,Remaining_DueMonth)
		values(@LoanID,@Date,@CreditAmount,
		Case when (Select Count(*) From TA_Tbl_LoanTransaction where LoanID=@LoanID)>0 then (Select CreditedAmount-Loan_BalanceAmount From TA_Tbl_LoanTransaction inner join TA_Tbl_LoanEntryDetails on Loan_ID=LoanID)
		Else (Select Loan_BalanceAmount From TA_Tbl_LoanEntryDetails where Loan_ID=@LoanID and Employee_Id=@EmployeeAutoID) - @CreditAmount End,
		Case when (Select Count(*) From TA_Tbl_LoanTransaction where LoanID=@LoanID )>0 then (Select Total_DeductionMonth From TA_Tbl_LoanEntryDetails where Loan_ID=@LoanID) - (Select Count(*) From TA_Tbl_LoanTransaction where LoanID=@LoanID )
		Else (Select Total_DeductionMonth From TA_Tbl_LoanEntryDetails where Loan_ID=@LoanID) -1 End )

	End
	
	Else if(@tag='S')
	Begin
		Select * From TA_Tbl_LoanTransaction inner Join TA_Tbl_LoanEntryDetails on Loan_ID=LoanID where LoanID=@LoanID and TransactionDate=@Date and ISLoanClose=0 and isdeleted!=1
	End

	Else IF(@tag='U')
	Begin
	
		Update TA_Tbl_LoanTransaction set CreditedAmount=@CreditAmount where LoanID=@LoanID and TransactionDate=@Date

		Update TA_Tbl_LoanEntryDetails set Loan_BalanceAmount=Loan_BalanceAmount-@CreditAmount Where Loan_ID=@LoanID

	End

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LocationNameExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LocationNameExists]
	@locationname nvarchar(250)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT count(*)as Total from ta_tbl_landmarks where locationname=@locationname
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoginOrNot]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoginOrNot] 
	@userId as nvarchar(15),
    @ipAddress as nvarchar(15),
    @sessionId as nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ConcurrentUserId, LoginTime  FROM TA_Tbl_ConcurrentUser where UserId = @userId AND IpAddress = @ipAddress AND status=1 AND SessionId = @sessionId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutAdmin]
	-- Add the parameters for the stored procedure here
	@UserId as nvarchar(15)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_ConcurrentUser WHERE UserId = @UserId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutUser] 
	-- Add the parameters for the stored procedure here
	(@ConcurrentUserId varchar(1000))
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		SET @Query='DELETE TA_Tbl_ConcurrentUser WHERE ConcurrentUserId in (' + @ConcurrentUserId + ')'
EXEC (@Query) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUserOwn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutUserOwn]
	-- Add the parameters for the stored procedure here
	@UserId nvarchar(15),  
	@IpAddress nvarchar(15),  
	@SessionId nvarchar(25)  
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM ta_tbl_concurrentuser where UserId=@UserId and IpAddress=@IpAddress and SessionId=@SessionId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LookupTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- Create date: 21 July 2007
-- Description:	Look up Table Queries
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LookupTable] 
@Type CHAR(1),
@ID INT
AS
BEGIN
	SET NOCOUNT ON;
	IF (@Type='C')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=1 and isdeleted=0
	ELSE IF (@Type='S')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=2 AND Parent=@ID and isdeleted=0
	ELSE IF (@Type='T')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=3 AND Parent=@ID and isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ManualTimeEntryExport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*   
Procedure Name : Proc_TA_RptManualTimeEntry    
Description : select manual time entry details
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : Gopinath.K
Created On : 10-Sep-2013
Proc_TA_ManualTimeEntryExport '','','2014/08/01','2014/08/01','0,39',0,0,'SuperAdmin','0','All','',0,0,'Both'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ManualTimeEntryExport] 
(
	-- Add the parameters for the stored procedure here
	@EmpAutoID int,
	@employeeName nvarchar(50),
	@employeeId nvarchar(15),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10)	
)
AS
declare @sqlQuery as varchar(8000)  
set @sqlQuery = ''  
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	DECLARE @timeformat as int
	DECLARE @time as nvarchar(25)
	SELECT @time=TimeFormat FROM TA_Tbl_DateandTimeFormat
	if(@time='HH:mm')
		BEGIN
			SET @timeformat=108
		END
	ELSE
		BEGIN
			SET @timeformat=109
		END
BEGIN
	SET NOCOUNT ON;
	--Temporary table's creation
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlEmpLevel=
		'insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,'''+cast(@toDate as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''')'
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@toDate as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(8)) + ''')'
	Execute(@sqlEmpDesi)
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@toDate as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
	Execute(@sqlEmpType)
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@toDate as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
	Execute(@sqlEmpCategory)
	SET NOCOUNT ON;
	set @sqlQuery = @sqlQuery + ' SELECT distinct ISNULL(TA_Tbl_Employee.Employee_FirstName, '' '') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, '' '') AS Employee_Name,' 
	set @sqlQuery = @sqlQuery + '  replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id, dbo.TA_Tbl_Employee.Employee_Code_Id as ManualTimeEntry_Employee_Id, Convert(varchar, TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date, case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate, '+cast(@dateFormat as varchar(100))+') end AS ManualTimeEntry_InDate, case when '+cast(@timeformat as varchar(100))+'=108 then convert(char(5),cast(TA_Tbl_ManualTimeEntry.ManualTimeEntry_InTime as datetime),108)
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_InTime end as ManualTimeEntry_InTime, case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate, '+cast(@dateFormat as varchar(100))+') end AS ManualTimeEntry_OutDate, 
	case when '+cast(@timeformat as varchar(100))+'=108 then convert(char(5),cast(TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutTime as datetime),108)
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutTime end as ManualTimeEntry_OutTime,  replace(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Reason,''&amp;'',''&'') as ManualTimeEntry_Reason,TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status,
	TA_Tbl_Title.TitleName,TA_Tbl_Employee.Gender,TA_Tbl_ManualTimeEntry.ManualTimeEntry_InPunchType,TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutPunchType '		set @sqlQuery = @sqlQuery + ' FROM TA_Tbl_Employee' 
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_ManualTimeEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id'	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' WHERE ((TA_Tbl_Employee.Employee_Status = 1) 
	or(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)
	>= 
	convert(varchar(11),TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,102))) 
	AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) AND (TA_Tbl_ManualTimeEntry.IsOnDuty=0)'
	--********************************End***************************************************************************************************
	set @sqlQuery = @sqlQuery + ' AND ((TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate >= CONVERT(DATETIME, '''+cast(@fromdate as nvarchar(20))+''', 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate <= CONVERT(DATETIME, '''+cast(@todate as nvarchar(20))+''', 102) )'
	set @sqlQuery = @sqlQuery + ' or (TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate >= CONVERT(DATETIME, '''+cast(@fromDate as nvarchar(20))+''', 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate <= CONVERT(DATETIME, '''+cast(@toDate as nvarchar(20))+''', 102) ))'		 	
	IF not (@employeeName='')  
		BEGIN
		 Declare @Tempname nvarchar(200)
         set @Tempname= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
	     set @sqlQuery = @sqlQuery + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 
	    END
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	 
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	if not (@employeeId='')  
  begin  
   set @SqlQuery = @SqlQuery + ' and ta_tbl_employee.Employee_Code_Id = ''' + cast (@employeeId as nvarchar(50)) + ''' '  
  end  
	if not(@Status='' or @Status='All')
		begin
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status = ''' + @Status + ''''
		end	
	set @sqlQuery = @sqlQuery + ' order by TA_Tbl_Employee.Employee_Code_Id'
	EXEC (@sqlQuery)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_MappingCorrespondingPunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 25-08-2014
-- Description:	Map the corresponding punch details
-- select * from ta_tbl_MatchedPunches where Clk_Date='2014-08-11' and Clk_EmpId='787'
-- Break In Came
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-11 00:00:00.000','1900-01-01 11:02:00.000','Break In','2014-08-11 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '788','787','2014-08-04 00:00:00.000','1900-01-01 11:13:00.000','Break In','2014-08-18 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:15:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:14:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:10:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:09:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:07:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:25:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:08:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:05:00.000','Break In','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:12:00.000','Break In','2014-08-04 00:00:00.000'
-- Break Out came
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-11 00:00:00.000','1900-01-01 11:00:00.000','Break Out','2014-08-11 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','787','2014-08-04 00:00:00.000','1900-01-01 11:10:00.000','Break Out','2014-08-04 00:00:00.000'
-- Proc_Ta_MappingCorrespondingPunches '787','788','2014-07-09 00:00:00.000','1900-01-01 09:00.000','Break Out','2014-07-09 00:00:00.000'
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_MappingCorrespondingPunches]
	-- Add the parameters for the stored procedure here
@clk_empid NVARCHAR(20),
@clk_InOrOutDeviceId VARCHAR(20),
@clk_InOrOutDate DATETIME,
@clk_InOrOutTime DATETIME,
@clk_InOrOutPunchType VARCHAR(25),
@clk_date DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	CREATE TABLE #TempInPunchDetails
	(
		TempInPunch_AutoId INT IDENTITY(1,1),
		TempInPunch_clk_empid NVARCHAR(20),
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		TempInPunch_clk_date DATETIME
	)
	CREATE TABLE #TempOutPunchDetails
	(
		TempOutPunch_AutoId INT IDENTITY(1,1),
		TempOutPunch_clk_empid NVARCHAR(20),
		TempOutPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempOutPunch_clk_InOrOutDate DATETIME,
		TempOutPunch_clk_InOrOutTime DATETIME,
		TempOutPunch_clk_InOrOutPunchType VARCHAR(25),
		TempOutPunch_clk_date DATETIME,
		TempOutPunch_MappedOrNot INT,
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25)		
	)	
	CREATE TABLE #TempInPunchDetails1
	(
		TempInPunch_AutoId INT IDENTITY(1,1),
		TempInPunch_clk_empid NVARCHAR(20),
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		TempInPunch_clk_date DATETIME
	)
	CREATE TABLE #TempOutPunchDetails1
	(
		TempOutPunch_AutoId INT IDENTITY(1,1),
		TempOutPunch_clk_empid NVARCHAR(20),
		TempOutPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempOutPunch_clk_InOrOutDate DATETIME,
		TempOutPunch_clk_InOrOutTime DATETIME,
		TempOutPunch_clk_InOrOutPunchType VARCHAR(25),
		TempOutPunch_clk_date DATETIME,
		TempOutPunch_MappedOrNot INT,
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		OrderBy int default 787
	)		
	IF(@clk_InOrOutPunchType='Break Out' or @clk_InOrOutPunchType='Break In')
		BEGIN		
			DELETE FROM ta_tbl_MatchedPunches WHERE Clk_EmpId=@clk_empid and Clk_Date=@clk_date
			and (Clk_InPunchType='Break Out' or Clk_OutPunchType='Break In')
			INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutDate + ' '+ Clk_OutTime,Clk_OutPunchType,Clk_Date,0 FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_OutPunchType='Break Out'
			ORDER BY Clk_OutDate+' '+Clk_OutTime
			--Before Adding this procedure means,we need to enable below line
			--IF(@clk_InOrOutPunchType='Break Out')
			--	BEGIN
			--		INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date)
			--		VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
			--	END
			INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InDate+' '+Clk_InTime,Clk_InPunchType,Clk_Date FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_InPunchType='Break In'
			ORDER BY Clk_InDate +' '+Clk_InTime
			--Before Adding this procedure means,we need to enable below line
			--IF(@clk_InOrOutPunchType='Break In')
			--	BEGIN
			--		INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			--		VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
			--	END
			--For ordering the Datetime
			INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,0 FROM #TempOutPunchDetails WHERE TempOutPunch_clk_date=@clk_date and TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_InOrOutPunchType='Break Out'
			ORDER BY TempOutPunch_clk_InOrOutTime
			INSERT INTO #TempInPunchDetails1(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType='Break In'
			ORDER BY TempInPunch_clk_InOrOutTime
		END
	IF(@clk_InOrOutPunchType='Official Out' or @clk_InOrOutPunchType='Official In')
		BEGIN		
			DELETE FROM ta_tbl_MatchedPunches WHERE Clk_EmpId=@clk_empid and Clk_Date=@clk_date
			and (Clk_InPunchType='Official Out' or Clk_OutPunchType='Official In')
			INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutDate + ' '+ Clk_OutTime,Clk_OutPunchType,Clk_Date,0 FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_OutPunchType='Official Out'
			ORDER BY Clk_OutDate+' '+Clk_OutTime
			IF(@clk_InOrOutPunchType='Official Out')
				BEGIN
					INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date)
					VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
				END
			INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InDate+' '+Clk_InTime,Clk_InPunchType,Clk_Date FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_InPunchType='Official In'
			ORDER BY Clk_InDate +' '+Clk_InTime
			IF(@clk_InOrOutPunchType='Official In')
				BEGIN
					INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
					VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
				END
			--For ordering the Datetime
			INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,0 FROM #TempOutPunchDetails WHERE TempOutPunch_clk_date=@clk_date and TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_InOrOutPunchType='Official Out'
			ORDER BY TempOutPunch_clk_InOrOutTime
			INSERT INTO #TempInPunchDetails1(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType='Official In'
			ORDER BY TempInPunch_clk_InOrOutTime
		END
	DECLARE @MatchedPunchesTableCount INT
	DECLARE @InPunchTableCount INT
	DECLARE @MatchedPunchesTableStart INT
	DECLARE @InPunchTableStart INT
	--#TempOutPunchDetails variables
	DECLARE @TempOutPunchInOrOutTime DATETIME
	DECLARE @TempOutPunchAutoId INT
	DECLARE @matchedUpdateId INT
	--#TempInPunchDetails variables
	DECLARE @TempInPunch_Intime DATETIME
	DECLARE @TempInPunch_ClkInDate DATETIME
	DECLARE @TempInPunch_ClkInDeviceId VARCHAR(20)
	DECLARE @TempInPunch_ClkInPunchType VARCHAR(20)
	SET @MatchedPunchesTableStart =1
	SET @InPunchTableStart =1
	SET @MatchedPunchesTableCount=(SELECT COUNT(*) FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_date=@clk_date)
	SET @InPunchTableCount =(SELECT COUNT(*) FROM #TempInPunchDetails1 WHERE TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_date=@clk_date)
	--select @MatchedPunchesTableCount,@InPunchTableCount	
	select * from #TempInPunchDetails1
	select * from #TempOutPunchDetails1
	IF(@MatchedPunchesTableCount!=0 and @InPunchTableCount!=0)
		BEGIN
			WHILE @InPunchTableCount>0
				begin
					SELECT @TempInPunch_Intime=TempInPunch_clk_InOrOutTime,@TempInPunch_ClkInDate=TempInPunch_clk_InOrOutDate,@TempInPunch_ClkInDeviceId=TempInPunch_clk_InOrOutDeviceId,
					@TempInPunch_ClkInPunchType=TempInPunch_clk_InOrOutPunchType
					FROM #TempInPunchDetails1 WHERE TempInPunch_AutoId=@InPunchTableStart
					SELECT @TempOutPunchInOrOutTime=isnull(TempOutPunch_clk_InOrOutTime,0),@TempOutPunchAutoId=TempOutPunch_AutoId FROM #TempOutPunchDetails1 WHERE TempOutPunch_AutoId=@MatchedPunchesTableStart and TempOutPunch_MappedOrNot=0
					IF(@TempOutPunchInOrOutTime!='1900-01-01 00:00:00.000')
						BEGIN
							if @TempOutPunchInOrOutTime<=@TempInPunch_Intime
								BEGIN
									SET @matchedUpdateId=@TempOutPunchAutoId
									SET @TempOutPunchInOrOutTime=''
									SET @MatchedPunchesTableStart=@MatchedPunchesTableStart+1
									CONTINUE;
								END
							ELSE
								BEGIN
									IF(@matchedUpdateId!=0)
										BEGIN
											UPDATE #TempOutPunchDetails1 SET TempInPunch_clk_InOrOutDeviceId=@TempInPunch_ClkInDeviceId,
											TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate,
											TempInPunch_clk_InOrOutTime=@TempInPunch_Intime,
											TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType,
											TempOutPunch_MappedOrNot=1
											,OrderBy=@InPunchTableStart+3 
											WHERE TempOutPunch_AutoId=@matchedUpdateId
											UPDATE #TempOutPunchDetails1 SET TempOutPunch_MappedOrNot=1 where TempOutPunch_AutoId<@matchedUpdateId
											and TempOutPunch_MappedOrNot=0
											SET @matchedUpdateId=0
										END
									ELSE
										BEGIN
											IF((SELECT COUNT(*)FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid= @clk_empid and TempOutPunch_clk_date = @Clk_Date 
											and TempInPunch_clk_InOrOutTime=@TempInPunch_Intime and TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate 
											and TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType)=0)
											BEGIN
												INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,OrderBy)
												values(@clk_empid,@TempInPunch_ClkInDeviceId,@TempInPunch_ClkInDate,@TempInPunch_Intime,@TempInPunch_ClkInPunchType,@Clk_Date,@InPunchTableStart+3)
											END
										END
								END
						END
					ELSE
						BEGIN
							IF(@matchedUpdateId!=0)
								BEGIN
									UPDATE #TempOutPunchDetails1 SET TempInPunch_clk_InOrOutDeviceId=@TempInPunch_ClkInDeviceId,
									TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate,
									TempInPunch_clk_InOrOutTime=@TempInPunch_Intime,
									TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType,
									TempOutPunch_MappedOrNot=1,
									OrderBy=@InPunchTableStart+3
									WHERE TempOutPunch_AutoId=@matchedUpdateId
									UPDATE #TempOutPunchDetails1 SET TempOutPunch_MappedOrNot=1 where TempOutPunch_AutoId<@matchedUpdateId
									and TempOutPunch_MappedOrNot=0
									SET @matchedUpdateId=0
								END
							ELSE
								BEGIN
									IF((SELECT COUNT(*)FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid= @clk_empid and TempOutPunch_clk_date = @Clk_Date 
									and TempInPunch_clk_InOrOutTime=@TempInPunch_Intime and TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate 
									and TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType)=0)
											BEGIN
												INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,OrderBy)
												values(@clk_empid,@TempInPunch_ClkInDeviceId,@TempInPunch_ClkInDate,@TempInPunch_Intime,@TempInPunch_ClkInPunchType,@Clk_Date,@InPunchTableStart+3)
											END
								END
						END
					SET @InPunchTableCount=@InPunchTableCount-1
					SET @InPunchTableStart=@InPunchTableStart+1
					--SET @MatchedPunchesTableStart=@MatchedPunchesTableStart+1
				END
				IF(@InPunchTableCount<=0)
					BEGIN
						INSERT INTO ta_tbl_MatchedPunches 
						SELECT 	TempOutPunch_clk_empid,
						TempOutPunch_clk_InOrOutDeviceId,
						TempOutPunch_clk_InOrOutDate ,
						TempOutPunch_clk_InOrOutTime ,
						TempOutPunch_clk_InOrOutPunchType,
						TempInPunch_clk_InOrOutDeviceId,
						TempInPunch_clk_InOrOutDate,
						TempInPunch_clk_InOrOutTime,
						TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date
						FROM #TempOutPunchDetails1 order by OrderBy,TempOutPunch_clk_InOrOutTime 
					END
		END
	ELSE
		BEGIN
			IF(@MatchedPunchesTableCount=0 and @InPunchTableCount!=0)
				BEGIN
					IF(@clk_InOrOutPunchType='Break In' OR @clk_InOrOutPunchType='Official In')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails1 WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType='Break In'
							ORDER BY TempInPunch_clk_InOrOutTime
						END
				END
			IF(@MatchedPunchesTableCount!=0 AND @InPunchTableCount=0)
				BEGIN
					IF(@clk_InOrOutPunchType='Break Out' OR @clk_InOrOutPunchType='Official Out')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT 	TempOutPunch_clk_empid,
							TempOutPunch_clk_InOrOutDeviceId,
							TempOutPunch_clk_InOrOutDate ,
							TempOutPunch_clk_InOrOutTime ,
							TempOutPunch_clk_InOrOutPunchType,
							TempOutPunch_clk_date
							FROM #TempOutPunchDetails1
						END
				END
			IF(@MatchedPunchesTableCount=0 AND @InPunchTableCount=0)
				BEGIN
					IF(@clk_InOrOutPunchType='Break Out' OR @clk_InOrOutPunchType='Official Out')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)		
							SELECT 	TempOutPunch_clk_empid,
							TempOutPunch_clk_InOrOutDeviceId,
							TempOutPunch_clk_InOrOutDate ,
							TempOutPunch_clk_InOrOutTime ,
							TempOutPunch_clk_InOrOutPunchType,
							TempOutPunch_clk_date
							FROM #TempOutPunchDetails1
						END
					IF(@clk_InOrOutPunchType='Break In' OR @clk_InOrOutPunchType='Official In')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+' '+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails1 WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType='Break In'
							ORDER BY TempInPunch_clk_InOrOutTime
						END
				END
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <16/07/2019>
-- Description:	<The attendance will be marked as Absent, When employees is Absent on saturday and monday, then sunday will be marked as Absent, instead of Weekoff or Holiday as per shift setting>
-- [Proc_TA_MarkAbsentForWeekoffHoliday] '2020/08/11 00:00:00:000', '5',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]
	-- Add the parameters for the stored procedure here
	@Date datetime, @EmployeeCodeId varchar(40),@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--Vaiable declaration
	DECLARE @EnableAbsent int
	Declare @IsHoliday int
	Declare @IsWeekOff int
	Declare @PrevDay Datetime
	Declare @NextDay Datetime
	set @IsHoliday = 0;
	set @IsWeekOff =0;
	--This Value is updated using organization setting screen , very First condition to proceed
	SELECT @EnableAbsent = convert(int,EnableAbsent) from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
	IF(isnull(@EnableAbsent,0) = 1)  -- Option Enabled For the company or not
	BEGIN
		if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=@Date and (FNAttendanceCode='Absent'))
		begin
			if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and ((FNAttendanceCode='Weekly off' and ANAttendanceCode='Weekly off') or (ANAttendanceCode='Holiday')))
			begin
				if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-2,@Date) and (ANAttendanceCode='Absent'))
				begin
					update TA_Tbl_ProcessedData set FNAttendanceCode='Absent',ANAttendanceCode='Absent',Attendance='Absent' where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date)
				end				
			end	
		end
		else
		begin
			if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and Shift_Id=-1 and FNAttendanceCode='Absent' and FNAttendanceCode='Absent')
			begin
				update TA_Tbl_ProcessedData set FNAttendanceCode='Weekly Off',ANAttendanceCode='Weekly off',Attendance='Weekly off' where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and Shift_Id=-1 and FNAttendanceCode='Absent' and FNAttendanceCode='Absent'
			end
			else
			begin
				declare @EmpAUTOID int
				select @EmpAUTOID= Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeId and Isdeleted=0;
				Declare @prevDate datetime
				set @prevDate=dateadd(d,-1,@Date)
				
				declare @EventId int
				CREATE TABLE #EventId (EventId int, Descr varchar(500) )
				insert into #EventId execute [Proc_TA_CheckHolidayForService] @HOLIDAYTYPE ='G',@EMPLOYEEAUTOID = @EmpAUTOID,@FROMDATE = @PrevDate
				select @EventId = EventId from #EventId
				if(@EventId!=0)
				begin
					update TA_Tbl_ProcessedData set FNAttendanceCode='Holiday',ANAttendanceCode='Holiday',Attendance='Holiday' where Employee_Code_Id=@EmployeeCodeId and date=@PrevDate and FNAttendanceCode='Absent' and FNAttendanceCode='Absent'
				end
				drop table #EventId 
			end
		end
	END
	--SAPCO requirement. IF Its affect anything for any other client, comment the below whole codings.
	--Implemented by manikandan.rr on 18-Dec-2020 10:29 AM
	DECLARE @ShiftID BIGINT
	DECLARE @ShiftShortName varchar(10)
	DECLARE @FNAttendance VARCHAR(50)
	DECLARE @ANAttendance VARCHAR(50)
	SELECT @ShiftID=Shift_Id,@FNAttendance=FNAttendanceCode,@ANAttendance=ANAttendanceCode FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id=@EmployeeCodeId and date=@Date
	SELECT @ShiftShortName=Shift_ShortName FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	IF(@FNAttendance IN('PRESENT','ABSENT') or @ANAttendance IN('PRESENT','ABSENT'))
	BEGIN
		IF(@ShiftShortName='PLO' OR @ShiftShortName='PHO')
		BEGIN
			UPDATE TA_Tbl_ProcessedData SET 
			FNAttendanceCode=CASE WHEN @ShiftShortName='PLO' and @FNAttendance IN('PRESENT','ABSENT') THEN 'PLOff'
								  WHEN @ShiftShortName='PHO' and @FNAttendance IN('PRESENT','ABSENT') THEN 'PHOff'
								  else FNAttendanceCode
							 END,
			ANAttendanceCode=CASE WHEN @ShiftShortName='PLO' and @ANAttendance IN('PRESENT','ABSENT') THEN 'PLOff'
								  WHEN @ShiftShortName='PHO' and @ANAttendance IN('PRESENT','ABSENT') THEN 'PHOff'
								  else ANAttendanceCode
							 END
			WHERE Employee_Code_Id=@EmployeeCodeId and date=@Date
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MaxHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_MaxHoliday]
AS
BEGIN
 	 SELECT *  FROM TA_Tbl_HolidaySettings
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NewPredectionChartForAbsent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CReate PROCEDURE [dbo].[Proc_TA_NewPredectionChartForAbsent]


	@FromDate Nvarchar(50)='2023',@Tag nvarchar(50)='',@EmployeeID int='34'

AS
BEGIN
	
	if(@FromDate ='')
	begin 

	Select @FromDate=StartYear from TA_Tbl_YearSetting where IsActive =1

	end
	Declare @InYear varchar(4) = DATEPART(YEAR, @FromDate) 
	Declare @FromD Nvarchar(50) 
	Declare @ToD Nvarchar(50)
	set @FromD= @InYear+'-'+'1'+'-'+'1'
	Set @ToD = @InYear+'-'+'12'+'-'+'31'
	Print @FromD
	print @ToD



CREATE TABLE #Calendar (CalendarDate DATE)

DECLARE @StartDate DATE = @FromD
DECLARE @EndDate DATE = @ToD

WHILE @StartDate <= @EndDate
BEGIN
    INSERT INTO #Calendar (CalendarDate) VALUES (@StartDate)
    SET @StartDate = DATEADD(DAY, 1, @StartDate)
END

-- Count leave applications by month
SELECT DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1) AS LeaveMonth,
       COUNT(la.Leave_ApplicationDate) AS LeaveCount into #TempMonth
FROM #Calendar c
LEFT JOIN TA_Tbl_LeaveApplication la ON c.CalendarDate = la.Leave_ApplicationDate
WHERE c.CalendarDate BETWEEN @FromD AND @ToD
GROUP BY DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1)
ORDER BY LeaveMonth
	

Declare @YearSetting Nvarchar(10)
if(@FromDate='')
begin

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where IsActive =1
end 
else
begin 

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where StartYear = @InYear

end


if(@Tag='Admin')
begin

declare @EmpCount int 
Select @EmpCount=convert(int,Count(*)) 
from TA_Tbl_Employee where InActive_Status = 0
print @EmpCount


SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    COUNT(*) AS LateInCount into #TempAbsent
FROM TA_Tbl_ProcessedData
--WHERE Attendance = 'Absent' and YearSettingId = @YearSetting
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
WHERE Attendance = 'Absent' and 
TA_Tbl_Employee.Employee_Id = case when @EmployeeID ='1' then TA_Tbl_Employee.Employee_Id else @EmployeeID end
and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

DECLARE @DaysWorkedPerMonth INT = 26

DECLARE @TotalPossibleWorkDays INT = @EmpCount * @DaysWorkedPerMonth

Select #TempMonth.LeaveMonth,
--isnull(#TempAbsent.LateInCount ,0)
ISNULL(ROUND(CONVERT(FLOAT, ISNULL(#TempAbsent.LateInCount, 0)) / NULLIF(@TotalPossibleWorkDays, 0) * 100, 1), 0.0)as LeaveDaysCount from #TempMonth
Left Join #TempAbsent on #TempAbsent.Month = #TempMonth.LeaveMonth

drop Table #TempAbsent 

end 
else
begin

SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    COUNT(*) AS LateInCount into #TempAbsents
FROM TA_Tbl_ProcessedData
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
WHERE Attendance = 'Absent' and TA_Tbl_Employee.Employee_Id = @EmployeeID and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

Select #TempMonth.LeaveMonth,isnull(#TempAbsents.LateInCount ,0)as LeaveDaysCount from #TempMonth
Left Join #TempAbsents on #TempAbsents.Month = #TempMonth.LeaveMonth

drop Table #TempAbsents

end 



DROP TABLE #Calendar;
drop Table #TempMonth



END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NewPredectionChartForEarlyEXit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_NewPredectionChartForEarlyEXit] 

		@FromDate Nvarchar(50)='2023',@Tag nvarchar(50)='Admin',@EmployeeID int='54'
AS
BEGIN
	
	if(@FromDate ='')
	begin 

	Select @FromDate=StartYear from TA_Tbl_YearSetting where IsActive =1

	end
	Declare @InYear varchar(4) = DATEPART(YEAR, @FromDate) 
	Declare @FromD Nvarchar(50) 
	Declare @ToD Nvarchar(50)
	set @FromD= @InYear+'-'+'1'+'-'+'1'
	Set @ToD = @InYear+'-'+'12'+'-'+'31'
	Print @FromD
	print @ToD



CREATE TABLE #Calendar (CalendarDate DATE)

DECLARE @StartDate DATE = @FromD
DECLARE @EndDate DATE = @ToD

WHILE @StartDate <= @EndDate
BEGIN
    INSERT INTO #Calendar (CalendarDate) VALUES (@StartDate)
    SET @StartDate = DATEADD(DAY, 1, @StartDate)
END

-- Count leave applications by month
SELECT DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1) AS LeaveMonth,
       COUNT(la.Leave_ApplicationDate) AS LeaveCount into #TempMonth
FROM #Calendar c
LEFT JOIN TA_Tbl_LeaveApplication la ON c.CalendarDate = la.Leave_ApplicationDate
WHERE c.CalendarDate BETWEEN @FromD AND @ToD
GROUP BY DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1)
ORDER BY LeaveMonth


Declare @YearSetting Nvarchar(10)
if(@FromDate='')
begin

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where IsActive =1

end 
else
begin 

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where StartYear = @InYear

end


if(@Tag = 'Admin')
begin

declare @EmpCount int 
Select @EmpCount=convert(int,Count(*)) 
from TA_Tbl_Employee where InActive_Status = 0
print @EmpCount

SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    COUNT(*) AS LateInCount into #TempEarlyExit
FROM TA_Tbl_ProcessedData
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
--WHERE EarlyOut != '00:00' and YearSettingId = @YearSetting
WHERE EarlyOut != '00:00' and 
TA_Tbl_Employee.Employee_Id = case when @EmployeeID ='1' then TA_Tbl_Employee.Employee_Id else @EmployeeID end
and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

DECLARE @DaysWorkedPerMonth INT = 26

DECLARE @TotalPossibleWorkDays INT = @EmpCount * @DaysWorkedPerMonth

Select #TempMonth.LeaveMonth,
ISNULL(ROUND(CONVERT(FLOAT, ISNULL(#TempEarlyExit.LateInCount, 0)) / NULLIF(@TotalPossibleWorkDays, 0) * 100, 1), 0.0)as LeaveDaysCount from #TempMonth
Left Join #TempEarlyExit on #TempEarlyExit.Month = #TempMonth.LeaveMonth

drop Table #TempEarlyExit

end
else
begin

SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    COUNT(*) AS LateInCount into #TempEarlyExits
FROM TA_Tbl_ProcessedData
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
WHERE EarlyOut != '00:00' and TA_Tbl_Employee.Employee_Id = @EmployeeID and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

Select #TempMonth.LeaveMonth,isnull(#TempEarlyExits.LateInCount ,0)as LeaveDaysCount from #TempMonth
Left Join #TempEarlyExits on #TempEarlyExits.Month = #TempMonth.LeaveMonth

drop Table #TempEarlyExits

end 


DROP TABLE #Calendar;
drop Table #TempMonth



END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NewPredectionChartForLateIn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_NewPredectionChartForLateIn]

		@FromDate Nvarchar(50)='2023',@Tag nvarchar(50)='',@EmployeeID int='34'
AS
BEGIN
	
	if(@FromDate ='')
	begin 

	Select @FromDate=StartYear from TA_Tbl_YearSetting where IsActive =1

	end
	Declare @InYear varchar(4) = DATEPART(YEAR, @FromDate) 
	Declare @FromD Nvarchar(50) 
	Declare @ToD Nvarchar(50)
	set @FromD= @InYear+'-'+'1'+'-'+'1'
	Set @ToD = @InYear+'-'+'12'+'-'+'31'
	Print @FromD
	print @ToD



CREATE TABLE #Calendar (CalendarDate DATE)

DECLARE @StartDate DATE = @FromD
DECLARE @EndDate DATE = @ToD

WHILE @StartDate <= @EndDate
BEGIN
    INSERT INTO #Calendar (CalendarDate) VALUES (@StartDate)
    SET @StartDate = DATEADD(DAY, 1, @StartDate)
END

-- Count leave applications by month
SELECT DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1) AS LeaveMonth,
       COUNT(la.Leave_ApplicationDate) AS LeaveCount into #TempMonth
FROM #Calendar c
LEFT JOIN TA_Tbl_LeaveApplication la ON c.CalendarDate = la.Leave_ApplicationDate
WHERE c.CalendarDate BETWEEN @FromD AND @ToD
GROUP BY DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1)
ORDER BY LeaveMonth


Declare @YearSetting Nvarchar(10)
if(@FromDate='')
begin

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where IsActive =1
end 
else
begin 

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where StartYear = @InYear

end

if(@Tag='Admin')
begin

declare @EmpCount int 
Select @EmpCount=convert(int,Count(*)) 
from TA_Tbl_Employee where InActive_Status = 0
print @EmpCount

	SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    Convert(int, COUNT(*)) AS LateInCount into #TempLateIn
FROM TA_Tbl_ProcessedData
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
WHERE LateIn != '00:00' and 
TA_Tbl_Employee.Employee_Id = case when @EmployeeID ='1' then TA_Tbl_Employee.Employee_Id else @EmployeeID end
and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

DECLARE @DaysWorkedPerMonth INT = 26

DECLARE @TotalPossibleWorkDays INT = @EmpCount * @DaysWorkedPerMonth

Select #TempMonth.LeaveMonth,
--isnull(#TempLateIn.LateInCount,0) 
ISNULL(ROUND(CONVERT(FLOAT, ISNULL(#TempLateIn.LateInCount, 0)) / NULLIF(@TotalPossibleWorkDays, 0) * 100, 1), 0.0) as LeaveDaysCount 
from #TempMonth
Left Join #TempLateIn on #TempLateIn.Month = #TempMonth.LeaveMonth



drop Table #TempLateIn

end 
else
begin 


	SELECT 
    DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS Month,
    COUNT(*) AS LateInCount 
	into #TempLateInE
FROM TA_Tbl_ProcessedData
inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ProcessedData.Employee_Code_Id
WHERE LateIn != '00:00' and TA_Tbl_Employee.Employee_Id = @EmployeeID and YearSettingId = @YearSetting
GROUP BY DATEFROMPARTS(YEAR(Date), MONTH(Date), 1)
ORDER BY Month;

Select #TempMonth.LeaveMonth,isnull(#TempLateInE.LateInCount ,0)as LeaveDaysCount from #TempMonth
Left Join #TempLateInE on #TempLateInE.Month = #TempMonth.LeaveMonth

Drop Table #TempLateInE

end



--Select * from TA_Tbl_ProcessedData



DROP TABLE #Calendar;
drop Table #TempMonth




END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NewPredectionChartForLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_NewPredectionChartForLeave]
	
	@FromDate Nvarchar(50)='11-Nov-2024',@Tag nvarchar(50)='Admin',@Employee_Id int='1'
AS
BEGIN
	
	if(@FromDate ='')
	begin 

	Select @FromDate=StartYear from TA_Tbl_YearSetting where IsActive =1

	end
	Declare @InYear varchar(4) = DATEPART(YEAR, @FromDate) 
	Declare @FromD Nvarchar(50) 
	Declare @ToD Nvarchar(50)
	set @FromD= @InYear+'-'+'1'+'-'+'1'
	Set @ToD = @InYear+'-'+'12'+'-'+'31'
	Print @FromD
	print @ToD

CREATE TABLE #Calendar (CalendarDate DATE)

DECLARE @StartDate DATE = @FromD
DECLARE @EndDate DATE = @ToD

WHILE @StartDate <= @EndDate
BEGIN
    INSERT INTO #Calendar (CalendarDate) VALUES (@StartDate)
    SET @StartDate = DATEADD(DAY, 1, @StartDate)
END

-- Count leave applications by month
SELECT DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1) AS LeaveMonth,
       COUNT(la.Leave_ApplicationDate) AS LeaveCount into #TempMonth
FROM #Calendar c
LEFT JOIN TA_Tbl_LeaveApplication la ON c.CalendarDate = la.Leave_ApplicationDate
WHERE c.CalendarDate BETWEEN @FromD AND @ToD
GROUP BY DATEFROMPARTS(YEAR(c.CalendarDate), MONTH(c.CalendarDate), 1)
ORDER BY LeaveMonth

Declare @YearSetting Nvarchar(10)
if(@FromDate='')
begin

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where IsActive =1
end 
else
begin 

Select @YearSetting=YearSettings_Id from TA_Tbl_YearSetting where StartYear = @InYear

end

Declare @EmployeeCount int 
Select  @EmployeeCount=Count(*) 
from TA_Tbl_Employee where InActive_Status = 0


--Select  TA_Tbl_Employee.Employee_Id as EMPID,Sum(TA_Tbl_LeavePolicyDetails.MaxDays_applicable )as TotalManDays into #TempLeave 
--from TA_Tbl_Employee 
--inner Join TA_Tbl_Emp_LeavePolicy on TA_Tbl_Emp_LeavePolicy.EmployeeId = TA_Tbl_Employee.Employee_Id 
--inner Join TA_Tbl_LeavePolicyDetails on TA_Tbl_LeavePolicyDetails.Policy_Id = TA_Tbl_Emp_LeavePolicy.LeavePolicy_Id
--inner join TA_Tbl_LeaveType on TA_Tbl_LeaveType.LeaveType_Id = TA_Tbl_LeavePolicyDetails.LeaveType_Id
--where TA_Tbl_Emp_LeavePolicy.YearSettingId=@YearSetting
--group by Employee_Id 


Select DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1)AS Leave_ApplicationMonth,
Sum(NumberOfDays)as LeaveDays into #TempLeaveCount
from TA_Tbl_LeaveApplication
WHERE Leave_ApplicationDate BETWEEN @FromD AND @ToD and Status ='Approved' and IsDeleted=0
    OR Leave_ApplicationDate IS NULL
    OR NumberOfDays = 0 
GROUP BY DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1)
ORDER BY Leave_ApplicationMonth;

--Select * from #TempLeaveCount

if(@Tag = 'Admin' and @Employee_Id ='1')
begin 

print @EmployeeCount
Select  DATEFROMPARTS(YEAR(Leave_ApplicationMonth), MONTH(Leave_ApplicationMonth), 1)AS Leave_ApplicationMonth,
Convert (int,LeaveDays/@EmployeeCount *100 ) as LeaveDays 
into #TempFinal from #TempLeaveCount 

--Where Employee_Id = case when @Employee_Id ='1' then Employee_Id  else @Employee_Id end 
--Select * from #TempLeaveCount

Select #TempMonth.LeaveMonth, isnull(#TempFinal.LeaveDays,0)as LeaveDaysCount  From #TempMonth
left Join #TempFinal on #TempFinal.Leave_ApplicationMonth = #TempMonth.LeaveMonth

Drop table #TempFinal


end 
else
begin 


Select DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1)AS Leave_ApplicationMonth,
TA_Tbl_LeaveApplication.Employee_Id,Sum(NumberOfDays)as LeaveDays  into #TempLeaveCounts
from TA_Tbl_LeaveApplication
WHERE Leave_ApplicationDate BETWEEN @FromD AND @ToD 
and TA_Tbl_LeaveApplication.Employee_Id = case when @Employee_Id ='1' then TA_Tbl_LeaveApplication.Employee_Id  else @Employee_Id end 
    OR Leave_ApplicationDate IS NULL
    OR NumberOfDays = 0 
GROUP BY DATEFROMPARTS(YEAR(Leave_ApplicationDate), MONTH(Leave_ApplicationDate), 1),TA_Tbl_LeaveApplication.Employee_Id
ORDER BY Leave_ApplicationMonth;



Select  DATEFROMPARTS(YEAR(Leave_ApplicationMonth), MONTH(Leave_ApplicationMonth), 1)AS Leave_ApplicationMonth,
#TempLeaveCounts.Employee_Id,Convert (int,LeaveDays/@EmployeeCount *100 )  as LeaveDays into #TempFinalEmployeeWise from #TempLeaveCounts
--inner Join #TempLeave on #TempLeave.EMPID = #TempLeaveCounts.Employee_Id
Where #TempLeaveCounts.Employee_Id = case when @Employee_Id ='1' then #TempLeaveCounts.Employee_Id  else @Employee_Id end 

Select #TempMonth.LeaveMonth, isnull(#TempFinalEmployeeWise.LeaveDays,0) as LeaveDaysCount From #TempMonth
left Join #TempFinalEmployeeWise on #TempFinalEmployeeWise.Leave_ApplicationMonth = #TempMonth.LeaveMonth




--Select  DATEFROMPARTS(YEAR(Leave_ApplicationMonth), MONTH(Leave_ApplicationMonth), 1)AS Leave_ApplicationMonth,
--#TempLeaveCounts.Employee_Id,LeaveDays  as LeaveDays into #TempFinalEmployeeWise from #TempLeaveCount
--inner Join #TempLeave on #TempLeave.EMPID = #TempLeaveCounts.Employee_Id
--Where #TempLeaveCounts.Employee_Id = case when @Employee_Id ='1' then Employee_Id  else @Employee_Id end 

----Select * from #TempFinalEmployeeWise

--Select #TempMonth.LeaveMonth, isnull(#TempFinalEmployeeWise.LeaveDays,0) as LeaveDaysCount From #TempMonth
--left Join #TempFinalEmployeeWise on #TempFinalEmployeeWise.Leave_ApplicationMonth = #TempMonth.LeaveMonth


drop table #TempFinalEmployeeWise

end 


--Drop table #TempLeave
DROP TABLE #Calendar;
drop table #TempMonth
--drop table #TempCountMonth


END

GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NonProcessedDataDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 09-07-2014
-- Description:	To show the unprocessed data record details
-- ==========================================================================================
--ALTER PROCEDURE [dbo].[Proc_Ta_NonProcessedDataDetails]
--	-- Add the parameters for the stored procedure here	
--AS
--BEGIN
--	-- SET NOCOUNT ON added to prevent extra result sets from
--	-- interfering with SELECT statements.
--	SET NOCOUNT ON;
--    -- Insert statements for procedure here
--    --Employee Details
--	SELECT CLK_CARDID ,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData C
--	--inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=1
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	--and E.Isdeleted=0 and (E.InActiveDate is null or E.InActiveDate<=CLK_DATE)
--	group by CLK_CARDID order by CLK_CARDID 
--	--Terminal Details
--	SELECT CLK_DEVICEID,TotalRecords=count(convert(int,CLK_DEVICEID)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=2
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_DEVICEID order by CLK_DEVICEID
--	--Shift not allocated Employee details
--	SELECT CLK_CARDID,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=3
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_CARDID order by CLK_CARDID 	
--	--Punch types not created device details
--	SELECT CLK_DEVICEID,CLK_TYPE,TotalRecords=count(convert(int,CLK_TYPE)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=4
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_DEVICEID,CLK_TYPE order by CLK_DEVICEID ,CLK_TYPE
--END
CREATE PROCEDURE [dbo].[Proc_Ta_NonProcessedDataDetails]
	-- Add the parameters for the stored procedure here	
	@FROMDATE datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @FromdateString varchar(20)
	if @FROMDATE!=''
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+'-'+CONVERT(varchar(20),DATEPART(month,@fromdate))+'-'+
			case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then '0'+CONVERT(varchar(20),DATEPART(D,@fromdate))
			else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
		Declare @Query1 nvarchar(4000)
		Declare @Query2 nvarchar(4000)
		Declare @Query3 nvarchar(4000)
		Declare @Query4 nvarchar(4000)
    -- Insert statements for procedure here
    --Employee Details
	set @Query1 = ' SELECT CLK_CARDID ,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData C
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=1
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) '
	if(@fromdate!='')
		begin
		set @Query1 =@Query1 +	' and CLK_DATE <=  CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) '
		end
	set @Query1 =@Query1 + ' group by CLK_CARDID order by CLK_CARDID '
	execute (@Query1)
	--Terminal Details
	 set @Query2 = ' SELECT CLK_DEVICEID,TotalRecords=count(convert(int,CLK_DEVICEID)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=2
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) '
	if(@fromdate!='')
		begin
		set @Query2 =@Query2 +	' and CLK_DATE <=  CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) '
		end
	set @Query2 =@Query2 + ' group by CLK_DEVICEID order by CLK_DEVICEID '
	execute (@Query2)
	--Shift not allocated Employee details
	set @Query3 = ' SELECT CLK_CARDID,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=3
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) '
	if(@fromdate!='')
		begin
		set @Query3 =@Query3 +	' and CLK_DATE <=  CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) '
		end
	set @Query3 =@Query3 + ' group by CLK_CARDID order by CLK_CARDID '
	execute (@Query3)
	--Punch types not created device details
	set @Query4 = ' SELECT CLK_DEVICEID,CLK_TYPE,TotalRecords=count(convert(int,CLK_TYPE)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=4
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) '
	if(@fromdate!='')
		begin
		set @Query4 =@Query4 +	' and CLK_DATE <=  CONVERT(DATETIME,'''+cast(@FROMDATE as nvarchar(50))+''', 102) '
		end
	set @Query4 =@Query4 + ' group by CLK_DEVICEID,CLK_TYPE order by CLK_DEVICEID ,CLK_TYPE '
	execute (@Query4)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NotProcessedDataDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_NotProcessedDataDetails]
	-- Add the parameters for the stored procedure here
	@ManualTimeEntry_Id int,
	@ManualTimeEntry_Employee_Id int,
	@ManualTimeEntry_InReaderID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Insert into Ta_tbl_NotProcessedDataDetails values(@ManualTimeEntry_Id,@ManualTimeEntry_Employee_Id,@ManualTimeEntry_InReaderID,'Punch Types is not defined','M')
    -- Insert statements for procedure here
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofGolbalHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_NumberofGolbalHolidays]
AS
BEGIN
	select count(*) as G from TA_Tbl_Holiday where Holiday_Type='G' and Isdeleted=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofYearlyHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_NumberofYearlyHolidays]
AS
BEGIN
	select count(*) as Y from TA_Tbl_Holiday where Holiday_Type='Y' and Isdeleted=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OndutyApplicationApproved]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan
-- Create date: 14-Mar-2016
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OndutyApplicationApproved]
	@ODID int,
	@Status nvarchar(50),
	@Remarks nvarchar(Max),
	@Emp_ID int
AS
BEGIN
	SET NOCOUNT ON;
		declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@Emp_ID)


	update Ta_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@Emp_ID as nvarchar(20)),TimeStamp =@GetUTCTime  where OnDuty_ID=@ODID
	update TA_Tbl_OndutyEntry set Onduty_Status=@Status,Emp_Id=@Emp_ID where Onduty_ID=@ODID
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OracleAutomaticSync]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_OracleAutomaticSync '05/04/2022 02:40 PM'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OracleAutomaticSync]
@SyncDate date
AS
BEGIN
	SET NOCOUNT ON;
	IF(@SYNCDATE=CONVERT(VARCHAR(11),GETDATE()))
	BEGIN
		IF NOT EXISTS(SELECT SyncDate from ta_tbl_oracleSync where SyncDate=@SyncDate)
		BEGIN
			SELECT HostName, Port, ServiceName, UserName, Pwd FROM dbo.Ta_tbl_OracleDBConfiguration
		END
		ELSE
		BEGIN
			SELECT HostName, Port, ServiceName, UserName, Pwd FROM dbo.Ta_tbl_OracleDBConfiguration where hostname='1'
		END
	END
	ELSE
	BEGIN
		SELECT HostName, Port, ServiceName, UserName, Pwd FROM dbo.Ta_tbl_OracleDBConfiguration where hostname=1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEdit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OrgEdit]
(
	@lid int
)
AS
BEGIN
	DECLARE @lelid int, @lelName varchar(50)
	declare @pid as int
	SELECT @lelName = name, @pid=ParentID FROM ta_tbl_levelDetails WHERE id = @lid
	INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName,pid ) VALUES (@lid,@lelName,@pid)
	SELECT @lelid=parentID FROM ta_tbl_levelDetails WHERE id = @lid
	if (@lelid >0)
	BEGIN
		EXEC dbo.Proc_TA_OrgEdit @lelid
	END		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEditUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_OrgEditUpdated]  1, '1,2,3'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OrgEditUpdated]
(
		@lid int,
		@LevelIDs nvarchar(1000)
)
AS
BEGIN
	declare @Query as varchar(7000)
	set @Query = 'DECLARE @lelid int, @lelName varchar(30)'
	set @Query =  @Query + ' SET @lelName = (SELECT name FROM ta_tbl_levelDetails WHERE id =' + cast(@lid as nvarchar(20))  + ' and  id in (' + @LevelIDs + '))'
	set @Query =  @Query + ' INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES (' + cast(@lid as nvarchar(20)) + ',@lelName)'
	set @Query =  @Query + ' SET @lelid = (SELECT parentID FROM ta_tbl_levelDetails WHERE id = ' + cast(@lid as nvarchar(20)) + ')'
	set @Query =  @Query + ' if (@lelid >0)'
	set @Query =  @Query + ' BEGIN'
	set @Query =  @Query + ' EXEC dbo.Proc_TA_OrgEdit @lelid ,' + @LevelIDs
	set @Query =  @Query + ' END'
exec (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OverallPreferrenceLoad]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OverallPreferrenceLoad]

@EmployeeCode NVARCHAR(50) ='6'
AS
BEGIN

	Select TA_Tbl_EmployeeLevel.LevelId,Ta_Tbl_levelDetails.TimezoneId,TimeZoneName,TimeZoneDesc,HoursToBeAdded,MinToBeAdded from TA_Tbl_EmployeeLevel
	Inner Join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id =TA_Tbl_EmployeeLevel.LevelId
	Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
	Inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id =  TA_Tbl_EmployeeLevel.EmployeeId
	Where TA_Tbl_Employee.Employee_Id =@EmployeeCode
	
	--Select * from TA_Tbl_UTCTimeZonesCountryDetails
	
	--Where 	EmployeeCode = @EmployeeCode
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OverTimeRoundOff]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OverTimeRoundOff]
	-- Add the parameters for the stored procedure here
	@inShiftSettingId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT StartMins,EndMins,RoundedAs FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId =  @inShiftSettingId 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ParentIDs]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- Create date: 16 July 2007
-- Modified by : R.Manikandan
-- Modified on : 19-Apr-2019 11:51 AM
-- Description:	Get Parent Level IDs
-- We got some wrong data binding in iffco. They are created the level details tables as per their requirement.
-- i.e they were created the parent id after the child data creation. Due to this level dropdowns are not loaded
-- properly in employee master modify page. Due to this, we bring row_number.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ParentIDs]
AS	
BEGIN
	SET NOCOUNT ON;
	select LevelID,LevelName,pid from
	(
		SELECT *,ROW_NUMBER()over(order by (select 100))as slno FROM TA_Tbl_ParentIDs 
	)as a order by slno desc
	DELETE FROM TA_Tbl_ParentIDs
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Payroll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_Payroll] 'convert(varchar(100),ppd.Employee_Id) as Employee_Id,convert(varchar(100),ppd.EarlyOut) as EarlyOut,convert(varchar(100),ppd.LateIn) as LateIn,convert(varchar(100),ppd.HrsLess) as HrsLess,convert(varchar(100),ppd.HrsExtra) as HrsExtra,convert(varchar(100),ppd.LeaveDays) as LeaveDays,convert(varchar(100),ppd.AbsentDays) as AbsentDays,convert(varchar(100),ppd.PresentDays) as PresentDays,convert(varchar(100),ppd.Holidays) as Holidays,convert(varchar(100),ppd.LOPDays) as LOPDays,convert(varchar(100),ppd.TotalPermissionHours) as TotalPermissionHours,convert(varchar(100),ppd.WeekOffDays) as WeekOffDays,convert(varchar(100),ppd.HrsWork) as Hours_Worked,convert(varchar(100),ppd.HrsOt) as Total_OT,convert(varchar(100),ppd.NormOt) as WeekDay_OT,convert(varchar(100),ppd.OffOT) as WeekOff_OT,convert(varchar(100),ppd.HolOT) as Holiday_OT,convert(varchar(100),ppd.WorkHrs) as Defined_WorkHours,convert(varchar(250),LD.description) as LevelCode' , 'January','2019','1','1','1',2,'SuperAdmin',1,'SummarizedData'  
--[Proc_TA_Payroll] '   Date, InTime, OutTime, EarlyOut, LateIn, HrsLess, HrsExtra, FNAttendanceCode, ANAttendanceCode, Hours_Worked, Total_OT, WeekDay_OT, WeekOff_OT, Holiday_OT, Defined_WorkHours, Employee_Id, EmployeeName, CardNo, ShiftCode, ShiftName, DateIn, DateOut, InReaderId, OutReaderId, InReaderName, OutReaderName, Remarks, LevelCode, LevelName, OverTimeType' , 'March','2011','323','323','3',45,'SuperAdmin',323,'DailyData'  
CREATE   PROCEDURE [dbo].[Proc_TA_Payroll]  
(  
   @SelectedFieldNames NVARCHAR(4000),  
   @Month VARCHAR(20),  
   @Year INT,  
   @CompanyID as int,    
   @Level as varchar(1000),  
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int,
   @DataType varchar(50) 
)  
AS  
Begin 
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	create table #LevelRights_Company(LevelId int)
	insert into  #LevelRights_Company select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@CompanyID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	DECLARE @Query AS VARCHAR(8000)  
	declare @ToDate as nvarchar(15)  
	if (@mon=12)  
	Begin  
		set @ToDate =  '01/' + '01/' + cast(@Year+1 as nvarchar(20))  
	End  
	Else  
	Begin  
		set @ToDate = cast(@mon+1 as nvarchar(20)) + '/' + '01/' + cast(@Year as nvarchar(20))  
	End  
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	 
	if(@DataType = 'SummarizedData')
		BEGIN
			 SET @Query = 'SELECT ' +  @SelectedFieldNames 
			 SET @Query = @Query + ' FROM  TA_Tbl_PayrollProcessDetails ppd'  
			 SET @Query = @Query + ' inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id '  
			 SET @Query = @Query + ' inner join ta_tbl_employee e on e.swipecardno = ppd.Employee_Id '  
			 SET @Query = @Query + ' inner join ta_tbl_employeelevel on e.employee_id=ta_tbl_employeelevel.employeeid '  
			 SET @Query = @Query + ' inner join TA_Tbl_LevelDetails LD on ta_tbl_employeelevel.levelId=LD.Id '  
			 set @Query = @Query + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
			 set @Query = @Query + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid '
			 set @Query = @Query + ' Inner join #LevelRights_Company on #LevelRights_Company.LevelId=#EmpLevel.levelid '
			 SET @Query = @Query + ' WHERE  mc.MonthClosure_Month = ''' + @Month  + ''' AND  '  
			 SET @Query = @Query + ' mc.MonthClosure_Year = ' + CAST(@Year AS NVARCHAR) +'  and  '  
			 SET @Query = @Query + ' mc.MonthClosure_Id = ' + CAST(@intMonthClosureId AS NVARCHAR(25)) +' '
			 Print(@Query)  
			 exec(@Query)  
		 END
	 ELSE
	 BEGIN
	    create table #TempExportData 
		(
			Date  nvarchar(50),
			DateIn nvarchar(20),
			DateOut nvarchar(20),
			InTime  nvarchar(20),
			OutTime  nvarchar(20),			
			Hours_Worked  nvarchar(20),
			Total_OT  nvarchar(20),
			WeekDay_OT  nvarchar(20),
			WeekOff_OT  nvarchar(20),
			Holiday_OT  nvarchar(20),
			EarlyOut  nvarchar(20),
			LateIn  nvarchar(20),
			Defined_WorkHours  nvarchar(20),
			HrsLess  nvarchar(20),
			HrsExtra  nvarchar(20),
			FNAttendanceCode  nvarchar(20),
			ANAttendanceCode  nvarchar(20),
			Employee_ID  nvarchar(20),
			EmployeeName nvarchar(250),
			CardNo  nvarchar(20),
			ShiftCode  nvarchar(250),
			ShiftName  nvarchar(250),
			InReaderId  nvarchar(20),
			OutReaderId  nvarchar(20),
			InReaderName  nvarchar(20),
			OutReaderName  nvarchar(20),
			LevelCode  nvarchar(250),
			LevelName nvarchar(250),
			OverTimeType  nvarchar(50),
			--AttendanceCode  varchar(50),
			Remarks  nvarchar(20)
		)
		/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempExportData] 
		(
			[Date] ASC
		) ON [PRIMARY]		
		CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]
		CREATE TABLE #TempClockDetails
		(
			[Clk_Id] int,
			[Clk_CompId] varchar(10),
			[Clk_EmpId] nvarchar(20),
			[Clk_InDeviceId] nvarchar(20),
			[Clk_InDate] datetime,
			[Clk_InTime] datetime,
			[Clk_InPunchType] nvarchar(25),
			[Clk_OutDeviceId] nvarchar(20),
			[Clk_OutDate] datetime,
			[Clk_OutTime] datetime,
			[Clk_OutPunchType] nvarchar(25),
			[Clk_Process] nvarchar(1),
			[Clk_Remarks] nvarchar(100),
			[Clk_User] nvarchar(20),
			[Clk_Date] datetime,
			[Clk_Status] char(1),
			[IsVoid] bit
	     )
	      /****** Object:  Index [IDX_Clk_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Clk_Date] ON [dbo].[#TempClockDetails] 
		(
			[Clk_Date] ASC
		) ON [PRIMARY]
		  /****** Object:  Index [IDX_Clk_EmpId]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Clk_EmpId] ON [dbo].[#TempClockDetails] 
		(
			[Clk_EmpId] ASC
		) ON [PRIMARY]
		insert into #TempProcessedData 
		select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
		[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
		[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
		inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
		where PD.Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
		--select * from #TempProcessedData
		insert into #TempClockDetails
		select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],
		[Clk_OutDate],[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
		from TA_Tbl_ClockDetails CD 
		inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
		where CD.Clk_Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
		
        insert into #TempExportData(Date,InTime,OutTime,Hours_Worked,Total_OT,WeekDay_OT,WeekOff_OT,Holiday_OT,EarlyOut,LateIn,Defined_WorkHours,HrsLess,HrsExtra,FNAttendanceCode,ANAttendanceCode,Employee_Id,EmployeeName,CardNo,ShiftCode,ShiftName,LevelCode,LevelName,OverTimeType,Remarks,InReaderId,OutReaderId,InReaderName,OutReaderName,DateIn,DateOut)  
        select isnull(PD.Date,''),
                isnull(PD.InTime,''),
				isnull(PD.OutTime,''),
				isnull(PD.HrsWork,''),
				isnull(PD.HrsOT,'00:00'),
				isnull(PD.NormOT,'00:00'),
				isnull(PD.OffOT,'00:00'),
				isnull(PD.HolOT,'00:00'),
				isnull(PD.EarlyOut,''),
				isnull(PD.LateIn,''),
				isnull(PD.WorkHrs,''),
				isnull(PD.HrsLess,''),
				isnull(PD.HrsExtra,''),
				isnull(PD.FNAttendanceCode,''),
				isnull(PD.ANAttendanceCode,''),
				isnull(E.Employee_Code_ID,''),
				isnull(isnull(E.Employee_FirstName,'') + ' ' + isnull(E.Employee_LastName,''),''),
				isnull(E.SwipeCardNo,''),
				isnull(Sht.Shift_Description,''),
				isnull(Sht.Shift_Name,case Pd.Shift_Id when '-1' then 'Weekly Off' else '' end),
				isnull(LD.description,''),
				isnull(LD.name,''),
				--isnull(OT.OTType,''),
				--isnull(AC.AttandanceCode,''),
				'','','','','','','','' 
				from #TempProcessedData PD 
				inner join TA_Tbl_Employee E on E.SwipeCardNo = PD.Employee_Code_Id 
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeID=E.Employee_ID 
				inner join TA_Tbl_LevelDetails LD on EL.LevelId=LD.Id 
				Inner join #EmpLevel on #EmpLevel.EffectiveDate=EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
				Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid
				Inner join #LevelRights_Company on #LevelRights_Company.LevelId=#EmpLevel.levelid 
				left join TA_Tbl_Shift Sht on PD.Shift_Id=Sht.Shift_Id 
				inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
				--left join TA_Tbl_OtType OT on 1=1 
				--left join TA_Tbl_AttandanceCode AC on 1=1 
				--where PD.Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
				where MC.IsDeleted=0 order by PD.Employee_Code_Id,PD.Date
				--and AC.AttandanceValue='Absent' 
				--and AC.isdeleted=0 
				--and AC.CompanyID=1 
				--and OT.Isdeleted=0 and OT.OtValue='WorkingDay' and OT.CompanyID=@CompanyID
				--select * from #TempExportData
				--updates the FNAttendanceCode in the #TempExportData
				update #TempExportData set FNAttendanceCode=TA_Tbl_AttandanceCode.AttandanceCode from TA_Tbl_AttandanceCode
				inner join #TempExportData on TA_Tbl_AttandanceCode.AttandanceValue=#TempExportData.FNAttendanceCode
				and TA_Tbl_AttandanceCode.CompanyID=@CompanyID and TA_Tbl_AttandanceCode.isdeleted=0
				--select * from #TempExportData
				--updates the ANAttendanceCode in the #TempExportData
				update #TempExportData set ANAttendanceCode=TA_Tbl_AttandanceCode.AttandanceCode from TA_Tbl_AttandanceCode
				inner join #TempExportData on TA_Tbl_AttandanceCode.AttandanceValue=#TempExportData.ANAttendanceCode
				and TA_Tbl_AttandanceCode.CompanyID=@CompanyID and TA_Tbl_AttandanceCode.isdeleted=0
				--select * from #TempExportData
				--updates the OverTimeType in the #TempExportData
				update #TempExportData set OverTimeType =
				case when #TempExportData.WeekDay_OT<>'00:00'
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)='WorkingDay' and isdeleted=0 and CompanyId=@CompanyID)
				when #TempExportData.WeekOff_OT<>'00:00'
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)='WeeklyOff' and isdeleted=0 and CompanyId=@CompanyID)
				when #TempExportData.Holiday_OT<>'00:00'
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)='Holiday' and isdeleted=0 and CompanyId=@CompanyID)
				else
				''
				end
				--updates the Total Ot Hours in the #TempExportData
				update #TempExportData set Total_OT = case	when #TempExportData.WeekDay_OT<>'00:00' then (WeekDay_OT)
															when #TempExportData.WeekOff_OT<>'00:00' then (WeekOff_OT)
															when #TempExportData.Holiday_OT<>'00:00' then (Holiday_OT)
															else '00:00'
													  end
				--updates the terminal id for in punch in temp table
				update #TempExportData set InReaderId=isnull(Clk_InDeviceId,'') from #TempClockDetails 
				inner join #TempExportData on Clk_EmpId=CardNo and Clk_Date=[Date] and IsVoid=0 and #TempExportData.InTime<>'' 
				and Clk_InTime=convert(datetime,#TempExportData.InTime)
				--updates the terminal id for out punch in temp table
				
				update #TempExportData set OutReaderId=isnull(Clk_OutDeviceId,'')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.OutTime<>'' 
				and Clk_OutTime=convert(datetime,#TempExportData.OutTime)
				
				--updates the DateIn in the temp table
				update #TempExportData set DateIn=isnull(Clk_InDate,'')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.InTime<>'' and Clk_InTime=#TempExportData.InTime
				--select * from #TempExportData
				--updates the DateOut in the temp table
				update #TempExportData set DateOut=isnull(Clk_OutDate,'')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.OutTime<>'' and Clk_OutTime=#TempExportData.OutTime
				--select * from #TempExportData
				--updates the terminal name for OUT reader id in temp table
				update #TempExportData set InReaderName=isnull(TA_Tbl_Terminal.Terminal_Name,'')
				from TA_Tbl_Terminal inner join #TempExportData on TA_Tbl_Terminal.Terminal_ReaderId=#TempExportData.InReaderId
				--select * from #TempExportData
				---updates the terminal name for OUT reader id in temp table
				update #TempExportData set OutReaderName=isnull(TA_Tbl_Terminal.Terminal_Name,'')
				from TA_Tbl_Terminal inner join #TempExportData on TA_Tbl_Terminal.Terminal_ReaderId=#TempExportData.OutReaderId
				--select * from #TempExportData
	    SET @Query = 'select ' + @SelectedFieldNames
		SET @Query = @Query + ' from #TempExportData '
		exec (@Query)
		drop table #TempExportData
		drop table #TempProcessedData
		drop table #TempClockDetails
	 END
	--Remove the temporary tables here
	drop table #EmpLevel
	drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByAttandance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_PayrollByAttandance 'ppd.Employee_Id,ppd.AbsentDays' , 'March','2009','40','40,182,187,185,183,204,202,206,200,191,195,218,220,222,197,189,228,214,193,216,224,226,184,199,186,188,190,192,194,196,198,201,203,205,207,215,217,219,221,223,225,227,229','03'
CREATE   PROCEDURE [dbo].[Proc_TA_PayrollByAttandance] 
(
   @SelectedFieldNames NVARCHAR(2000),
   @Month VARCHAR(20),  
   @Year INT,
   @CompanyID as int,  
   @Level as varchar(8000),
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int 
)
AS
Begin
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
declare @ToDate as nvarchar(15)
--set @FromDate = cast(@SelectedMonth as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
if (@mon=12)
	Begin
		set @ToDate =  '01/' + '01/' + cast(@Year+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@mon+1 as nvarchar(20)) + '/' + '01/' + cast(@Year as nvarchar(20))
	End
	DECLARE @Query AS VARCHAR(8000)
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
--SET @Query =  'SELECT  ' +  @SelectedFieldNames + ',TA_Tbl_AttandanceCode.AttandanceCode'
--ppd.Employee_Id
SET @Query =  'SELECT  ta_tbl_employee.employee_code_id as employee_code,'
SET @Query = @Query +  cast (@Mon as varchar(3)) + ' as pay_month ,' + cast(@year as varchar(4)) + ' as pay_year,'
SET @Query = @Query + ' TA_Tbl_AttandanceCode.AttandanceCode as attn_code, ppd.AbsentDays as no_of_days'
SET @Query = @Query + ' ,''auto upload'' as remarks  FROM TA_Tbl_PayrollProcessDetails ppd inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id'
SET @Query = @Query + ' left join TA_Tbl_AttandanceCode on 1=1'  
SET @Query = @Query + ' inner join ta_tbl_employee on ta_tbl_employee.swipecardno = ppd.Employee_Id'
SET @Query = @Query + ' inner join ta_tbl_employeelevel on ta_tbl_employee.employee_id=ta_tbl_employeelevel.employeeid'
set @Query = @Query + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
set @Query = @Query + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid '
SET @Query = @Query + ' WHERE '
SET @Query = @Query + ' mc.MonthClosure_Month =''' + @Month  + ''' AND '
SET @Query = @Query + ' mc.MonthClosure_Year = ' + CAST(@Year AS NVARCHAR) +'  and '
SET @Query = @Query + ' mc.MonthClosure_Id = ' + CAST(@intMonthClosureId AS NVARCHAR(25)) +' and '
SET @Query = @Query + ' TA_Tbl_AttandanceCode.AttandanceValue=''Absent'' and '
SET @Query = @Query + ' TA_Tbl_AttandanceCode.CompanyID=' + CAST(@CompanyID AS NVARCHAR) + ' and '
SET @Query = @Query + ' TA_Tbl_AttandanceCode.isdeleted=0 and  ppd.AbsentDays<>0.0 '
--SET @Query = @Query + ' TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''+ @ToDate + ''', 102) order by EffectiveDate desc)'
--SET @Query = @Query + ' #EmpLevel.levelid in (' + @Level + ')'
	EXEC(@Query)
  --Remove the temporary tables here
drop table #EmpLevel
drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByOverTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_PayrollByOverTime 'ppd.Employee_Id,ppd.HrsOT' , 'March','2009','40','40,182,187,185,183,204,202,206,200,191,195,218,220,222,197,189,228,214,193,216,224,226,184,199,186,188,190,192,194,196,198,201,203,205,207,215,217,219,221,223,225,227,229','03'
--Proc_TA_PayrollByOverTime '' , 'April','2009','1','1,2,3','03',5,'SuperAdmin',0
CREATE   PROCEDURE [dbo].[Proc_TA_PayrollByOverTime] 
(
   @SelectedFieldNames NVARCHAR(2000),
   @Month VARCHAR(20),  
   @Year INT,
   @CompanyID as int,  
   @Level as varchar(8000),
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int	
)
AS
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
declare @ToDate as nvarchar(15)
if (@mon=12)
	Begin
		set @ToDate =  '01/' + '01/' + cast(@Year+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@mon+1 as nvarchar(20)) + '/' + '01/' + cast(@Year as nvarchar(20))
	End
  set @SelectedFieldNames = replace(@SelectedFieldNames,'ppd.HrsOT','round (cast(replace(ppd.NormOT,'':'',''.'') as decimal) +   (round(cast(replace(ppd.NormOT,'':'',''.'') as float)- cast(replace(ppd.NormOT,'':'',''.'') as decimal),2)*100)/60,2) as HrsOT')
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
Begin
	DECLARE @Query AS VARCHAR(8000)
--SET @Query = 'SELECT  ' + cast (@Mon as varchar(3)) + ',' + cast(@year as varchar(4)) +',' +  @SelectedFieldNames 
--SET @Query = @Query + ' ,TA_Tbl_OtType.OTType'
--ppd.Employee_Id
--select * from TA_Tbl_OtType
SET @Query = 'SELECT  ta_tbl_employee.employee_code_id as employee_code, '
SET @Query = @Query +  cast (@Mon as varchar(3)) + ' as pay_month ,' + cast(@year as varchar(4)) + ' as pay_year,'
SET @Query = @Query + ' TA_Tbl_OtType.OTType as ot_type,'
--round (cast(replace(ppd.NormOT,'':'',''.'') as decimal) +   (round(cast(replace(ppd.NormOT,'':'',''.'') as float)- cast(replace(ppd.NormOT,'':'',''.'') as decimal),2)*100)/60,2) as ot_hours'
SET @Query = @Query + ' ''overtime ' + substring(@Month,1,3) + ''' as remarks, '
SET @Query = @Query + ' ppd.NormOT,ppd.OffOT,ppd.HolOT'
SET @Query = @Query + ' FROM TA_Tbl_PayrollProcessDetails ppd'
SET @Query = @Query + ' inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id'
SET @Query = @Query + ' left join TA_Tbl_OtType on 1=1  '
SET @Query = @Query + ' inner join ta_tbl_employee on ta_tbl_employee.swipecardno = ppd.Employee_Id'
SET @Query = @Query + ' inner join ta_tbl_employeelevel on ta_tbl_employee.employee_id=ta_tbl_employeelevel.employeeid'
set @Query = @Query + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
set @Query = @Query + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid '
SET @Query = @Query + ' WHERE mc.MonthClosure_Month = ''' + @Month  + ''' AND '
SET @Query = @Query + ' mc.MonthClosure_Year = ' + CAST(@Year AS NVARCHAR) +' and '
SET @Query = @Query + ' mc.MonthClosure_Id = ' + CAST(@intMonthClosureId AS NVARCHAR(25)) +' and '
SET @Query = @Query + ' TA_Tbl_OtType.OtValue = case when ppd.NormOT<>''00:00'' then ''WorkingDay'' when ppd.OffOT<>''00:00'' then ''WeeklyOff'' when ppd.HolOT<>''00:00'' then ''Holiday '' end  and  '
SET @Query = @Query + ' TA_Tbl_OtType.isdeleted=0 and (ppd.NormOT<>''00:00'' or ppd.HolOT<>''00:00'' or ppd.OffOT<>''00:00'') And'
SET @Query = @Query + ' TA_Tbl_OtType.CompanyID=' + CAST(@CompanyID AS NVARCHAR) + ''
--SET @Query = @Query + ' TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''+ @ToDate + ''', 102) order by EffectiveDate desc)'
--SET @Query = @Query + ' #EmpLevel.levelid in (' + @Level + ')'
create table #EmpOTExport
(TempId int identity(1,1),employee_code nvarchar(15),pay_month varchar(3),pay_year varchar(4),ot_type varchar(50),ot_hours nvarchar(25) default null,remarks nvarchar(200),
NormOTMins nvarchar(25),WeekOffOTMins nvarchar(25),
HolidayOTMins nvarchar(25))
insert into #EmpOTExport(employee_code,pay_month,pay_year,ot_type,remarks,NormOTMins,WeekOffOTMins,HolidayOTMins)
  EXEC(@Query) 
--select * from #EmpOTExport
declare @incr as int
declare @maxrec as int
set @incr=1
set @maxrec = (select max(TempId) from #EmpOTExport)
while(@incr<=@maxrec)
begin
	declare @hrsNormOTnv as nvarchar(25)
	declare @hrsWkOffOTnv as nvarchar(25)
	declare @hrsHOLOTnv as nvarchar(25)
	declare @dotposition as varchar(25)
	declare @length as int
	declare @hrsNormOTint as int
	declare @hrsWkOffOTint as int
	declare @hrsHOLOTint as int
	declare @minNormOTint as int
	declare @minWkOffOTint as int
	declare @minHOLOTint as int
	set @hrsNormOTnv = (select ISNULL(NormOTMins,'00:00') from #EmpOTExport where TempId=@incr)
	set @hrsWkOffOTnv = (select ISNULL(WeekOffOTMins,'00:00') from #EmpOTExport where TempId=@incr)
	set @hrsHOLOTnv = (select ISNULL(HolidayOTMins,'00:00') from #EmpOTExport where TempId=@incr)
	set @dotposition = CHARINDEX(':',@hrsNormOTnv)
	set @length = len(@hrsNormOTnv)
	set @hrsNormOTint = SUBSTRING(@hrsNormOTnv,1,@dotposition-1)
	set @minNormOTint = SUBSTRING(@hrsNormOTnv,cast(@dotposition+1 as int),@length)
	set @dotposition = CHARINDEX(':',@hrsWkOffOTnv)
	set @length = len(@hrsWkOffOTnv)
	set @hrsWkOffOTint = SUBSTRING(@hrsWkOffOTnv,1,@dotposition-1)
	set @minWkOffOTint = SUBSTRING(@hrsWkOffOTnv,cast(@dotposition+1 as int),@length)
	set @dotposition = CHARINDEX(':',@hrsHOLOTnv)
	set @length = len(@hrsHOLOTnv)
	set @hrsHOLOTint = SUBSTRING(@hrsHOLOTnv,1,@dotposition-1)
	set @minHOLOTint = SUBSTRING(@hrsHOLOTnv,cast(@dotposition+1 as int),@length)
	declare @otHrs as nvarchar(25)
	declare @otMins as nvarchar(25)
	declare @exportOTHrs as float
	set @otHrs = @hrsNormOTint + @hrsWkOffOTint + @hrsHOLOTint
	set @otMins = @minNormOTint + @minWkOffOTint + @minHOLOTint
	if(@otMins>=60)
		begin
			declare @minToHr as int 
			set @minToHr = @otMins / 60
			set @otHrs = @otHrs + @minToHr
			set @otMins = @otMins % 60
		end
	declare @result as nvarchar(25)
	set @result = @otHrs +':'+@otMins
	set @exportOTHrs = @otHrs * 60
	set @exportOTHrs = @exportOTHrs + @otMins
    declare @othours as nvarchar(25)
	set @othours = (select round (cast(replace(@result,':','.') as decimal) +   (round(cast(replace(@result,':','.') as float)- cast(replace(@result,':','.') as decimal),2)*100)/60,2))
    update  #EmpOTExport set ot_hours = @othours where TempId=@incr
	--select round( cast( ((@exportOTHrs) / 60) as float) ,2) as 'hours' 
    -- wrong result as 100%
	set @incr=@incr+1
end
select employee_code,pay_month,pay_year,ot_type,ot_hours,remarks from #EmpOTExport
drop table #EmpOTExport
  --Remove the temporary tables here
drop table #EmpLevel
drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollConfigSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name, Maria Prasanth>
-- Create date: <Create Date,,2022-Dec-19>
-- Description:	<Description,, Organization Setting Payroll Config Tab value>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PayrollConfigSetting]
	-- Add the parameters for the stored procedure here
	@CompanyID int,
	@DA	float=0,
	@HRANonMetro float=0,
	@HRAMetro float =0,
	@MedicalAmount bigint =0,
	@MedicalPercentage float =0,
	@isMedicalFlag bit=0,
	@CEAAmount bigint=0,
	@CEAPercentage float=0,
	@isCEAFlag bit=0,
	@tag char(3)=0,
	@EmployeeId int=0,
	@payrollconfigId int=0

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @UTCDateTime Datetime



if(@EmployeeId='1')
begin

Set @UTCDateTime = getdate()

end 

else
begin
	
	
Select @UTCDateTime=[dbo].[GetUTCTimeZoneDateTime](@EmployeeId)

end

   if(@tag='I')
   Begin 
		Insert Into TA_Tbl_PayrollConfigSetting (CompanyId,D_Allowance,HRA_Metro,HRA_NonMetro,MedicalAmount,MedicalPercent,CEAAmount,CEAPercentage,isMedicalflag,isCEAflag,isDeleted,createdBy,createDate,modifyDate)
		Values(@CompanyID,@DA,@HRANonMetro,@HRAMetro,@MedicalAmount,@MedicalPercentage,@CEAAmount,@CEAPercentage,@isMedicalFlag,@isCEAFlag,0,@EmployeeId,@UTCDateTime,null)

   End

   if(@tag='S')
   Begin
		Select * From TA_Tbl_PayrollConfigSetting where CompanyId=@CompanyID
   End
  
  if(@tag='U')
  Begin
	Update TA_Tbl_PayrollConfigSetting set D_Allowance=@DA,HRA_Metro=@HRAMetro,HRA_NonMetro=@HRANonMetro,MedicalAmount=@MedicalAmount,MedicalPercent=@MedicalPercentage,CEAAmount=@CEAAmount,CEAPercentage=@CEAPercentage
	,isMedicalflag=@isMedicalFlag,isCEAflag=@isCEAFlag,CreatedBy=@EmployeeId,modifyDate=@UTCDateTime where CompanyId=@CompanyID

  End

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PaySlipReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PaySlipReport]
	-- Add the parameters for the stored procedure here

	@tag char(3),
	@EmployeeName nvarchar(30)=null,
	@EmployeeCodeID nvarchar(20)=null,
	@Designation nvarchar(30)=null,
	@Gender char(10)=null,
	@PayslipMonth varchar(20)=null,
	@year varchar(20)=null,
	@Calender_Days int=0,
	@PD int=0,
	@AD int=0,
	@LD int=0,
	@WOD int=0,
	@HD int=0,
	@LOPD int=0,
	@TotalOT varchar(20)=null,
	@CTC int=0,
	@BasicSalary bigint=0,
	@DA bigint=0,
	@Hra bigint=0,
	@EarnedAmount bigint=0,
	@CA bigint=0,
	@MA bigint=0,
	@CEA bigint=0,
	@Tds_PolicyId int=0,
	@PF bigint=0,
	@ESI bigint=0,
	@LoanCount bigint=0,
	@LoanDueAmount bigint=0,
	@TDSAmount bigint=0,
	@Professional_Tax bigint=0,
	@TotalDeduction bigint=0,
	@TotalAddition bigint=0,
	@NetSalary bigint=0,
	@OA bigint=0

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	SET NOCOUNT ON;

    -- Insert statements for procedure here

	if(@tag='I')
	Begin
		Insert Into TA_Tbl_PaySlip (EmployeeName,Employee_Code_Id,Designation,Gender,PayslipMonth,Calender_Days,Present_Days,Absent_Days,Leave_Days,Weekly_OFF_Days,Holiday_Days,LossofPay_Days,TotalOTHrs,CostToCompany,BasicSalary,EarnedAmount,
		Dearness_Allowance,HouseRent_Allowance,Conveyance_Allowance,Medical_Allowance,Children_Education_Allowance,Tds_PolicyId,ProvidentFund,ESI,LoanCount,LoanDueAmount,TDSAmount,Professional_Tax,TotalAdditions,TotalDeduction,NetSalary,generateDate,OA,PayslipYear)Values
		(@EmployeeName,@EmployeeCodeID,@Designation,@Gender,@PayslipMonth,@Calender_Days,@PD,@AD,@LD,@WOD,@HD,@LOPD,@TotalOT,@CTC,@BasicSalary,@EarnedAmount,@DA,
		@Hra,@CA,@MA,@CEA,@Tds_PolicyId,@PF,@ESI,@LoanCount,@LoanDueAmount,@TDSAmount,@Professional_Tax,@TotalAddition,@TotalDeduction,@NetSalary,GETDATE(),@OA,@year)

		Select 1 As Num

		--if(@LoanCount>0 and @LoanDueAmount!=0)
		--Begin
			
		--	Select * from TA_Tbl_PaySlip

		--	insert into TA_Tbl_LoanTransaction(LoanID,LoanAmount,TransactionDate,CreditedAmount,Balance_Amount,Remaining_DueMonth)
		--	Values(

		--	Select * From TA_Tbl_LoanEntryDetails
			
		--End

	End
	if(@tag='S')
	Begin

		Select * From TA_Tbl_PaySlip where Employee_Code_Id In (@EmployeeCodeID) and PayslipMonth=@PayslipMonth and PayslipYear=@year

	End

	if(@tag='U')
	Begin
		Update TA_Tbl_PaySlip set Designation=@Designation,PayslipMonth=@PayslipMonth,Calender_Days=@Calender_Days,Present_Days=@PD,Absent_Days=@AD,Leave_Days=@LD,Weekly_OFF_Days=@WOD,Holiday_Days=@HD,
		LossofPay_Days=@LOPD,TotalOTHrs=@TotalOT,CostToCompany=@CTC,BasicSalary=@BasicSalary,EarnedAmount=@EarnedAmount,Dearness_Allowance=@DA,HouseRent_Allowance=@Hra,Conveyance_Allowance=@CA,Medical_Allowance=@MA,Children_Education_Allowance=@CEA,Tds_PolicyId=@Tds_PolicyId,
		LoanDueAmount=@LoanDueAmount,LoanCount=@LoanCount,TdsAmount=@TDSAmount,Professional_Tax=@Professional_Tax,TotalAdditions=@TotalAddition,NetSalary=@NetSalary,generateDate=GETDATE(),OA=@OA,PayslipYear=@year where Employee_Code_Id=@EmployeeCodeID
		
		Select * From TA_Tbl_PaySlip where Employee_Code_Id In (@EmployeeCodeID) and PayslipMonth=@PayslipMonth and PayslipYear=@year

	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PermanentDeleteAttandanceCode]
	@AttandanceID as varchar(2000),	
	@EmpID as int
AS
BEGIN
    declare @Query varchar(2000)
	set @Query=''	
	set @Query = @Query + 'delete from TA_Tbl_AttandanceCode where AttandanceID in (' + @AttandanceID + ')'
	exec(@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PermanentDeleteOtType] 
	@OtTypeID as int,	
	@EmpId as int
AS
BEGIN	
update  TA_Tbl_OtType set EmpID=@EmpID where OtTypeID=@OtTypeID
	delete from TA_Tbl_OtType where OtTypeID=@OtTypeID	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeletePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_PermanentDeletePolicy]
(
	@Type CHAR(30),	
	@PolicyId NVARCHAR(500)
)
As 
Begin
	DECLARE @Query1 NVARCHAR(2000)
	DECLARE @Query2 NVARCHAR(2000)
	DECLARE @Query3 NVARCHAR(2000)
	SET @Query1=''
	SET @Query2=''
	SET @Query3=''
	if(@Type='PermanentDeletePFPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_PF_ESIDetails WHERE PFESI_Id IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End
	if(@Type='PermanentDeleteCAPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_ConveyanceAllowance WHERE C_Id IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End
	Else if(@Type='PermanentDeleteTaxPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_TaxMasterDetails WHERE TaxPolicy_Id IN ('+ @PolicyId +')'
			EXEC (@Query1)

			SET @Query2 = 'DELETE FROM TA_Tbl_TdsSlab WHERE Tax_PolicyId IN ('+ @PolicyId +')'
			EXEC (@Query2)

			SET @Query3 = 'DELETE FROM TA_Tbl_ProfSlab WHERE Tax_PolicyId IN ('+ @PolicyId +')'
		    EXEC (@Query3)
	End
	Else if(@Type='PermanentDeleteLoan')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_LoanEntryDetails WHERE Loan_ID IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End
End


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentTaxPolicyDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth S>
-- Create date: <Create Date,,07-Dec-22>
-- Description:	<Description,,Permenant Delete Tax Policy>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PermanentTaxPolicyDelete]

	
	@Type CHAR(30),	
	@PolicyId NVARCHAR(500)
AS
BEGIN

	DECLARE @Query1 NVARCHAR(2000)
	SET @Query1=''

	if(@Type='PermanentDeleteTaxPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_TaxMasterDetails WHERE TaxPolicy_Id IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End
	if(@Type='PermanentDeleteTDSPolicy')
	Begin
			SET @Query1 = 'DELETE FROM TA_Tbl_TdsSlab WHERE Tax_PolicyId IN ('+ @PolicyId +')'
			EXEC (@Query1)
	End
	if(@Type='PermanentDeleteProfPolicy')
	Begin
		SET @Query1 = 'DELETE FROM TA_Tbl_ProfSlab WHERE Tax_PolicyId IN ('+ @PolicyId +')'
		EXEC (@Query1)
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PFESIPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_PFESIPolicy] 
(
	@tag varchar(20),
	@companyID int=null,
	@Employee_Id INT=null,
	@EmployeeCategory INT=null,
	@EmployeeType INT=null,
	@Gender nvarchar(10)=null,
	@PFESIPolicyName varchar(20)=null,
	@PFPolicyid int=null,
	@PFEmployer float=null,
	@PFEmployee float=null,
	@ESIEmployer float=null,
	@ESIEmployee float=null,
	@LevelID int=null
)
as 
Begin
	Declare @isDeleted bit
	set @isDeleted=0

	if(@tag='I')
	begin
		Insert into TA_Tbl_PF_ESIDetails (PFESI_PolicyName,CompanyId,EmployeeCategory,EmployeeType,Gender,PF_Employer,PF_Employee,ESI_Employer,ESI_Employee,Creadted_BY,Created_Date,Modifi_Date,isDeleted) Values
		(@PFESIPolicyName,@companyID,@EmployeeCategory,@EmployeeType,@Gender,@PFEmployer,@PFEmployee,@ESIEmployer,@ESIEmployee,@Employee_Id,getDate(),null,@isDeleted)
	End
	else if(@tag='U')
	Begin
		Update TA_Tbl_PF_ESIDetails set PF_Employee=@PFEmployee,PF_Employer=@PFEmployer,ESI_Employee=@ESIEmployee,ESI_Employer=@ESIEmployer,CompanyId=@companyID,EmployeeCategory=@EmployeeCategory,EmployeeType=@EmployeeType,Gender=@Gender,Modifi_Date=getDate()  where PFESI_Id=@PFPolicyid
	End
	else if(@tag='S')
	Begin
		If (isNull(@PFPolicyid,0)=0 and ISNULL(@LevelID,0)=0)
		Begin
			Select PFESI_PolicyName,PFESI_Id,1 as flag From TA_Tbl_PF_ESIDetails 
		End
		else if(isNull(@PFPolicyid,0)=0 and ISNULL(@LevelID,0)!=0)
		Begin
			Select PFESI_PolicyName,PFESI_Id,1 as flag From TA_Tbl_PF_ESIDetails where CompanyId=dbo.Func_TA_GetParentIds(@LevelID)
		End
		Else
		Begin
			Select PFESI_PolicyName,PFESI_Id,PF_Employee,PF_Employer,ESI_Employee,ESI_Employer,CompanyId,Gender,EmployeeCategory,EmployeeType  From TA_Tbl_PF_ESIDetails where PFESI_PolicyName=@PFESIPolicyName or PFESI_Id=@PFPolicyid
		End
	End
	Else if(@tag='policyName')
	Begin
		Select PFESI_PolicyName,PFESI_Id,PF_Employee,PF_Employer,ESI_Employee,ESI_Employer,CompanyId,Gender,EmployeeCategory,EmployeeType  From TA_Tbl_PF_ESIDetails where PFESI_PolicyName=@PFESIPolicyName
	End
	Else if(@tag='D')
	Begin
		if(@PFPolicyid!=' ')
		begin
			Delete From TA_Tbl_PF_ESIDetails where PFESI_Id=@PFPolicyid
			select '1' as D_count
		End
		else
		begin
			select '0' as D_count
		end
	End
	
End

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PolicyName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_PolicyName]  (@PolicyId int,@PolicyName varchar(50))
as
SELECT COUNT(*) FROM TA_Tbl_LeavePolicy WHERE PolicyName=@PolicyName and IsDeleted=0 and Policy_Id <>@PolicyId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Preferences]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 22-09-2017
-- =============================================
create PROCEDURE [dbo].[Proc_TA_Preferences]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	select isDomain,DomainName,DomainAdminUserName,DomainAdminPassword from TA_Tbl_Preferences
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProInsertShiftLocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_ProInsertShiftLocation '2020-01-02 00:00:00.000',1,19

CREATE PROCEDURE [dbo].[Proc_TA_ProInsertShiftLocation]
@Shiftdate datetime,
@UserId int,
@LocationId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

IF EXISTS (select EmployeeId from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId )
BEGIN
		IF NOT EXISTS (select Shift_Lcoation_Id from TA_tbl_ShiftAdd_Location where ShiftDate= @Shiftdate 
		and EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId   ))
			BEGIN
			Insert into TA_tbl_ShiftAdd_Location(EmployeeId, LocationId,ShiftDate,CreatedBy)
			select EmpID, @LocationId, @Shiftdate, @UserId
			from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId
			END

		ELSE
			BEGIN
			UPDATE TA_tbl_ShiftAdd_Location
			set LocationId = @LocationId, ModifiedBy = @UserId, ModifiedOn=getdate()
			where ShiftDate= @Shiftdate and EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId)
			END
		END

END


Select * From TA_Tbl_TempShiftAllocation
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectDuplicate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ProjectDuplicate]
	-- Add the parameters for the stored procedure here
	@Project_Name varchar(250)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select count(*) from TA_Tbl_Project where Project_Name=@Project_Name and IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectReport_Mesmack]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<Project Summary Report>
-- =============================================
--Proc_TA_ProjectReport_Mesmack 'v124','0,1','01/jan/2019','30/Dec/2019','',0,0,0,'SuperAdmin','0',0,0,'Both',0,0,0
--v124	477	11124 SANTHOSAM M
CREATE PROCEDURE [dbo].[Proc_TA_ProjectReport_Mesmack]

	@EmployeeID varchar(50), 
	@LevelID varchar(8000),  
	@FromDate varchar(50), 
	@ToDate varchar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int,
	@ProjectId bigint

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @local_EmployeeID varchar(50)
	DECLARE @local_LevelID varchar(8000)
	DECLARE @local_FromDate varchar(50) 
	DECLARE @local_ToDate varchar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	DECLARE @local_ProjectId int

	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	set @local_ProjectId=@ProjectId

	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	DECLARE @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	create table #Project(projectId bigint)
    create table #EmpOvertime(SwipecardNo varchar(50),overtimeduration varchar(10));
	create table #EmpAbsent(SwipecardNo varchar(50), Absentdays float);
	create table #EmpSickeLeave(SwipecardNo varchar(50),EmployeeName varchar(200), SickeLeaves float);
	create table #EmpUmrahLeave(SwipecardNo varchar(50),EmployeeName varchar(200), UmrahLeave float);
	create table #EmpOtherLeave(SwipecardNo varchar(50),EmployeeName varchar(200), OtherLeave float);
	create table #tempProjectSummary (EmployeeName varchar(200),Employee_Code_Id varchar(50), overtimeduration varchar(10),Absentdays float,SickeLeaves float,UmrahLeave float,OtherLeave float)

	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	create table #EmployeeNames(SwipecardNo varchar(50), EmployeeName varchar(200), EmployeeCodeId varchar(50))

	--insert into #Project
	--select Project_Id from ta_tbl_project
	--where (Project_StartTime >= CONVERT(DATETIME,''+cast(@local_FromDate as nvarchar(20))+'', 102)
	--and Project_EndTime <=  CONVERT(DATETIME,''+cast(@local_ToDate as nvarchar(20))+'', 102) )
	--and (Project_Status != 'Rejected') and (IsDeleted = 0)

    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 


	--insert into level table
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End	
	Execute(@sqlEmpLevel);

	--Overtime for the duration coding

	WITH cte AS (
    SELECT a.Employee_Code_Id,SUM(DATEDIFF(MINUTE, '00:00', CAST(NormOT AS TIME))) t
    FROM TA_Tbl_ProcessedData a
	inner join #EmpLevel b on b.SwipeCard = a.Employee_Code_Id
	inner join #EmpDesignation c on c.SwipeCard = a.Employee_Code_Id
	inner join #EmpType d on d.SwipeCard = a.Employee_Code_Id
	inner join #EmpCategory e on e.SwipeCard = a.Employee_Code_Id
	where a.date >= CONVERT(DATETIME,''+cast(@local_FromDate as nvarchar(50))+'', 102) 
	and a.date <= CONVERT(DATETIME,''+cast(@local_ToDate as nvarchar(50))+'', 102) 
	GROUP BY a.Employee_Code_Id
	)

   	insert into #EmpOvertime SELECT Employee_Code_Id,
	RTRIM(t/60) + ':' + RIGHT('0' + RTRIM(t%60), 2) FROM cte

	--Absent days for the duration coding

	insert into #EmpAbsent	
	select a.Employee_Code_Id,
	sum(case when a.FNAttendanceCode = 'Absent' and a.ANAttendanceCode = 'Absent' then 1
	else 0
	end)
	FROM TA_Tbl_ProcessedData a
	inner join #EmpLevel b on b.SwipeCard = a.Employee_Code_Id
	inner join #EmpDesignation c on c.SwipeCard = a.Employee_Code_Id
	inner join #EmpType d on d.SwipeCard = a.Employee_Code_Id
	inner join #EmpCategory e on e.SwipeCard = a.Employee_Code_Id
	where a.date >= CONVERT(DATETIME,''+cast(@local_FromDate as nvarchar(50))+'', 102) 
	and a.date <= CONVERT(DATETIME,''+cast(@local_ToDate as nvarchar(50))+'', 102) 
	GROUP BY a.Employee_Code_Id


	--Leave count according to type coding

	declare @DynamicSQL varchar(max)
	set @DynamicSQL = ''

	set @DynamicSQL = @DynamicSQL + 'select b.SwipeCardNo, b.Employee_FirstName, isnull(sum(isnull(a.NumberOfDays,0)),0)
	from TA_Tbl_LeaveApplication a
	inner join TA_Tbl_LeaveType d on d.LeaveType_Id = a.LeaveType_id
	inner join ta_tbl_employee b on b.Employee_Id = a.Employee_Id
	inner join #EmpLevel c on c.SwipeCard = b.SwipeCardNo
	where a.Leave_FromDate >= CONVERT(DATETIME,'''+cast(@local_FromDate as nvarchar(50))+''', 102) 
	and a.Leave_ToDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) 
	and (d.LeaveType_Id = a.LeaveType_id)	'

	insert into #EmpSickeLeave exec(@DynamicSQL + ' and d.LeaveType = ''SL'' group by b.SwipeCardNo,b.Employee_FirstName ' ) 
	insert into #EmpUmrahLeave exec(@DynamicSQL + ' and d.LeaveType = ''EL'' group by b.SwipeCardNo, b.Employee_FirstName' ) 
	insert into #EmpOtherLeave exec(@DynamicSQL + ' and d.LeaveType not in (''SL'',''EL'') group by b.SwipeCardNo,b.Employee_FirstName' ) 
	
	--insert into employee names table	
	insert into #EmployeeNames
	select a.SwipecardNo, b.Employee_FirstName, b.Employee_Code_Id
	from #EmpOvertime a
	inner join ta_tbl_employee b on b.SwipeCardNo = a.SwipecardNo

	-- the final table for rpt binding

	insert into #tempProjectSummary (
	EmployeeName,
	Employee_Code_Id,
	overtimeduration,
	Absentdays,
	SickeLeaves,
	UmrahLeave,
	OtherLeave)
	select 
	isnull(f.EmployeeName,''),
	isnull(f.EmployeeCodeId,''),
    isnull(a.overtimeduration,0),
	isnull(b.Absentdays,0),
	isnull(c.SickeLeaves,0),
	isnull(d.UmrahLeave,0),
	isnull(e.OtherLeave,0)
	from #EmpOvertime a
	left outer join #EmpAbsent b on b.SwipecardNo = a.SwipecardNo
	left outer join #EmpSickeLeave c on c.SwipecardNo = a.SwipecardNo
	left outer join #EmpUmrahLeave d on d.SwipecardNo = a.SwipecardNo
	left outer join #EmpOtherLeave e on e.SwipecardNo = a.SwipecardNo
	inner join #EmployeeNames f on f.SwipecardNo = a.SwipecardNo


	select 
	isnull(EmployeeName,'') as EmployeeName,
	isnull(Employee_Code_Id,'')as Employee_Code_Id,
	isnull(overtimeduration,'') as overtimeduration,
	isnull(Absentdays,0) as Absentdays,
	isnull(SickeLeaves,0) as SickeLeaves,
	isnull(UmrahLeave,0) as UmrahLeave,
	isnull(OtherLeave,0) as OtherLeave
	from #tempProjectSummary

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RAWDATANEWSELECTFORREPORT]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_RAWDATANEWSELECTFORREPORT]

@FROMDATE DATETIME = '',
@TODATE DATETIME = ''

	
AS
BEGIN
	SELECT CLK_DATE,CLK_CARDID,dbo.TA_Tbl_Terminal.Terminal_Name AS [PLANET NAME],dbo.TA_Tbl_Employee.Employee_Code_Id AS [EMPLOYEE ID],
dbo.TA_Tbl_Employee.Employee_FirstName AS [EMPLOYEE NAME],dbo.Ta_Tbl_levelDetails.name AS DEPARTMENT,CLK_DATE  + Max(CLK_TIME) as INPUNCH,CLK_DATE  + Min(CLK_TIME) as OUTPUNCH,

[dbo].[ConvertMinsToHours](DATEDIFF(MI,CLK_DATE  + max(CLK_TIME),CLK_DATE  + min(CLK_TIME))) as WORKHOURS


FROM TA_Tbl_Clk_RawData INNER JOIN
 dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
 dbo.TA_Tbl_EmployeeLevel ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN
 dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelId = dbo.Ta_Tbl_levelDetails.id INNER JOIN
 dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID


WHERE dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE BETWEEN '2023-04-01 00:00:00.000' AND '2023-05-30 00:00:00.000' 
GROUP BY CLK_DATE,CLK_CARDID,dbo.TA_Tbl_Terminal.Terminal_Name,dbo.TA_Tbl_Employee.Employee_Code_Id ,
dbo.TA_Tbl_Employee.Employee_FirstName ,dbo.Ta_Tbl_levelDetails.name


END







--SELECT        dbo.TA_Tbl_Employee.Employee_FirstName, dbo.TA_Tbl_Clk_RawData.CLK_CARDID, dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID, dbo.TA_Tbl_Clk_RawData.CLK_DATE, dbo.TA_Tbl_Clk_RawData.CLK_TIME, 
--                         dbo.TA_Tbl_Clk_RawData.CLK_TYPE, dbo.TA_Tbl_Clk_RawData.CLK_FLAG, dbo.TA_Tbl_Clk_RawData.CLK_PROCESS, dbo.TA_Tbl_Clk_RawData.TimeStamp, dbo.TA_Tbl_Clk_RawData.TimecheckDateTime, 
--                         dbo.TA_Tbl_Clk_RawData.ReasonId, dbo.TA_Tbl_Terminal.Terminal_Name INTO #PIN
--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE ='2023-05-04 00:00:00.000' and 
--CLK_TIME  = (SELECT  MAX( CLK_TIME)FROM dbo.TA_Tbl_Clk_RawData WHERE CLK_TYPE = 1 AND CLK_DATE ='2023-05-04 00:00:00.000')


--SELECT        dbo.TA_Tbl_Employee.Employee_FirstName, dbo.TA_Tbl_Clk_RawData.CLK_CARDID, dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID, dbo.TA_Tbl_Clk_RawData.CLK_DATE, dbo.TA_Tbl_Clk_RawData.CLK_TIME, 
--                         dbo.TA_Tbl_Clk_RawData.CLK_TYPE, dbo.TA_Tbl_Clk_RawData.CLK_FLAG, dbo.TA_Tbl_Clk_RawData.CLK_PROCESS, dbo.TA_Tbl_Clk_RawData.TimeStamp, dbo.TA_Tbl_Clk_RawData.TimecheckDateTime, 
--                         dbo.TA_Tbl_Clk_RawData.ReasonId, dbo.TA_Tbl_Terminal.Terminal_Name INTO #POUT
--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE ='2023-05-04 00:00:00.000' and 
--CLK_TIME  = (SELECT  MIN( CLK_TIME)FROM dbo.TA_Tbl_Clk_RawData WHERE CLK_TYPE = 1 AND CLK_DATE ='2023-05-04 00:00:00.000')



--SELECT       dbo.TA_Tbl_Clk_RawData.CLK_DATE as [PUNCH DATE], dbo.TA_Tbl_Terminal.Terminal_Name AS [PLANET NAME],dbo.TA_Tbl_Employee.Employee_Code_Id AS [EMPLOYEE ID],
--dbo.TA_Tbl_Employee.Employee_FirstName AS [EMPLOYEE NAME],dbo.Ta_Tbl_levelDetails.name AS DEPARTMENT,#PIN.CLK_TIME AS [IN PUNCH],#POUT.CLK_TIME AS [OUT PUNCH] ,

--(DATEDIFF(HH,CONVERT(DATETIME,#PIN.CLK_TIME,104),CONVERT(datetime,#POUT.CLK_TIME,104)) %24) AS WORKHOURS,

--(CASE WHEN (DATEDIFF(HH,CONVERT(DATETIME,#PIN.CLK_TIME,104),CONVERT(datetime,#POUT.CLK_TIME,104)) %24) >=8 then 'P' else 'A' end ) as STATUS

--FROM            dbo.TA_Tbl_Clk_RawData INNER JOIN
--                         dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Clk_RawData.CLK_CARDID = dbo.TA_Tbl_Employee.Employee_Code_Id INNER JOIN
--                         dbo.TA_Tbl_EmployeeLevel ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN
--                         dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelId = dbo.Ta_Tbl_levelDetails.id INNER JOIN
--                         dbo.TA_Tbl_Terminal ON dbo.TA_Tbl_Clk_RawData.CLK_DEVICEID = dbo.TA_Tbl_Terminal.Terminal_ReaderID inner join 
--						 #PIN ON #PIN.CLK_CARDID = dbo.TA_Tbl_Clk_RawData.CLK_CARDID INNER JOIN 
--						 #POUT ON #POUT.CLK_CARDID = dbo.TA_Tbl_Clk_RawData.CLK_CARDID 
						 
--WHERE  dbo.TA_Tbl_Clk_RawData.CLK_TYPE = 1 AND dbo.TA_Tbl_Clk_RawData.CLK_DATE = '2023-05-04 00:00:00.000' 

--GROUP BY dbo.TA_Tbl_Clk_RawData.CLK_DATE , dbo.TA_Tbl_Terminal.Terminal_Name ,dbo.TA_Tbl_Employee.Employee_Code_Id ,
--dbo.TA_Tbl_Employee.Employee_FirstName ,dbo.Ta_Tbl_levelDetails.name,#PIN.CLK_TIME ,#POUT.CLK_TIME


----select * from #PIN
----select * from #POUT



--drop table #PIN
--drop table #POUT
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RecursionLeaveDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Proc_TA_RecursionLeaveDays 7,'04/02/2015 12:00:00 AM','04/04/2016 12:00:00 AM'
Created By		:	Manjula.P
Created Date	:	25-May-2013
Descriptions	:	To restrict the Continued leave as per the new leave policy
*/
CREATE proc [dbo].[Proc_TA_RecursionLeaveDays]
(
@Employee_Id int,
@LeavePrevious datetime,
@LeaveNext datetime
)
as begin
create table #TempRecursion
(
	LeaveApplicationId int,
	LeaveType varchar(50),
	LeaveFromDAte datetime,
	LeaveToDate datetime,
	EmpId int,
	Type varchar(50),
	NoOfDays decimal(18,1)
)
BEGIN
	SET NOCOUNT ON;
	declare @Count int;
	declare @DateDiff int;
	declare @FirstRowToDate datetime;
	set @Count=(select COUNT( LA.LeaveApplication_Id) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
	where (LA.Employee_Id=@Employee_Id) 
	and
	(
	(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
	or
	(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
	or           
	(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
	)
	and LA.IsDeleted=0 and LA.Status<>'Rejected')
	set @DateDiff=1;
	while (@Count>0 and (@DateDiff=1 or @DateDiff=-1) )
		begin
			insert into #TempRecursion
			select LA.LeaveApplication_Id, LT.LeaveType,LA.Leave_FromDate,LA.Leave_ToDate,Employee_Id,LA.Type, LA.NumberOfDays from TA_Tbl_LeaveApplication LA
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			where (LA.Employee_Id=@Employee_Id) 
			and
			(
			(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
			or
			(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
			or           
			(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
			)
			and LA.IsDeleted=0 and LA.Status<>'Rejected'
			set @FirstRowToDate=@LeaveNext;
			set @LeavePrevious=DATEADD(DAY,-1, @LeavePrevious)
			set @LeaveNext=DATEADD(DAY,1, @LeaveNext)
			--set @DateDiff=DATEDIFF(day,@LeavePrevious,@FirstRowToDate);
			set @Count= (select COUNT( LA.LeaveApplication_Id) from TA_Tbl_LeaveApplication LA
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			where (LA.Employee_Id=@Employee_Id) 
			and
			(
			(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
			or
			(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
			or           
			(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
			)
			and LA.IsDeleted=0 and LA.Status<>'Rejected'  and LA.LeaveApplication_Id not in (select #TempRecursion.LeaveApplicationId from #TempRecursion))
		end
	select * from #TempRecursion 
	group by LeaveApplicationId,EmpId,LeaveFromDAte,LeaveToDate,LeaveType,NoOfDays,Type
	drop table #TempRecursion
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RegionNameByCid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_RegionNameByCid]
(@CompanyId int)
AS
DECLARE @Isdel int
SET @Isdel=1
BEGIN
SELECT Region_Id,Region_Name from TA_Tbl_Region WHERE Isdeleted=@Isdel and Company_Id=@CompanyId 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-02-2013
-- Description:	Removing the EmailReportNotSendedDetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]
	-- Add the parameters for the stored procedure here
	@ReScheduleid bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM Ta_tbl_EmailReportNotSendedDetails where ReScheduleid=@ReScheduleid
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RemoveImportMasterErrData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <17-11-2018 01.27 PM>
-- Description:	<To remove import master Error Data from database>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_RemoveImportMasterErrData]
AS
BEGIN
	SET NOCOUNT ON;
	Delete from TA_Tbl_ImportMasterError
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplaceInDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Check whether the InTime lies inbetween any InTime and OutTime in the Clock Details Table for particular Employee
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ReplaceInDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@Type char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if @Type='I'
	begin
		Select Clk_Id,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_OutDeviceId IN (@strOutDeviceId) AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <@strInDateTime ) 
		AND (CAST(Clk_OutDate+Clk_OutTime AS DateTime) > @strInDateTime) AND IsVoid=0
	end
	if @Type='O'
	begin
		Select Clk_Id,Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_InDeviceId IN (@strOutDeviceId) 
		AND (CAST(Clk_InDate+Clk_InTime AS DateTime) < @strInDateTime) 
		AND (CAST(Clk_OutDate+Clk_OutTime AS DateTime) > @strInDateTime) AND IsVoid=0
	end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReplaceReportingPerson]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_ReplaceReportingPerson]
(
@OldManagerEmployeeCode varchar(15),
@NewManagerEmployeeCode varchar(15)
)
AS
BEGIN
	DECLARE @OldManagerEmployeeId as bigint
	DECLARE @NewManagerEmployeeId as bigint
	SET @OldManagerEmployeeId=(SELECT Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@OldManagerEmployeeCode)
	SET @NewManagerEmployeeId=(SELECT Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@NewManagerEmployeeCode)
	UPDATE TA_Tbl_Employee SET Reporting_To=@NewManagerEmployeeId WHERE Reporting_To=@OldManagerEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplacingSMSContent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-01-2017 12.54>
-- Description:	<Description,,>
-- After the release of ver2.4, we got the sms gateway for testing. That time we created this procedure
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ReplacingSMSContent]
AS
BEGIN
	SET NOCOUNT ON;
	-- if any white list are used by client, we need to append those string into below service url @serviceUrl
	--select '\nInfo:Timecheck\n-Trinetra' as whiteList
	select '' as whiteList
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenu]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_ReportsSubMenu] 149,7
--	Modified By		:	Manjula.P
--	Modified On		:	04-Oct-2013
--	Descriptions	:	Adding order by P.pageId for displaying menu order correctly. : Mantis : 0019213
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ReportsSubMenu] 
	-- Add the parameters for the stored procedure here
	@ReportsMenu varchar(50),
	@groupId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if(@ReportsMenu = 'ReportsMenu')
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId
			where (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			--Added by Manjula.P on 04-Oct-2013 for getting Employee order wise Mantis : 0019213 
			order by P.pageId
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenuForExpress]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
/*
--	Create By		:	Thilakraj.C
--	Create On		:	26-Nov-2013
--  Reson : For Express edition creation
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ReportsSubMenuForExpress] 
	-- Add the parameters for the stored procedure here
	@ReportsMenu varchar(50),
	@groupId int,
 @strType varchar(20)   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
  if(@strType='Standard')
  begin  
    if(@ReportsMenu = 'ReportsMenu')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1)
			and ur.groupId=@groupId and P.pageId not in 			
			(20,24,25,69,96,97,98,110,133,93,116,127,130,118,174) 
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			and P.pageId not in (20,24,25,69,96,97,98,110,133,93,116,127,130,118,174) 
			order by P.pageId
		end
	End
	else if(@strType='Express')
	begin  
    if(@ReportsMenu = 'ReportsMenu')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) 
			and ur.groupId=@groupId and P.pageId not in (20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,76,60,116,118,127,130,117,174,175) 
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			and P.pageId not in (20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,76,60,116,118,127,130,117,174,175) 
			order by P.pageId
		end
	End
else
begin
if(@ReportsMenu = 'ReportsMenu')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			order by P.orderBy
		end
End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Reprocess_HolidayData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 12/01/2015
-- Description:	Reprocess the past entries while creating a holidays.
-- [Proc_Ta_Reprocess_HolidayData]'2015-06-10','2015-06-10'
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_Reprocess_HolidayData]
	-- Add the parameters for the stored procedure here			
	@FromDate DATETIME,
	@ToDate Datetime	
AS
BEGIN
	set nocount on;
	Declare @HOLIDAYLEVELID nvarchar(max)
	set @HOLIDAYLEVELID =-1
	SELECT @HOLIDAYLEVELID=coalesce(@HOLIDAYLEVELID+',','')+convert(varchar(20),hct.LevelId) FROM TA_Tbl_Holiday 
	inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id	
	where 
	(
		((TA_Tbl_Holiday.Holiday_FromDate between @FromDate and @ToDate and TA_Tbl_Holiday.Isdeleted=0) 
		or 
		(TA_Tbl_Holiday.Holiday_ToDate between @FromDate and @ToDate and TA_Tbl_Holiday.Isdeleted=0))	
	) 	
	or 
	(
		((@FromDate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
	 or 
		(@ToDate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))	
	) 
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,''
	Declare @dtFROMDate datetime
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData PD inner join ta_tbl_employee E on PD.employee_code_id=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Date BETWEEN @FromDate AND @todate and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Clk_Date BETWEEN @FROMDate AND @ToDate and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
	SET @dtFROMDate=@fromdate
	WHILE(@dtFROMDate<=@todate)
		BEGIN
			DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
			WHERE Clk_InDate=@dtFROMDate and E.Isdeleted =0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
			WHERE Clk_OutDate=@dtFROMDate and Clk_InDate is null and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			UPDATE TA_Tbl_ManualTimeEntry set Clk_Process='N' FROM Ta_Tbl_ManualTimeEntry MT inner join ta_tbl_employee E on MT.ManualTimeEntry_Employee_Id=E.Employee_Code_Id
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
            where (ManualTimeEntry_InDate = @dtFROMDate or ManualTimeEntry_OutDate = @dtFROMDate) and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			SET @dtFROMDate=DateAdd(d,1,@dtFROMDate)
		END       
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 FROM TA_Tbl_Clk_RawData CR inner join ta_tbl_employee E on CR.CLK_CARDID=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Clk_Date BETWEEN DateAdd(d,-1,@FROMDate) AND DateAdd(d,1,@ToDate) and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReprocessEmpData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_ReprocessEmpData]  
(   
	@FromDate Datetime,  
	@ToDate Datetime,  
	@EmployeeCodeId varchar(50)   
)  
AS  
BEGIN
	set nocount on
	Declare @SwipeCardNumber varchar(50)
	select @SwipeCardNumber=SwipeCardNo from ta_tbl_employee where Employee_Code_Id=@EmployeeCodeId and isdeleted=0
	--select @FromDate,@ToDate,@EmployeeCodeId
	DELETE PD FROM TA_Tbl_ProcessedData PD Where PD.Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) And PD.Employee_Code_Id=@SwipeCardNumber
	Update TA_Tbl_Clk_RawData Set CLK_FLAG=0,CLK_PROCESS=0 Where CLK_DATE BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	and CLK_CARDID=@SwipeCardNumber
	Delete CD from TA_Tbl_ClockDetails CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	Delete CD from ta_tbl_MatchedPunches CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	UPDATE MT SET MT.Clk_Process = 'N' from TA_Tbl_ManualTimeEntry MT
	Inner join TA_Tbl_Employee E on E.Employee_Code_Id = MT.ManualTimeEntry_Employee_Id 
	AND ((MT.ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,isnull(@FromDate,@Todate)) AND DateAdd(d,1,isnull(@ToDate,@FromDate) )) 
	OR (MT.ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,isnull(@FromDate,@Todate)) AND DateAdd(d,1,isnull(@ToDate,@FromDate) )))  
	where MT.ManualTimeEntry_Employee_Id=@EmployeeCodeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ResetBonusLeaveForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 07-11-2014
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ResetBonusLeaveForService]
	@Employee_Code_Id varchar(50),
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	--RETRY: -- Label RETRY
	--BEGIN TRANSACTION
	--	BEGIN TRY
	UPDATE TA_Tbl_ProcessedData SET  fnAttendanceCode='Absent', anAttendanceCode='Absent', Attendance = 'Absent', Status = NULL 
	WHERE Employee_Code_Id = @Employee_Code_Id AND Status = 'BL' AND Date > @dtmDate
	--	COMMIT TRANSACTION
	--	END TRY
	--BEGIN CATCH	
	--	ROLLBACK TRANSACTION
	--	IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
	--	BEGIN
	--		WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
	--		GOTO RETRY -- Go to Label RETRY
	--	END
	--END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ResetPassword]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_ResetPassword](@EmpId varchar(10),@Password varchar(30))  
 -- Add the parameters for the stored procedure here  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
UPDATE TA_Tbl_Employee SET Emp_password=@Password WHERE Employee_Code_Id=@EmpId  
select count(*)  as ResetCount from TA_Tbl_Employee WHERE Employee_Code_Id=@EmpId  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_RestoreAttandanceCode]
	@AttandanceID as int,	
	@EmpID as int
AS
BEGIN
	update  TA_Tbl_AttandanceCode set 
				IsDeleted=0,				
				EmpID=@EmpID where 
		AttandanceID=@AttandanceID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Category set IsDeleted=0,EmpId='+cast(@EmpID as nvarchar(20))+' where CategoryId IN ('+ @CategoryID +')'
	Execute(@Query)
	--update TA_Tbl_Category set IsDeleted=0,EmpId = @EmpID where CategoryId=@CategoryID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Created by	:	P.Prabakaran
Created on	:	05-Feb_08
Description	:	Restore Shift Pattern Based on their Id's
*/
CREATE PROCEDURE [dbo].[Proc_TA_RestoreShiftPattern] 
@ShiftPatternIds varchar(1000)
as
DECLARE @restore NVARCHAR
SET @restore=0
DECLARE @Query NVARCHAR(2000)
SET @Query=''
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_ShiftPattern SET IsDeleted= ' + @restore + ' WHERE ShiftPattern_Id IN ('+ @ShiftPatternIds +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftRoster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--	Author		:	A.K.T.MOORTHI
--	Create date	:	17-Dec-2013
--	Description	:	Check Pattern Exists Are Not
--	EXEC [Proc_TA_RestoreShiftRoster] '10'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreShiftRoster]
	-- Add the parameters for the stored procedure here
	@ShiftRosterIds VARCHAR(MAX)	
AS
BEGIN
	DECLARE @TblShiftRoster TABLE(ShiftRosterId BIGINT, ShiftRosterName VARCHAR(50), LevelId BIGINT, PatternsCount INT, RetMessage VARCHAR(20), Process BIT)
	INSERT INTO @TblShiftRoster
		SELECT Value, SR.ShiftRoaster_Name, SR.Level_Id, SR.NumberOfPatterns, '', 0 FROM dbo.Split(@ShiftRosterIds, ',') Id
			INNER JOIN TA_Tbl_ShiftRoaster SR ON SR.ShiftRoaster_Id = ID.Value
		WHERE SR.IsDeleted = 1
	WHILE(EXISTS(SELECT ShiftRosterId FROM @TblShiftRoster WHERE Process = 0))
	BEGIN
		DECLARE @RosterId BIGINT, @Patterns INT, @LevelId BIGINT
		DECLARE @RosterName VARCHAR(50)
		DECLARE @SQLQuery VARCHAR(MAX), @Query VARCHAR(MAX)
		DECLARE @TblRosterId TABLE(ShiftRosterId BIGINT)
		SET @SQLQuery = 'SELECT DISTINCT ShiftRoaster_Id FROM TA_Tbl_ShiftRoaster SR'
		SET @Query = ''
		SELECT @RosterId = ShiftRosterId, @Patterns = PatternsCount, @RosterName = ShiftRosterName, @LevelId = LevelId FROM @TblShiftRoster WHERE Process = 0
		;WITH Patterns AS(
			SELECT PC = 1
			UNION ALL
			SELECT PC = PC + 1 FROM Patterns WHERE PC < @Patterns
		)
		SELECT 
			@SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ShiftPattern SP' + CAST(PC AS VARCHAR(2)) + ' ON SP' + CAST(PC AS VARCHAR(2)) + '.ShiftPattern_Id = SR.Pattern' + CAST(PC AS VARCHAR(2)),
			@Query = @Query + ' AND SP' + CAST(PC AS VARCHAR(2)) + '.Isdeleted = 0'
		FROM Patterns
		IF(@Query != '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' WHERE SR.ShiftRoaster_Id = ' + CAST(@RosterId AS VARCHAR(20)) +  @Query
			INSERT INTO @TblRosterId
				EXEC(@SQLQuery)
			IF(EXISTS(SELECT * FROM @TblRosterId))
			BEGIN
				IF(NOT EXISTS(SELECT * FROM TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Name LIKE '' + @RosterName + '' AND IsDeleted = 0 AND Level_Id = @LevelId ))
				BEGIN
					UPDATE TA_Tbl_ShiftRoaster SET IsDeleted = 0 WHERE ShiftRoaster_Id = @RosterId
					UPDATE @TblShiftRoster SET RetMessage = 'Successfully' WHERE ShiftRosterId = @RosterId
				END
				ELSE
				BEGIN
					UPDATE @TblShiftRoster SET RetMessage = 'Exists' WHERE ShiftRosterId = @RosterId
				END
			END
			ELSE
			BEGIN
				UPDATE @TblShiftRoster SET RetMessage = 'Failed' WHERE ShiftRosterId = @RosterId
			END
		END
		UPDATE @TblShiftRoster SET Process = 1 WHERE ShiftRosterId = @RosterId
	END
	SELECT DISTINCT RetMessage FROM @TblShiftRoster
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''
	SET @Query = 'update TA_Tbl_Type set IsDeleted=0,EmpId='+cast(@EmpID as nvarchar(20))+' where TypeId IN ('+ @TypeID +')'
	Execute(@Query)
	--update TA_Tbl_Type set IsDeleted=0,EmpId = @EmpID where TypeId=@TypeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_RPT_FilterLevel]  
(  
  @lid varchar(1000)  
)  
AS  
BEGIN  
declare @qry as varchar(7000)  
set @qry = ('select id from ta_tbl_leveldetails where isdeleted=0 and parentid in (' + @lid + ')')  
exec (@qry)  
/*  
 DECLARE @lelid int, @lelName varchar(30)  
 SET @lelName = (SELECT min(id) FROM ta_tbl_leveldetails WHERE isdeleted=0 and parentid = @lid)  
 --INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES (@lid,@lelName)  
 SET @lelid = (SELECT min(ID) FROM ta_tbl_leveldetails WHERE isdeleted=0 and parentid = @lid)  
 if (@lelid <8)  
 BEGIN  
  EXEC dbo.proc_ta_rpt_filterlevel @lelid  
 END    
*/  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevelUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_RPT_FilterLevelUpdated]  
(  
	@lid varchar(1000)  ,
	@TotLevels varchar(5000)
)  
AS  
BEGIN  
	declare @qry as varchar(7000)  
	set @qry = ('select id from ta_tbl_leveldetails where isdeleted=0 and parentid in (' + @lid + ') and id in ('+ @TotLevels + ') ')  
	exec (@qry)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- Author:  <Author,,Name>      
-- ALTER  date: <Create Date,,>      
-- Description: <Description,,>      
-- exec Proc_TA_Rpt_header @LevelId=10
-- =============================================      
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_header]  
(      
 @LevelId int    
)
AS      
BEGIN        
	IF @LevelId <> 0
		BEGIN  
			DECLARE @LevelName table (LevelID int,LevelName nvarchar(250))    
			DECLARE @string nvarchar(2000) 
			WHILE((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '')    
				BEGIN    
					INSERT INTO @LevelName select id,replace(name,'&amp;','&') from TA_tbl_LevelDetails where id=@LevelId    
					SET @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId)
				END    
			SET @string = (select LevelName + ' / ' from @LevelName order by LevelID asc for xml path(''))    
			SET @string = LEFT(@string,LEN(@string) - 1)     
			SELECT isnull(@string,'') as name,city,logo from  TA_tbl_LevelDetails where id=(select min(LevelID) from @LevelName)    
		END  
	ELSE   
		BEGIN  
			SELECT logo from TA_tbl_LevelDetails where id=1
		END  
END      
    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header_Email]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[Proc_TA_Rpt_header_Email]  
(      
 @LevelId int     
)
AS      
BEGIN        
	IF @LevelId <> 0
		BEGIN  
			DECLARE @LevelName table (LevelID int,LevelName nvarchar(250))    
			DECLARE @string nvarchar(2000) 
			WHILE((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '')    
				BEGIN    
					INSERT INTO @LevelName select id,replace(name,'&amp;','&') from TA_tbl_LevelDetails where id=@LevelId    
					SET @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId)
				END    
			SET @string = (select LevelName + ' / ' from @LevelName order by LevelID asc for xml path(''))    
			SET @string = LEFT(@string,LEN(@string) - 1)     
			SELECT isnull(@string,'') as name,city,logo from  TA_tbl_LevelDetails where id=(select min(LevelID) from @LevelName)    
		END  
	ELSE   
		BEGIN  
			SELECT logo from TA_tbl_LevelDetails where id=1
		END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--	Modified By		:	Manjula.P., K.Gopinath
--	Modified On		:	30-Sep-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--	Descriptions	:	Selecting LOP with Leave type like LOP-CL, LOP-SL Mantis :0019151 
-- =============================================
--	Proc_TA_Rpt_LeaveSummaryDetails '04/01/2021','03/31/2022','','','','All','All',0,0,'SuperAdmin','','',0,0,'Both',1,9
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int,
	@YrSettingID bigint
)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_empId varchar(100)
	Declare @local_shift int
	Declare @local_EmployeeName varchar(50)
	Declare @local_LeaveType varchar(50)
	Declare @local_LeaveStatus varchar(30)
	Declare @local_employeeCategory int
	Declare @local_employeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)	
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_EmpAutoID int
	
	set @local_fromDat=@fromDat
	set @local_ToDat=@ToDat
	set @local_empId=@empId
	set @local_shift=@shift
	set @local_EmployeeName=@EmployeeName
	set @local_LeaveType=@LeaveType
	set @local_LeaveStatus=@LeaveStatus
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoID=@EmpAutoID
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@ParentID) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	--Employee Level Indexes
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@local_empId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@local_empId,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@local_empId,@local_employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@local_empId
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	create table #TempLeaveDetails 
	(
		Employee_Id bigint,
		Employee_Code_Id nvarchar(15),
		Employee_Name nvarchar(150),
		Designation nvarchar(250),
		PolicyName nvarchar(50),
		FromDate datetime,
		ToDate datetime,
		LeaveType_Id int,
		LeaveType_Name nvarchar(10),
		Leave_Days decimal(18,1),
		Leave_Days_Availed_Approved decimal(18,1),
		Leave_Days_Availed_InProgress decimal(18,1),
		Leave_Days_Remaining decimal(18,1),
		LOP_Days decimal(18,1),
		LOP_Days_Availed_Approved decimal(18,1),
		LOP_Days_Availed_InProgress decimal(18,1),
		LOP_Days_Remaining decimal(18,1),
		RestrictedHoliday decimal(18,1),
		RestrictedHoliday_Availed_Approved decimal(18,1),
		RestrictedHoliday_Availed_InProgress decimal(18,1),
		RestrictedHoliday_Remaining decimal(18,1),
		YearSettingsId int,
		Encashment decimal(18,1),
		CarryOver decimal(18,1),
		FinancialYear varchar(100)
	)
    DECLARE @sqlQuery varchar(8000)
    CREATE TABLE #TempYearSetting(AutoID INT IDENTITY(1,1),YrSettingID BIGINT)
    IF(@YrSettingID=0)
    BEGIN
		SELECT @YrSettingID=YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive=1
		INSERT INTO #TempYearSetting
		SELECT TOP 10 YearSettings_Id FROM TA_Tbl_YearSetting WHERE YearSettings_Id<=@YrSettingID 
    END
    ELSE
    BEGIN
		INSERT INTO #TempYearSetting VALUES(@YrSettingID)
    END    
    DECLARE @Start int
    SET @Start=1
    DECLARE @End int
    SELECT @End=COUNT(*) FROM #TempYearSetting
    WHILE @Start<=@End
    BEGIN
		SELECT @YrSettingID=YrSettingID FROM #TempYearSetting WHERE AutoID=@Start
		IF(ISNULL(@YrSettingID,'')!='')
		BEGIN
			set @sqlQuery = ''
			set @sqlQuery = @sqlQuery + 'insert into #TempLeaveDetails '
			set @sqlQuery = @sqlQuery + '(Employee_Id,Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,LeaveType_Id,LeaveType_Name, '
			set @sqlQuery = @sqlQuery + 'Leave_Days ,LOP_Days,RestrictedHoliday,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining, '
			set @sqlQuery = @sqlQuery + 'LOP_Days_Availed_Approved,LOP_Days_Availed_InProgress,LOP_Days_Remaining,RestrictedHoliday_Availed_Approved,RestrictedHoliday_Availed_InProgress,RestrictedHoliday_Remaining,YearSettingsId,Encashment,CarryOver,FinancialYear) '
			set @sqlQuery = @sqlQuery + 'select E.Employee_Id,E.Employee_Code_Id,isnull(E.Employee_FirstName,'''') + space(1) + isnull(E.Employee_lastName,''''),replace(TA_Tbl_Title.TitleName,''&amp;'',''&''),LP.PolicyName,Emp_LP.FromDate,Emp_LP.ToDate, '
			set @sqlQuery = @sqlQuery + 'LPD.LeaveType_Id,LT.LeaveType,case when YS.YearSettings_Id = empltd.YearSettingsId then Emp_LPD.No_Of_Days + empltd.PreviousYearBalance	     
			else Emp_LPD.No_Of_Days end,LPD.Max_LOP_Days,HS.Yearly_Maxdays as RestrictedHoliday,case when YS.YearSettings_Id = empltd.YearSettingsId then empltd.NoOffLeaveAvailed
			else 0 end,	0,0,0,0,0,0,0,0,ys.YearSettings_Id,isnull(en.NumberofDays,0),0,
			StartMonth+space(1)+CONVERT(varchar(10),StartYear)+'' - ''+EndMonth+space(1)+CONVERT(varchar(10),EndYear) '
			set @sqlQuery = @sqlQuery + 'from TA_Tbl_Employee E '
				If Not (@local_EmployeeName = '')  
				Begin  
					SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=E.Employee_Code_Id '
				End
			set @sqlQuery = @sqlQuery + 'Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + 'Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
			set @sqlQuery = @sqlQuery + 'Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + 'Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
			set @sqlQuery = @sqlQuery + 'Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id '
   			set @sqlQuery = @sqlQuery + 'INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId '
			set @sqlQuery = @sqlQuery + 'INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID '
			set @sqlQuery = @sqlQuery + 'Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_Emp_LeavePolicy Emp_LP on Emp_LP.employeeId=E.Employee_Id '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id = Emp_LP.LeavePolicy_Id '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id = Emp_LP.YearSettingId '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=Emp_LP.LeavePolicy_Id '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id = LPD.LeaveType_Id  '
			set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_Emp_LeavePolicyDetails Emp_LPD on Emp_LPD.Emp_LeavePolicyId = Emp_LP.Emp_LeavePolicyId '
			set @sqlQuery = @sqlQuery + 'and Emp_LPD.LeaveType_Id = LPD.LeaveType_Id '
			set @sqlQuery = @sqlQuery + 'left join TA_Tbl_HolidaySettings HS on HS.YearSettingId = YS.YearSettings_Id '
			set @sqlQuery = @sqlQuery + 'left outer join ta_tbl_emp_LeaveTypedetails empltd on (empltd.employeeid = Emp_LP.EmployeeId and empltd.leavetypeid=lpd.leavetype_id and empltd.YearSettingsId= YS.YearSettings_Id)'
			set @sqlQuery = @sqlQuery + 'left outer join ta_tbl_encashment en on en.employeeid=e.employee_id and ys.yearsettings_id=en.yearsettingid and LT.LeaveType_id=en.Leavetypeid '
			set @sqlQuery = @sqlQuery + 'left outer join ta_tbl_yearclosure yc on yc.Employee_Id=e.employee_id and ys.yearsettings_id=yc.Year_SettingID and LT.LeaveType_id=yc.LeaveTypeID'
			set @sqlQuery = @sqlQuery + ' where E.IsDeleted =0 and E.Employee_Code_Id<>''18000000'' and E.Employee_Status = 1 '
			--set @sqlQuery = @sqlQuery + 'and YS.IsActive='
			set @sqlQuery= @sqlQuery + ' and YS.YearSettings_Id=' +CONVERT(varchar(10),@YrSettingID)
			if(@local_UserGroupName<>'SuperAdmin')
				begin
					SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
				end		
			If Not (@local_EmpSwipeCard = '')  
				Begin  
				 Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @local_EmpSwipeCard + ''' '  
				End 
			if(@local_employeeCategory<>0)
				begin
					set @sqlQuery = @sqlQuery + ' and #EmpCategory.CategoryID = ' + cast (@local_employeeCategory as nvarchar(20))
				end
			if(@local_employeeType<>0)
				begin
					set @sqlQuery = @sqlQuery + ' and #EmpType.TypeID = ' + Cast(@local_employeeType  as nvarchar(20))
				end
			if(@local_DesignationID<>0)
				begin
				   set @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@local_DesignationID as nvarchar(8))
				end	
			if(@local_Gender<>'Both')
				begin
				   set @sqlQuery = @sqlQuery + ' and E.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
				end
			if(@isReportingto > 0)
					BEGIN
					   set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
					END
				 set @sqlQuery = @sqlQuery + ' order by Employee_Id '
			--print(@sqlQuery)
			exec(@sqlQuery)
		END
		set @Start=@Start+1
    END
    DROP TABLE #TempYearSetting
	
	update #TempLeaveDetails set CarryOver=isnull(case when Carry_PrevYear<>0 then Carry_PrevYear
	--Commented by manikandan. Carry over value is showing not having leave type too.
	--else Leave_Days 
	end ,0) from #TempLeaveDetails 
	inner join TA_Tbl_YearClosure yc on (#TempLeaveDetails.YearSettingsId=yc.Year_SettingID and #TempLeaveDetails.LeaveType_Id=yc.LeaveTypeID)
	and #TempLeaveDetails.Employee_Id=yc.Employee_Id 

	update #TempLeaveDetails set Leave_Days_Availed_Approved =Leave_Days_Availed_Approved+ A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id,LA.YearSettings_Id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id and LD.YearSettingsId=LA.YearSettings_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type='Leave' and LA.Status = 'Approved' and LA.isdeleted=0 and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id,LA.YearSettings_Id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id and #TempLeaveDetails.YearSettingsId=A.YearSettings_Id)
	
	--update #TempLeaveDetails set Leave_Days_Availed_Approved =Leave_Days_Availed_Approved+ A.NumberOfDays from
	--(
	--	select E.EmployeeId,isnull(sum(E.NumberOfDays),0) as NumberOfDays,E.LeaveTypeId from TA_Tbl_Encashment E
	--	inner join #TempLeaveDetails LD on LD.Employee_Id = E.EmployeeId
	--	and LD.LeaveType_Id = E.LeaveTypeId 
	--	inner join TA_Tbl_YearSetting ys on E.YearSettingId=ys.YearSettings_Id
	--	where ys.IsActive=1
	--	group by  E.EmployeeId,E.LeaveTypeId
	--) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.EmployeeId and #TempLeaveDetails.LeaveType_id = A.LeaveTypeId)
	
	update #TempLeaveDetails set Leave_Days_Availed_InProgress = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type='Leave' and LA.Status in ('Pending','Forwarded') and LA.isdeleted=0 and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set Leave_Days_Remaining = ((Leave_Days+CarryOver) - (Leave_Days_Availed_Approved + Leave_Days_Availed_InProgress+Encashment))
	update #TempLeaveDetails set LOP_Days_Availed_Approved = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type='LOP' and LA.Status = 'Approved' and LA.isdeleted=0  and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set LOP_Days_Availed_InProgress = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id and LA.isdeleted=0 
		where LA.type='LOP' and LA.Status in ('Pending','Forwarded') and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set LOP_Days_Remaining = (LOP_Days - (LOP_Days_Availed_Approved + LOP_Days_Availed_InProgress))
	update #TempLeaveDetails set RestrictedHoliday_Availed_Approved = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
		inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
		where LA.type='Restricted Holiday' and LA.Status = 'Approved' and LA.isdeleted=0  and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type='Restricted Holiday' and LA.Status in ('Pending','Forwarded') and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Remaining = (RestrictedHoliday - (RestrictedHoliday_Availed_Approved + RestrictedHoliday_Availed_InProgress))
	create table #TempLeaveDetails_Final 
	(
		Employee_Code_Id nvarchar(15),
		Employee_Name nvarchar(150),
		Designation nvarchar(250),
		PolicyName nvarchar(50),
		FromDate datetime,
		ToDate datetime,
		LeaveType_Name nvarchar(20),
		Leave_Days decimal(18,1),
		Leave_Days_Availed_Approved decimal(18,1),
		Leave_Days_Availed_InProgress decimal(18,1),
		Leave_Days_Remaining decimal(18,1),
		CarryOver decimal(18,1),
		Encashment decimal(18,1),
		yearsettingID bigint,
		FinancialYear varchar(100)
	)
	insert into #TempLeaveDetails_Final select Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining,CarryOver,Encashment,YearSettingsId,FinancialYear from #TempLeaveDetails
	
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining,yearsettingID,FinancialYear)
	select Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,'LOP-'+#TempLeaveDetails.LeaveType_Name,isnull(LOP_Days,0),isnull(LOP_Days_Availed_Approved,0),isnull(LOP_Days_Availed_InProgress,0),isnull(LOP_Days_Remaining,0),YearSettingsId,FinancialYear
	from #TempLeaveDetails where LOP_Days<>0.0
	
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining,yearsettingID,FinancialYear)
	select distinct Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,'Restricted Holiday',isnull(RestrictedHoliday,0),isnull(RestrictedHoliday_Availed_Approved,0),isnull(RestrictedHoliday_Availed_InProgress,0),
	isnull(RestrictedHoliday_Remaining,0),YearSettingsId,FinancialYear from #TempLeaveDetails
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	select 
	Employee_Code_Id,
	Employee_Name,
	Designation,
	PolicyName,
	REPLACE(CONVERT(VARCHAR(20), FromDate,@dateFormat),' ','-'),
	REPLACE(CONVERT(VARCHAR(20), ToDate,@dateFormat),' ','-'),
	LeaveType_Name,
	Leave_Days,
	Leave_Days_Availed_Approved,
	Leave_Days_Availed_InProgress,
	Leave_Days_Remaining,
	CarryOver=isnull(CarryOver,0.0),
	Encashment=isnull(Encashment,0.0),
	yearsettingID,
	FinancialYear
	from #TempLeaveDetails_Final order by yearsettingID,Employee_Code_Id,LeaveType_Name
	drop table #TempLeaveDetails
	drop table #TempLeaveDetails_Final
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--	Modified By		:	Manjula.P., K.Gopinath
--	Modified On		:	30-Sep-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--	Descriptions	:	Selecting LOP with Leave type like LOP-CL, LOP-SL Mantis :0019151 
-- =============================================
--	Proc_TA_Rpt_LeaveSummaryDetails_Angler '01/01/2017','10/31/2017','','','','All','All',0,0,'SuperAdmin','','',0,0,'Both'
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @YearSettingID int
	select @YearSettingID =max(yearsettings_ID) from ta_tbl_yearsetting where yearsettings_ID<(select yearsettings_ID from ta_tbl_yearsetting where isActive=1)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	create table #TempLeaveDetails 
	(
	Employee_Id bigint,
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Id int,
	LeaveType_Name nvarchar(10),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1),
	LOP_Days decimal(18,1),
	LOP_Days_Availed_Approved decimal(18,1),
	LOP_Days_Availed_InProgress decimal(18,1),
	LOP_Days_Remaining decimal(18,1),
	RestrictedHoliday decimal(18,1),
	RestrictedHoliday_Availed_Approved decimal(18,1),
	RestrictedHoliday_Availed_InProgress decimal(18,1),
	RestrictedHoliday_Remaining decimal(18,1),
	YearSettingsId int
	)
    declare @sqlQuery varchar(8000)
    set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'insert into #TempLeaveDetails '
	set @sqlQuery = @sqlQuery + '(Employee_Id,Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,LeaveType_Id,LeaveType_Name, '
	set @sqlQuery = @sqlQuery + 'Leave_Days ,LOP_Days,RestrictedHoliday,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining, '
	set @sqlQuery = @sqlQuery + 'LOP_Days_Availed_Approved,LOP_Days_Availed_InProgress,LOP_Days_Remaining,RestrictedHoliday_Availed_Approved,RestrictedHoliday_Availed_InProgress,RestrictedHoliday_Remaining,YearSettingsId) '
	set @sqlQuery = @sqlQuery + 'select E.Employee_Id,E.Employee_Code_Id,isnull(E.Employee_FirstName,'''') + space(1) + isnull(E.Employee_lastName,''''),replace(TA_Tbl_Title.TitleName,''&amp;'',''&''),LP.PolicyName,Emp_LP.FromDate,Emp_LP.ToDate, '
	set @sqlQuery = @sqlQuery + 'LPD.LeaveType_Id,LT.LeaveType,Emp_LPD.No_Of_Days ,LPD.Max_LOP_Days,HS.Yearly_Maxdays as RestrictedHoliday, 0,	0,0,0,0,0,0,0,0,ys.YearSettings_Id '
	set @sqlQuery = @sqlQuery + 'from TA_Tbl_Employee E '
		If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=E.Employee_Code_Id '
		End
	set @sqlQuery = @sqlQuery + 'Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + 'Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id '
	set @sqlQuery = @sqlQuery + 'Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + 'Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + 'Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id '
   	set @sqlQuery = @sqlQuery + 'INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId '
	set @sqlQuery = @sqlQuery + 'INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID '
	set @sqlQuery = @sqlQuery + 'Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_Emp_LeavePolicy Emp_LP on Emp_LP.employeeId=E.Employee_Id '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id = Emp_LP.LeavePolicy_Id '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id = Emp_LP.YearSettingId '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=Emp_LP.LeavePolicy_Id '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id = LPD.LeaveType_Id  '
	set @sqlQuery = @sqlQuery + 'inner join TA_Tbl_Emp_LeavePolicyDetails Emp_LPD on Emp_LPD.Emp_LeavePolicyId = Emp_LP.Emp_LeavePolicyId '
	set @sqlQuery = @sqlQuery + 'and Emp_LPD.LeaveType_Id = LPD.LeaveType_Id '
	set @sqlQuery = @sqlQuery + 'left join TA_Tbl_HolidaySettings HS on HS.YearSettingId = YS.YearSettings_Id '
	--set @sqlQuery = @sqlQuery + 'inner join ta_tbl_emp_LeaveTypedetails empltd on empltd.employeeid = Emp_LP.EmployeeId and empltd.leavetypeid=lpd.leavetype_id  '
	set @sqlQuery = @sqlQuery + 'where E.IsDeleted =0 and E.Employee_Code_Id<>''18000000'' and E.Employee_Status = 1 '
	set @sqlQuery = @sqlQuery + 'and YS.YearSettings_Id='+@YearSettingID
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end		
	If Not (@EmpSwipeCard = '')  
		Begin  
		 Set @sqlQuery = @sqlQuery + 'And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
	if(@Gender<>'Both')
		begin
		   set @sqlQuery = @sqlQuery + ' and E.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		 set @sqlQuery = @sqlQuery + ' order by Employee_Id '
exec(@sqlQuery)
	update #TempLeaveDetails set Leave_Days=case when Carry_PrevYear<>0 then Leave_Days+Carry_PrevYear
	else Leave_Days end from #TempLeaveDetails 
	inner join TA_Tbl_YearClosure yc on #TempLeaveDetails.YearSettingsId=yc.Year_SettingID
	and #TempLeaveDetails.Employee_Id=yc.Employee_Id 
	update #TempLeaveDetails set Leave_Days_Availed_Approved =Leave_Days_Availed_Approved+ A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type='Leave' and LA.Status = 'Approved' and LA.isdeleted=0 and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id 
	and #TempLeaveDetails.LeaveType_id = A.LeaveType_id
	update #TempLeaveDetails set Leave_Days_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type='Leave' and LA.Status in ('Pending','Forwarded') and LA.isdeleted=0 and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id 
	and #TempLeaveDetails.LeaveType_id = A.LeaveType_id
	update #TempLeaveDetails set Leave_Days_Remaining = (Leave_Days - (Leave_Days_Availed_Approved + Leave_Days_Availed_InProgress))
	update #TempLeaveDetails set LOP_Days_Availed_Approved = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type='LOP' and LA.Status = 'Approved' and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set LOP_Days_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id and LA.isdeleted=0 
	where LA.type='LOP' and LA.Status in ('Pending','Forwarded') and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set LOP_Days_Remaining = (LOP_Days - (LOP_Days_Availed_Approved + LOP_Days_Availed_InProgress))
	update #TempLeaveDetails set RestrictedHoliday_Availed_Approved = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type='Restricted Holiday' and LA.Status = 'Approved' and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type='Restricted Holiday' and LA.Status in ('Pending','Forwarded') and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Remaining = (RestrictedHoliday - (RestrictedHoliday_Availed_Approved + RestrictedHoliday_Availed_InProgress))
	create table #TempLeaveDetails_Final 
	(
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Name nvarchar(20),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1))
	insert into #TempLeaveDetails_Final select Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining from #TempLeaveDetails
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,'LOP-'+#TempLeaveDetails.LeaveType_Name,isnull(LOP_Days,0),isnull(LOP_Days_Availed_Approved,0),isnull(LOP_Days_Availed_InProgress,0),isnull(LOP_Days_Remaining,0) 
	from #TempLeaveDetails where LOP_Days<>0.0
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select distinct Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,'Restricted Holiday',isnull(RestrictedHoliday,0),isnull(RestrictedHoliday_Availed_Approved,0),isnull(RestrictedHoliday_Availed_InProgress,0),
	isnull(RestrictedHoliday_Remaining,0) from #TempLeaveDetails
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	select 
	Employee_Code_Id,
	Employee_Name,
	Designation,
	PolicyName,
	REPLACE(CONVERT(VARCHAR(20), FromDate,@dateFormat),' ','-'),
	REPLACE(CONVERT(VARCHAR(20), ToDate,@dateFormat),' ','-'),
	LeaveType_Name,
	Leave_Days,
	Leave_Days_Availed_Approved,
	Leave_Days_Availed_InProgress,
	Leave_Days_Remaining
	from #TempLeaveDetails_Final order by Employee_Code_Id,LeaveType_Name
	drop table #TempLeaveDetails
	drop table #TempLeaveDetails_Final
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_Ta_rptAbsent '2022/04/01','2022/04/20','',0,'','0',0,0,'superadmin',0,'',0,0,'both',0,0,1,3

/*
exec Proc_Ta_rptAbsent @fromDat=N'01/Jun/2024',@ToDat=N'19/Oct/2024',@empId=N'',@shift=0,@EmployeeName=N'',
@LevelID=N'0',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',
@ParentId=0,@DesignationID=0,@Gender=N'Both',@session=N'0',@EmpAutoId=0,@ExportType=1,@ContinueAbsentDays=0

*/
CREATE PROCEDURE [dbo].[Proc_Ta_rptAbsent]
(
	@fromDat DATETIME,
	@ToDat DATETIME,
	@empId NVARCHAR(max),
	@shift INT,
	@EmployeeName NVARCHAR(max),
	@LevelID NVARCHAR(max),
	@employeeCategory INT,
	@employeeType INT,
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20),
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@session INT,
	@EmpAutoId bigint,
	@ExportType int,
	@ContinueAbsentDays int=null
)     
AS
BEGIN
	SET NOCOUNT ON;
	--return;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='SuperAdmin' and @isReportingto!=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	CREATE TABLE #EmpLevel(id int identity(1,1),EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempProcessedData(EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),
	InTime nVARCHAR(25),OutTime nVARCHAR(25),Attendance nVARCHAR(50),fnattendanceCode nVARCHAR(50),
	anattendanceCode nVARCHAR(50),Shift_Id INT)
	CREATE TABLE #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo NVARCHAR(20))      
	--Get current date time format.
	DECLARE @dateFormat as INT
	select  @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	--insert in Temporary table
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID  
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType 
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
	if(@empId is not null and @empId <> '')
	BEGIN                  
		INSERT INTO #EmployeeID SELECT * from SplitupEmployeeCode(@empId)
	END
	if(@EmployeeName is not null and @EmployeeName <> '')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
	end
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from 
	(
		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		from TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		Left Outer JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id
		Left Outer JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id
		WHERE emp.Isdeleted=0 
		and (ISNULL(@empId,'')= '' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeID))
		and (ISNULL(@EmployeeName,'')= '' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeName))
		and (@Gender='Both' or emp.Gender=@Gender)
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nVARCHAR(50)),102) and EL.LevelId is not null
	  
	INSERT INTO #TempEmployee SELECT Employee_ID,SwipeCardNo from TA_Tbl_Employee
	INNER JOIN #EmpLevel ON #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id 
	
	--select * From #c

	

declare @Count int=0, @loop int=1,@SQLStr nvarchar(MAX)=''
	create table #Emptest (
		EmployeeId nvarchar(20),
		LevelId int,
		Level1Name nvarchar(200),
		Level1Details nvarchar(200),
		Level2Name nvarchar(200),
		Level2Details nvarchar(200),
		Level3Name nvarchar(200),
		Level3Details nvarchar(200),
		Level4Name nvarchar(200),
		Level4Details nvarchar(200),
		Level5Name nvarchar(200),
		Level5Details nvarchar(200)
	)
	select @Count=count(*) from #EmpLevel
	while(@Count>=@loop)
		begin
			Set @SQLStr=''
			declare @EmpIDs nvarchar(20),@LoopLevelID bigint
			Select @EmpIDs=EMPLOYEE_CODE_ID,@LoopLevelID=LEVELID from #EmpLevel where id=@loop
			select @SQLStr=dbo.Func_TA_LoadSpace(@EmpIDs,@LoopLevelID,'#Emptest')
			execute(@SQLStr)
			Set @loop=@loop+1
		end
	
	--print @SQLStr


	--select * from #Emptest


	INSERT INTO #TempProcessedData 
	SELECT      TE.EmpAutoId,
	PD.Date,
	PD.Employee_Code_Id,
	PD.InTime,
	PD.OutTime,
	PD.Attendance,
	PD.fnattendanceCode,
	PD.anattendanceCode,
	PD.Shift_Id 
	from TA_Tbl_ProcessedData PD 
	INNER JOIN #TempEmployee TE ON TE.EmpSwipeCardNo=PD.Employee_Code_Id
	WHERE (PD.fnAttendanceCode = 'Absent' OR PD.AnAttendanceCode ='Absent' OR PD.fnAttendanceCode = 'LOP' OR PD.AnAttendanceCode ='LOP')          
	And (PD.Date >= @fromDat AND PD.Date <= @todat)
	and(isnull(@shift,0)=0 or PD.Shift_Id = @shift)
	and
	(
		(isnull(@session,0)=0 and (PD.anattendanceCode like 'absent%' or PD.fnattendancecode like 'absent%')) or 
		(@session=1 And PD.fnattendancecode like 'absent%')or 
		(@session=2 And PD.anattendanceCode like 'absent%') or
		(@session=3 and (PD.anattendanceCode like 'absent%' and PD.fnattendancecode like 'absent%'))
	)
	
	UPDATE #TempProcesseddata SET  fnAttendanceCode=fnAttendanceCode + ' (L-'+ L.Status+')'  from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
	WHERE L.isdeleted=0 and L.Leave_SessionFrom='First Half' and L.Status <> 'Approved'
	
	UPDATE #TempProcesseddata SET fnAttendanceCode=fnAttendanceCode + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
	WHERE PER.isdeleted=0 and PER.Permission_status<> 'Approved'
	
	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + ' (L-'+ L.Status+')'  from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
	WHERE L.isdeleted=0 and L.Leave_SessionTo='Second Half' and L.Status <> 'Approved'
	
	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
	WHERE PER.isdeleted=0 and PER.Permission_status<> 'Approved'
	
	DECLARE @sqlQuery as NVARCHAR(max)
	SET @sqlQuery = ''
	if(@ExportType=1)
	begin
		SET @sqlQuery = @sqlQuery + ' SELECT E.Employee_Code_Id, 
		isnull(E.Employee_FirstName,'''') + SPACE(1)+ 
		isnull(E.Employee_LastName,'''') AS ''EmpName''
		,Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,
		Level4Name,Level4Details,Level5Name,Level5Details,
		replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,
		replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as ''Name'',E.Gender,case when '+CONVERT(varchar,@dateFormat) +'=106 then
											REPLACE(CONVERT(VARCHAR, PD.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
											else CONVERT(VARCHAR, PD.Date, '+CONVERT(varchar,@dateFormat)+') end  AS Date, ta_tbl_shift.Shift_ShortName,PD.fnAttendanceCode as ''FirstSession'', PD.anAttendanceCode as ''SecondSession'',pd.date '
	end
	else
	begin
		SET @sqlQuery = @sqlQuery + ' SELECT PD.fnAttendanceCode as FirstSession, PD.anAttendanceCode as SecondSession,#EmpLevel.LevelID, #EmpDesignation.DesignationId, E.Employee_Code_Id, case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, PD.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, PD.Date, '+CONVERT(varchar,@dateFormat)+') end  AS Date, '
		SET @sqlQuery = @sqlQuery + ' isnull(E.Employee_FirstName,'''') + SPACE(1)' 
		SET @sqlQuery = @sqlQuery + ' + isnull(E.Employee_LastName,'''') AS empname, PD.Attendance,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,' 
		SET @sqlQuery = @sqlQuery + '      replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, ta_tbl_shift.Shift_ShortName,E.Gender,PD.Date format '
	end
	
	SET @sqlQuery = @sqlQuery + ' FROM #TempProcessedData PD INNER JOIN'
	SET @sqlQuery = @sqlQuery + ' TA_Tbl_Employee E ON PD.EmpAutoId = E.Employee_ID'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = PD.Shift_ID  '    
	--SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id'
	SET @sqlQuery = @sqlQuery + ' inner Join #Emptest ELL on ELL.EmployeeId = E.Employee_Code_Id'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' WHERE 
								  (E.Isdeleted = 0) AND 
								  (E.Report_Exclude = 0) AND 
								  (
										(E.Employee_Status = 1)
										or
										(E.employee_status=0 and convert(nVARCHAR(11),E.InActiveDate,102)>=convert(nVARCHAR(11),PD.Date,102))
								  )
								  --While clicking the dashboard data, its showing wrong data in popu up screen. due to this i have commented as per testing team suggestion.
								  --16-11-2016 13.37 bug id is 0035540
								  and 
								  cast(convert(NVARCHAR, PD.Date, 111) + '' '' + convert(NVARCHAR,cast(Shift_StartTime as DATETIME),114) as DATETIME) <= getdate() '
	if(@UserGroupName<>'SuperAdmin')
	BEGIN
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	END
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	SET @sqlQuery = @sqlQuery + ' order by PD.Employee_Code_Id,PD.Date'
	
	--exec(@sqlQuery)

	if(@ExportType=2)
	begin
		create table #AbsentTable(FirstSession nvarchar(100),SecondSession nvarchar(100),LevelID int,DesignationID int,Employee_Code_Id nvarchar(50),Date nvarchar(50),empname nvarchar(100),Attendance nvarchar(50),TitleName nvarchar(100),name nvarchar(150),Shift_ShortName nvarchar(10),Gender nvarchar(10),format datetime)
		insert into #AbsentTable exec(@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		insert into #TempLevelName select distinct name from #AbsentTable
		declare @cou int
		select @cou=COUNT(distinct name) from #AbsentTable
		declare @i int
		set @i=1
		declare @SQLString nvarchar(Max)
		set @SQLString=''
		while @i<=@cou
		begin
			set @SQLString = @SQLString + cast((select Name from #TempLevelName where ID=@i) as nvarchar(MAX)) + '$' + cast((select COUNT(*) from #AbsentTable where name=(select Name from #TempLevelName where ID=@i)) as nvarchar(MAX)) +'%'
			set @i=@i+1
		end
		select @SQLString as ReturnString
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempDate select distinct CAST(format as datetime),Date from #AbsentTable order by format
		declare @couLevel int
		declare @couDate int
		select @couLevel=COUNT(*) from #TempLevelName
		select @couDate=COUNT(*) from #TempDate
		declare @j int
		set @j=1
		declare @k int
		set @k=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''
		while @j<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@j)
			set @SQLString1 = @SQLString1 + @Levelstr + '@'
			while @k<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #AbsentTable where name=@Levelstr and Date=(select date from #TempDate where ID=@k))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
				end
				set @k=@k+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + '#'
			set @k=1
			set @j=@j+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
	END
	ELSE
	BEGIN
		--if(@ExportType=1)
		--begin
		--Create table #TempFinalAbsent(AutoID int identity(1,1),Employee_Code_Id varchar(20),EmpName varchar(250),TitleName varchar(250),Name varchar(250),
		--Gender varchar(10),Date varchar(20),Shift_ShortName varchar(4),FirstSession varchar(100),SecondSession varchar(100),shiftDate datetime)
		--Insert into #TempFinalAbsent exec(@sqlQuery)		
		--end
		--if(@ContinueAbsentDays='' or @ContinueAbsentDays=0)
		--begin
		--	set @ContinueAbsentDays=0
		--end
		--if(@ContinueAbsentDays>0 and @ExportType=1)
		--begin
			
		--	select TFA.* from #TempFinalAbsent TFA
		--	inner join
		--	(
		--		select sub1.Employee_Code_Id,mindate=min(sub1.shiftDate),maxdate=MAX(sub1.shiftDate)
		--		--,dates=DATEDIFF(D,min(date),MAX(date))+1 
		--		from 
		--		(
		--			select Employee_Code_Id ,shiftDate,
		--			diff=DATEDIFF(d,row_number()over(partition by employee_code_id order by employee_code_id,shiftDate),shiftDate)
		--			from #TempFinalAbsent
		--		) as sub1 group by Employee_Code_Id,diff having((DATEDIFF(D,min(shiftDate),MAX(shiftDate))+1)>=@ContinueAbsentDays)
		--	)as sub2 on TFA.Employee_Code_Id=sub2.Employee_Code_Id
		--	where TFA.shiftDate>=sub2.mindate and TFA.shiftDate<=sub2.maxdate
		--	order by TFA.Employee_Code_Id
		--END
		--ELSE
		--BEGIN
			exec(@sqlQuery)
		--END
	end
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory 
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee      
END















--ALTER PROCEDURE [dbo].[Proc_Ta_rptAbsent]
--(
--	@fromDat DATETIME,
--	@ToDat DATETIME,
--	@empId NVARCHAR(max),
--	@shift INT,
--	@EmployeeName NVARCHAR(max),
--	@LevelID NVARCHAR(max),
--	@employeeCategory INT,
--	@employeeType INT,
--	@UserGroupName NVARCHAR(250),
--	@GradeLevel NVARCHAR(20),
--	@EmpSwipeCard NVARCHAR(20),
--	@ParentId INT,
--	@DesignationID INT,
--	@Gender NVARCHAR(10),
--	@session INT,
--	@EmpAutoId bigint,
--	@ExportType int,
--	@ContinueAbsentDays int=null
--)     
--AS
--BEGIN
--	SET NOCOUNT ON;
--	--return;
--	declare @isReportingto as int
--	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
--	create table #EmployeeIds(EmpAutoId int)
--	if(@UserGroupName!='SuperAdmin' and @isReportingto!=1)
--	begin
--		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
--		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--	end
--	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
--	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
--	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
--	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
--	CREATE TABLE #LevelRights(LevelId INT)
--	CREATE TABLE #TempProcessedData(EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime nVARCHAR(25),OutTime nVARCHAR(25),Attendance nVARCHAR(50),fnattendanceCode nVARCHAR(50),anattendanceCode nVARCHAR(50),Shift_Id INT)
--	CREATE TABLE #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo NVARCHAR(20))      
--	--Get current date time format.
--	DECLARE @dateFormat as INT
--	select  @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
--	--insert in Temporary table
--	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID  
--	INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType 
--	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory
--	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
--	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
--	if(@empId is not null and @empId <> '')
--	BEGIN                  
--		INSERT INTO #EmployeeID SELECT * from SplitupEmployeeCode(@empId)
--	END
--	if(@EmployeeName is not null and @EmployeeName <> '')
--	BEGIN
--		INSERT INTO #EmployeeName SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
--	end
--	INSERT INTO #EmpLevel 
--	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
--	from 
--	(
--		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
--		from TA_Tbl_EmployeeLevel el
--		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
--		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
--		Left Outer JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id
--		Left Outer JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id
--		WHERE emp.Isdeleted=0 
--		and (ISNULL(@empId,'')= '' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeID))
--		and (ISNULL(@EmployeeName,'')= '' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeName))
--		and (@Gender='Both' or emp.Gender=@Gender)
--		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
--	) ELevel
--	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
--	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
--	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nVARCHAR(50)),102) and EL.LevelId is not null
	  
--	INSERT INTO #TempEmployee SELECT Employee_ID,SwipeCardNo from TA_Tbl_Employee
--	INNER JOIN #EmpLevel ON #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id 
	
--	INSERT INTO #TempProcessedData 
--	SELECT      TE.EmpAutoId,
--	PD.Date,
--	PD.Employee_Code_Id,
--	PD.InTime,
--	PD.OutTime,
--	PD.Attendance,
--	PD.fnattendanceCode,
--	PD.anattendanceCode,
--	PD.Shift_Id 
--	from TA_Tbl_ProcessedData PD 
--	INNER JOIN #TempEmployee TE ON TE.EmpSwipeCardNo=PD.Employee_Code_Id
--	WHERE (PD.fnAttendanceCode = 'Absent' OR PD.AnAttendanceCode ='Absent' OR PD.fnAttendanceCode = 'LOP' OR PD.AnAttendanceCode ='LOP')          
--	And (PD.Date >= @fromDat AND PD.Date <= @todat)
--	and(isnull(@shift,0)=0 or PD.Shift_Id = @shift)
--	and
--	(
--		(isnull(@session,0)=0 and (PD.anattendanceCode like 'absent%' or PD.fnattendancecode like 'absent%')) or 
--		(@session=1 And PD.fnattendancecode like 'absent%')or 
--		(@session=2 And PD.anattendanceCode like 'absent%') or
--		(@session=3 and (PD.anattendanceCode like 'absent%' and PD.fnattendancecode like 'absent%'))
--	)
	
--	UPDATE #TempProcesseddata SET  fnAttendanceCode=fnAttendanceCode + ' (L-'+ L.Status+')'  from #TempProcesseddata P
--	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
--	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
--	WHERE L.isdeleted=0 and L.Leave_SessionFrom='First Half' and L.Status <> 'Approved'
	
--	UPDATE #TempProcesseddata SET fnAttendanceCode=fnAttendanceCode + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
--	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
--	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
--	WHERE PER.isdeleted=0 and PER.Permission_status<> 'Approved'
	
--	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + ' (L-'+ L.Status+')'  from #TempProcesseddata P
--	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
--	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
--	WHERE L.isdeleted=0 and L.Leave_SessionTo='Second Half' and L.Status <> 'Approved'
	
--	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
--	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
--	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
--	WHERE PER.isdeleted=0 and PER.Permission_status<> 'Approved'
	
--	DECLARE @sqlQuery as NVARCHAR(max)
--	SET @sqlQuery = ''
--	if(@ExportType=1)
--	begin
--		SET @sqlQuery = @sqlQuery + ' SELECT E.Employee_Code_Id, 
--		isnull(E.Employee_FirstName,'''') + SPACE(1)+ 
--		isnull(E.Employee_LastName,'''') AS ''EmpName'',
--		replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,
--		replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as ''Name'',E.Gender,case when '+CONVERT(varchar,@dateFormat) +'=106 then
--											REPLACE(CONVERT(VARCHAR, PD.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--											else CONVERT(VARCHAR, PD.Date, '+CONVERT(varchar,@dateFormat)+') end  AS Date, ta_tbl_shift.Shift_ShortName,PD.fnAttendanceCode as ''FirstSession'', PD.anAttendanceCode as ''SecondSession'',pd.date '
--	end
--	else
--	begin
--		SET @sqlQuery = @sqlQuery + ' SELECT PD.fnAttendanceCode as FirstSession, PD.anAttendanceCode as SecondSession,#EmpLevel.LevelID, #EmpDesignation.DesignationId, E.Employee_Code_Id, case when '+CONVERT(varchar,@dateFormat) +'=106 then
--										REPLACE(CONVERT(VARCHAR, PD.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--										else CONVERT(VARCHAR, PD.Date, '+CONVERT(varchar,@dateFormat)+') end  AS Date, '
--		SET @sqlQuery = @sqlQuery + ' isnull(E.Employee_FirstName,'''') + SPACE(1)' 
--		SET @sqlQuery = @sqlQuery + ' + isnull(E.Employee_LastName,'''') AS empname, PD.Attendance,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,' 
--		SET @sqlQuery = @sqlQuery + '      replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, ta_tbl_shift.Shift_ShortName,E.Gender,PD.Date format '
--	end
	
--	SET @sqlQuery = @sqlQuery + ' FROM #TempProcessedData PD INNER JOIN'
--	SET @sqlQuery = @sqlQuery + ' TA_Tbl_Employee E ON PD.EmpAutoId = E.Employee_ID'
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id '
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id '
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = PD.Shift_ID  '    
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id '
--	SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id '
--	SET @sqlQuery = @sqlQuery + ' WHERE 
--								  (E.Isdeleted = 0) AND 
--								  (E.Report_Exclude = 0) AND 
--								  (
--										(E.Employee_Status = 1)
--										or
--										(E.employee_status=0 and convert(nVARCHAR(11),E.InActiveDate,102)>=convert(nVARCHAR(11),PD.Date,102))
--								  )
--								  --While clicking the dashboard data, its showing wrong data in popu up screen. due to this i have commented as per testing team suggestion.
--								  --16-11-2016 13.37 bug id is 0035540
--								  and 
--								  cast(convert(NVARCHAR, PD.Date, 111) + '' '' + convert(NVARCHAR,cast(Shift_StartTime as DATETIME),114) as DATETIME) <= getdate() '
--	if(@UserGroupName<>'SuperAdmin')
--	BEGIN
--		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
--	END
--	if(@isReportingto > 0)
--	BEGIN
--		set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
--	END
--	SET @sqlQuery = @sqlQuery + ' order by PD.Employee_Code_Id,PD.Date'
	
--	if(@ExportType=2)
--	begin
--		create table #AbsentTable(FirstSession nvarchar(100),SecondSession nvarchar(100),LevelID int,DesignationID int,Employee_Code_Id nvarchar(50),Date nvarchar(50),empname nvarchar(100),Attendance nvarchar(50),TitleName nvarchar(100),name nvarchar(150),Shift_ShortName nvarchar(10),Gender nvarchar(10),format datetime)
--		insert into #AbsentTable exec(@sqlQuery)
--		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
--		insert into #TempLevelName select distinct name from #AbsentTable
--		declare @cou int
--		select @cou=COUNT(distinct name) from #AbsentTable
--		declare @i int
--		set @i=1
--		declare @SQLString nvarchar(Max)
--		set @SQLString=''
--		while @i<=@cou
--		begin
--			set @SQLString = @SQLString + cast((select Name from #TempLevelName where ID=@i) as nvarchar(MAX)) + '$' + cast((select COUNT(*) from #AbsentTable where name=(select Name from #TempLevelName where ID=@i)) as nvarchar(MAX)) +'%'
--			set @i=@i+1
--		end
--		select @SQLString as ReturnString
--		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
--		insert into #TempDate select distinct CAST(format as datetime),Date from #AbsentTable order by format
--		declare @couLevel int
--		declare @couDate int
--		select @couLevel=COUNT(*) from #TempLevelName
--		select @couDate=COUNT(*) from #TempDate
--		declare @j int
--		set @j=1
--		declare @k int
--		set @k=1
--		declare @SQLString1 nvarchar(Max)
--		set @SQLString1=''
--		while @j<=@couLevel
--		begin
--			declare @Levelstr nvarchar(100)
--			set @Levelstr =(select Name from #TempLevelName where ID=@j)
--			set @SQLString1 = @SQLString1 + @Levelstr + '@'
--			while @k<=@couDate
--			begin
--				declare @RowCount int
--				set @RowCount=(select COUNT(*) from #AbsentTable where name=@Levelstr and Date=(select date from #TempDate where ID=@k))
--				if(@RowCount!=0)
--				begin
--					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
--				end
--				else
--				begin
--					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
--				end
--				set @k=@k+1
--			end
--			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
--			set @SQLString1 = @SQLString1 + '#'
--			set @k=1
--			set @j=@j+1
--		end
--		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
--		select @SQLString1 as 'Value'
--	END
--	ELSE
--	BEGIN
--		if(@ExportType=1)
--		begin
--		Create table #TempFinalAbsent(AutoID int identity(1,1),Employee_Code_Id varchar(20),EmpName varchar(250),TitleName varchar(250),Name varchar(250),
--		Gender varchar(10),Date varchar(20),Shift_ShortName varchar(4),FirstSession varchar(100),SecondSession varchar(100),shiftDate datetime)
--		Insert into #TempFinalAbsent exec(@sqlQuery)		
--		end
--		if(@ContinueAbsentDays='' or @ContinueAbsentDays=0)
--		begin
--			set @ContinueAbsentDays=0
--		end
--		if(@ContinueAbsentDays>0 and @ExportType=1)
--		begin
			
--			select TFA.* from #TempFinalAbsent TFA
--			inner join
--			(
--				select sub1.Employee_Code_Id,mindate=min(sub1.shiftDate),maxdate=MAX(sub1.shiftDate)
--				--,dates=DATEDIFF(D,min(date),MAX(date))+1 
--				from 
--				(
--					select Employee_Code_Id ,shiftDate,
--					diff=DATEDIFF(d,row_number()over(partition by employee_code_id order by employee_code_id,shiftDate),shiftDate)
--					from #TempFinalAbsent
--				) as sub1 group by Employee_Code_Id,diff having((DATEDIFF(D,min(shiftDate),MAX(shiftDate))+1)>=@ContinueAbsentDays)
--			)as sub2 on TFA.Employee_Code_Id=sub2.Employee_Code_Id
--			where TFA.shiftDate>=sub2.mindate and TFA.shiftDate<=sub2.maxdate
--			order by TFA.Employee_Code_Id
--		END
--		ELSE
--		BEGIN
--			exec(@sqlQuery)
--		END
--	end
--	--Remove the temporary tables here 
--	drop table #EmpLevel
--	drop table #EmpDesignation
--	drop table #EmpType
--	drop table #EmpCategory 
--	drop table #LevelRights
--	drop table #TempProcessedData
--	drop table #TempEmployee      
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent_Email]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
 Proc_Ta_rptAbsent '2014-07-07','2014-07-07','',0,'','',0,0,'SuperAdmin',0,'',0
*/
CREATE  PROCEDURE [dbo].[Proc_Ta_rptAbsent_Email]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@DesignationID int,
	@Gender varchar(10),
	@ParentID bigint		
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
create table #LevelRights(LevelId int)
if(@ParentId='124')
Begin
insert into  #LevelRights values (124)
insert into  #LevelRights values (125)
insert into  #LevelRights values (129)
insert into  #LevelRights values (131)
insert into  #LevelRights values (130) 
End
--Employee Level Indexes
Else
Begin
insert into  #LevelRights values (107)
insert into  #LevelRights values (123)
insert into  #LevelRights values (108)
insert into  #LevelRights values (109)
insert into  #LevelRights values (110)
insert into  #LevelRights values (111)
insert into  #LevelRights values (112)
insert into  #LevelRights values (113)
insert into  #LevelRights values (114)
insert into  #LevelRights values (115)
end
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
--create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
create table #TempProcesseddata(FirstSession varchar(100),SecondSession varchar(100),LevelID int,DesignationId int,Employee_Code_Id varchar(25),
date Datetime,empname varchar(150),Attendance varchar(25),TitleName varchar(50),name varchar(150),Shift_ShortName varchar(50),Gender varchar(20))
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''		
		set @sqlQuery = @sqlQuery + 'SELECT TA_Tbl_ProcessedData.fnAttendanceCode as FirstSession,TA_Tbl_ProcessedData.anAttendanceCode as SecondSession,   TA_Tbl_EmployeeLevel.LevelID, TA_Tbl_EmployeeDesignation.DesignationId, TA_Tbl_Employee.Employee_Code_Id,'
		set @sqlQuery = @sqlQuery + ' TA_Tbl_ProcessedData.Date AS date, isnull(TA_Tbl_Employee.Employee_FirstName,'''') + SPACE(1)' 
		set @sqlQuery = @sqlQuery + ' + isnull(TA_Tbl_Employee.Employee_LastName,'''') AS empname, TA_Tbl_ProcessedData.Attendance, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName ,' 
		set @sqlQuery = @sqlQuery + ' replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, ta_tbl_shift.Shift_ShortName, TA_Tbl_Employee.Gender'
		set @sqlQuery = @sqlQuery + ' FROM TA_Tbl_ProcessedData INNER JOIN'
		set @sqlQuery = @sqlQuery + ' TA_Tbl_Employee ON TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
		set @sqlQuery = @sqlQuery + ' TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID  ' 	
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId '
		set @sqlQuery = @sqlQuery + ' WHERE (TA_Tbl_ProcessedData.fnAttendanceCode = ''Absent'' OR TA_Tbl_ProcessedData.AnAttendanceCode =''Absent'') AND (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)'		
        --set @sqlQuery = @sqlQuery + ' or (TA_Tbl_ProcessedData.fnAttendanceCode = ''LOP'' OR TA_Tbl_ProcessedData.AnAttendanceCode =''LOP'')'
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
		set @sqlQuery = @sqlQuery + ' AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 
		set @sqlQuery = @sqlQuery + ' AND (TA_Tbl_ProcessedData.Intime is null and TA_Tbl_ProcessedData.Outtime is null) and cast(convert(varchar, TA_Tbl_ProcessedData.Date, 111) + '' '' +  convert(varchar,cast(Shift_StartTime as datetime),114) as datetime) <= getdate() '
		if(@UserGroupName<>'SuperAdmin')
		begin
			--if(@EmpAutoId<>0)
			--	BEGIN
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		--+ ' AND (ta_tbl_Employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or ta_tbl_Employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''' or ta_tbl_Employee.Employee_Id=''' + cast(@EmpAutoId as varchar(30)) +''')'
			--	END
			--else
			--	 BEGIN
			--		SET @sqlQuery = @sqlQuery + ' AND (TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  + ' or ta_tbl_Employee.Employee_code_Id=''' + isnull(cast(@empId as varchar(50)),'') +''')'
			--	 END 
			--SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  + ' AND (ta_tbl_Employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or ta_tbl_Employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''' or ta_tbl_Employee.Employee_Id=''' + cast(@EmpAutoId as varchar(30)) +''')'
		end
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  ' And  Ta_Tbl_ProcessedData.Shift_Id = ' +  cast(@shift  as nvarchar(20))  
			end
		if not(@EmployeeName='')
			begin
				set @sqlQuery = @sqlQuery + 'and (TA_Tbl_Employee.Employee_FirstName + isnull(TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
			end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End
		if not (@empId='')
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
			end
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryId = ' +cast(@employeeCategory as nvarchar(8))
			end
		if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		if(@DesignationID<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' +cast(@employeeType as nvarchar(8))
			end		
		--if(@EmpAutoId = 0)
		--BEGIN
		--	if not(@LevelID='' or @LevelID='0')
		--		begin
		--			set @sqlQuery = @sqlQuery + ' and (#EmpLevel.LevelId IN (' + @LevelId + '))' 
		--		end	
		--END
		if(@EmpAutoId > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END	
		set @sqlQuery = @sqlQuery + ' order by TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date'
	insert into #TempProcesseddata 
		exec(@sqlQuery)
		--select * from #TempProcesseddata
update #TempProcesseddata set FirstSession=FirstSession + ' (L-'+ L.Status+')'  from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_leaveApplication L on L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
where L.isdeleted=0 and L.Leave_SessionFrom='First Half' and L.Status <> 'Approved'
update #TempProcesseddata set FirstSession=FirstSession + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_permission PER on PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
where PER.isdeleted=0 and PER.Permission_status<> 'Approved'
update #TempProcesseddata set SecondSession=SecondSession + ' (L-'+ L.Status+')'  from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_leaveApplication L on L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
where L.isdeleted=0 and L.Leave_SessionTo='Second Half' and L.Status <> 'Approved'
update #TempProcesseddata set SecondSession=SecondSession + ' (P-'+PER.Permission_status+')' from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_permission PER on PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
where PER.isdeleted=0 and PER.Permission_status<> 'Approved'
select * from #TempProcesseddata
--select * from ta_tbl_permission
--select * from ta_tbl_leaveApplication where Leave_FromDate='2011-04-13' between '04/04/2011' and '08/30/2011'
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
drop table #TempProcesseddata 
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsentCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-2007
-- Description:	Absentess reports
-- Modified by :K.Gopinath
-- Modified on : 18-Dec-2013
-- Description : SQL Query Optimization
-- [Proc_Ta_rptAbsentCount] '04/04/2007','05/30/2009','',0,'','',0,0,'SuperAdmin',3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_rptAbsentCount]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
	/****** Object:  Index [IDX_Employee_Id] IDX_Employee_Code_Id IDX_SwipeCardNo    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Id] ON [dbo].[ta_tbl_employee] 
(
	[Employee_Id] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[ta_tbl_employee] 
(
	[Employee_Code_Id] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[ta_tbl_employee] 
(
	[SwipeCardNo] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
Declare @sqlCommon nvarchar(4000)
set @sqlEmpLevel=
	'insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),'''')'
Execute(@sqlEmpLevel)
	--Employee Designation insert in Temporary table
Declare @sqlEmpDesi nvarchar(4000)
set @sqlEmpDesi=
'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),'''','''')'
Execute(@sqlEmpDesi)
--Employee Type insert in Temporary table
Declare @sqlEmpType nvarchar(4000)
set @sqlEmpType=
'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),'''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
Execute(@sqlEmpType)
--Employee Category insert in Temporary table
Declare @sqlEmpCategory nvarchar(4000)
set @sqlEmpCategory=
'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),'''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
Execute(@sqlEmpCategory)
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as nvarchar(4000)
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT count(*) FROM TA_Tbl_ProcessedData INNER JOIN'
		set @sqlQuery = @sqlQuery + ' TA_Tbl_Employee ON TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
		set @sqlQuery = @sqlQuery + ' TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID  ' 	
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' WHERE (TA_Tbl_ProcessedData.fnAttendanceCode = ''Absent'' OR TA_Tbl_ProcessedData.AnAttendanceCode =''Absent'' OR TA_Tbl_ProcessedData.fnAttendanceCode = ''LOP'' OR TA_Tbl_ProcessedData.AnAttendanceCode =''LOP'') AND (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)'		
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
		set @sqlQuery = @sqlQuery + ' AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  ' And  Ta_Tbl_ProcessedData.Shift_Id = ' +  cast(@shift  as nvarchar(20))  
			end
		if not(@EmployeeName='')
			begin
				set @sqlQuery = @sqlQuery + 'and (TA_Tbl_Employee.Employee_FirstName + '' '' +  isnull(TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' +cast(@employeeType as nvarchar(8))
			end		
		if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlQuery = @sqlQuery + ' and (#EmpLevel.LevelId IN (' + @LevelId + '))' 
			end			
		set @sqlQuery = @sqlQuery + ' order by TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date'
		exec(@sqlQuery)
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop index ta_tbl_employee.IDX_Employee_Id
drop index ta_tbl_employee.IDX_Employee_Code_Id 
drop index ta_tbl_employee.IDX_SwipeCardNo 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAbsenteesDetail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_RptAbsenteesDetail]
	(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @LeaveType VarChar(50), @EmployeeName varchar(50))
AS
BEGIN
	Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 AbsDate varchar(50)
	)
	Declare @AutoID as int
	Declare @totRec as int
	Declare @TestDate as Varchar(50)
	Set @TestDate = @FromDate
	Set @AutoID=0
	While (cast(@TestDate as datetime) <= cast(@ToDate as DateTime))
	Begin
	set @totRec = 0
	Select @totRec=Count(*)  from TA_Tbl_Holiday where Convert (varchar,Holiday_FromDate,101) >= @TestDate And Convert 
(varchar,Holiday_ToDate,101) <= @TestDate and Isdeleted = 1
	if @totRec = 0
	Begin
	Declare @SelectSQL As Varchar(4000)
	Set @SelectSQL = ' '
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName 
as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    Set @SelectSQL = @SelectSQL + 'D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, '
    Set @SelectSQL = @SelectSQL + 'C.Company_Logo AS Logo, B.Branch_Name As Region,''' +  @TestDate + ''' FROM 
TA_Tbl_Employee ED INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN TA_Tbl_CompanyDetails C ON 
ED.Company_Id = C.Company_Id  INNER JOIN TA_Tbl_Region R ON ED.Region_Id = R.Region_Id inner join TA_Tbl_Branch B on 
B.Branch_Id = ED.Branch_Id Where '
	Set @SelectSQL = @SelectSQL + 'ED.IsDeleted = ''1'' '
	If Not (@EmployeeId = '' Or @EmployeeId = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @EmployeeId + ''' '
	End
	If Not (@CompanyID = '' Or @CompanyID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Company_Id = ''' + @CompanyID + ''' '
	End
	If Not (@RegionID = '' Or @RegionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Region_Id = ''' + @RegionID + ''' '
	End
	If Not (@BranchID = '' Or @BranchID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Branch_Id = ''' + @BranchID + ''' '
	End
	If Not (@DeptID = '' Or @DeptID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Dept_Id = ''' + @DeptID + ''' '
	End
	If Not (@SectionID = '' Or @SectionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Section_Id = ''' + @SectionID + ''' '
	End
--	If Not (@LeaveType = '' Or @LeaveType = '0')
--	Begin
--	Set @SelectSQL = @SelectSQL + 'And LA.LeaveType_id = ''' + @LeaveType + ''' '	
--	end
	Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo Not In (SELECT Clk_EmpId FROM TA_Tbl_ClockDetails Where Convert 
(varchar,Clk_InDate,101) = ''' + @TestDate + ''') '	
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region, AbsDate)		
	Exec (@SelectSQL)
	End	
	Set @TestDate = Convert (varchar,Dateadd(dd,1,@TestDate),101)
	End
	--Return
	Set @EmployeeName = @EmployeeName + '%'
	Select * From #TempReportTable where EmployeeName like @EmployeeName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllException]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptAllException '787,758','0,1','2017/02/01','2022/02/28','Manikandan ,',0,0,0,'SuperAdmin','0','',0,0,'Both','00:40',1
CREATE PROCEDURE [dbo].[Proc_TA_RptAllException]  
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@MINExceptionHOURS AS VARCHAR(6),
	@EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@MINExceptionHOURS,0,CHARINDEX(':',@MINExceptionHOURS))*60 + SUBSTRING(@MINExceptionHOURS,CHARINDEX(':',@MINExceptionHOURS)+1,2)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		EarlyOut nvarchar(10),
		EarlyOutMins float,
		EarlyInMins int,
		EarlyInHrs varchar(10),
		HrsExtra nvarchar(10),
		ExtraMins int
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	insert into #TempEmployee 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee emp
	inner join #EmpLevel on #EmpLevel.EmployeeId=emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 
	left join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id 
	left join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
	where SwipeCardNo is not null and emp.Isdeleted=0  and emp.report_exclude=0
	and (isnull(@EmployeeID,'')='' or emp.Employee_Code_Id in (select * from #EmployeeID))
	and (isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in (select * from #EmployeeName))
	and (isnull(@Gender,'Both')='Both' or emp.Gender=@Gender)
	
	insert into #TempProcessedData select	TE.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.Process_Rec_ID,
											PD.LateIn,
											PD.LateInMins,
											PD.EarlyOut,
											PD.EarlyOutMins,
											PD.EarlyInMins,
											PD.EarlyInHrs,
											PD.LateExitHours,
											PD.lateExitMins 
	from TA_Tbl_ProcessedData PD inner join #TempEmployee TE on TE.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join ta_tbl_shift S on S.Shift_Id=PD.Shift_Id
	where (PD.Date >= @FromDate AND PD.Date <= @ToDate) and 	
	(
		(isnull(LateInMins,0) > 0) or 
		(isnull(PD.EarlyOutMins,0) > 0) or 
		(EarlyInMins!=0 and (cast(S.Shift_StartTime as datetime) > cast(PD.InTime AS datetime)) AND PD.LateInMins=0 and PD.EarlyEntry=1) or 
		(lateexit=1 and PD.OutTime <> '0' and PD.OutTime <> '00:00:00' and PD.OutTime <> '00:00' and PD.OutTime is not null and PD.OutTime <>'''' and PD.lateExitMins > 0)
	) 
	and processflag=1 and(isnull(@shift,0)=0 or PD.shift_id=@shift)
	and (isnull(@MINExceptionHOURS,'00:00')='00:00' or PD.LateInMins >=@TOTALExceptionMIN or PD.EarlyOutMins >=@TOTALExceptionMIN or PD.EarlyInMins >=@TOTALExceptionMIN or PD.lateExitMins >=0)
	
	Set @EmployeeName = @EmployeeName 
	SELECT PD.Process_Rec_ID,
	ED.Employee_Code_Id AS CardNo,
	ED.Employee_FirstName + ' ' + isnull(ED.Employee_LastName,'') AS 'EmployeeName',  
	replace(T.TitleName,'&amp;','&')  AS Designation,  
	replace(L.name,'&amp;','&')  AS [LevelName],
	sh.Shift_StartTime,sh.Shift_EndTime,replace(sh.shift_shortName,'&amp;','&') as shift_shortName,    
	case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, Date,@dateFormat) 
	end AS Date, 	
	case	when @TimeFormat='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114),0,6)
			else	case	when len(SUBSTRING(intime,0,charindex(':',intime)))=1 then '0'+intime
							else InTime 
					end
	end InTime,
	case	when @TimeFormat='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114),0,6) 
			else	case	when len(SUBSTRING(OutTime,0,charindex(':',OutTime)))=1 then '0'+ OutTime
							else OutTime 
					end 
	end OutTime,
	LateIn as LateBy,
	LateInMins,
	EarlyOut as EarlyOutBy,
	EarlyOutMins,
	EarlyInHrs as EarlyInBy,
	EarlyInMins,
	isnull(hrsExtra,'00:00') as LateExitBy,
	ExtraMins as lateExitMins,
	ED.Gender,
	Date as format
	FROM TA_Tbl_Employee ED 
	Inner join #EmpLevel Lev on Lev.employeeid=ED.Employee_Id 
	INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id
	Inner join #EmpDesignation  EDesig on EDesig.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID
	Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id
	INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId
	INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id
	Where 1=1
	and (@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	and (isnull(@isReportingto,0)=0 or ED.Employee_ID IN (select * from #EmployeeIds))
	AND 
	(
		(ED.employee_status=1) or 
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),Date,102))
	)
	order by CardNo,format
	--remove the temporary tables  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
 End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllSwipe]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_RptAllSwipe]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @TerminalID varchar(50), @EmployeeName varchar(50))
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Set @EmployeeName = @EmployeeName + '%'
	Set @SelectSQL = ' '  
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName 
as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    Set @SelectSQL = @SelectSQL + 'D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, '
    Set @SelectSQL = @SelectSQL + 'C.Company_Logo AS Logo,R.Region_Name AS Region, PD.Clk_InDeviceId as ReaderID, 
PD.Clk_InDate as Date, right(PD.Clk_InTime,charindex('' '',PD.Clk_InTime,1)) as InTime FROM TA_Tbl_Employee ED INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN '
   	Set @SelectSQL = @SelectSQL + 'TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Region R ON ED.Region_Id = R.Region_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_ClockDetails PD ON ED.SwipeCardNo = PD.Clk_EmpId Where '
	Set @SelectSQL = @SelectSQL + 'ED.IsDeleted = ''1'' and ED.Employee_FirstName + case when ED.Employee_MiddleName is 
not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) else '' '' end + ED.Employee_LastName like ''' + 
@EmployeeName + ''' '
	If Not (@EmployeeId = '' Or @EmployeeId = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @EmployeeId + ''' '
	End
	If Not (@CompanyID = '' Or @CompanyID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Company_Id = ''' + @CompanyID + ''' '
	End
	If Not (@RegionID = '' Or @RegionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Region_Id = ''' + @RegionID + ''' '
	End
	If Not (@BranchID = '' Or @BranchID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Branch_Id = ''' + @BranchID + ''' '
	End
	If Not (@DeptID = '' Or @DeptID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Dept_Id = ''' + @DeptID + ''' '
	End
	If Not (@SectionID = '' Or @SectionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Section_Id = ''' + @SectionID + ''' '
	End
	If (@FromDate <> '')
	Begin
		Set @SelectSQL = @SelectSQL + 'And PD.Clk_InDate >= ''' + @FromDate + ''' '
	End
	If (@ToDate <> '')
	Begin
		Set @SelectSQL = @SelectSQL + 'And PD.Clk_InDate <= ''' + @ToDate + ''' '
	End
	If Not (@TerminalID = '' Or @TerminalID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And PD.Clk_InDeviceId = ''' + @TerminalID + ''' '
	End
	Set @SelectSQL = @SelectSQL + 'Order By PD.Clk_InDate Asc'
	--Exec (@SelectSQL)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAnalysisDashboardforCheckINTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*

exec Proc_TA_RptAnalysisDashboardforCheckINTime @fromDat='2024-09-02',@ToDat='2024-09-02',
@Shift=2,@Hours='01:00'



*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptAnalysisDashboardforCheckINTime]
(   
	
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@SHIFT INT=0,
	@Hours nvarchar(5) ='02:00'
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	declare @MINWORKHOURS AS NVARCHAR(10)=''
	declare @EMPLOYEENAME NVARCHAR(MAX)=''
	declare @LEVELID NVARCHAR(MAX)='0'
	declare @EMPLOYEEID NVARCHAR(MAX)=''
	declare @EMPLOYEECATEGORY INT=0
	declare @EMPLOYEETYPE INT=0
	declare @USERGROUPNAME NVARCHAR(250)='SuperAdmin'
	declare @GRADELEVEL NVARCHAR(20)='0'
	declare @EMPSWIPECARD NVARCHAR(20)=''
	declare @PARENTID INT=0
	declare @DESIGNATIONID INT=0
	declare @GENDER NVARCHAR(10)='Both'
	declare @DATALOADING INT=0
	declare @EMPAUTOID BIGINT=0
	declare @EXPORT INT=0
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!='Superadmin')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER='BOTH' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME='Superadmin')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			(case when  vp.INTIME is null or vp.INTIME='00:00'  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME='00:00' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK='00:00' then null else vp.HRSWORK end) as HRSWORK,
			
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY'))))
		AND ((INTIME IS NOT NULL OR not(INTIME='00:00')) OR (OUTTIME IS NOT NULL OR not(OUTTIME='00:00')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))
	)
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,'00:00'))
	if(@TOTALMIN='') set @TOTALMIN=0
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(50),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		SHIFT_ID int 
	)	
	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	
	CASE	WHEN PD.FNATTENDANCECODE='PRESENT' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,'FN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION='M' then ' #' else '' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE ='PRESENT' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,'AN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION='M' then ' #' else '' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,'&AMP;','&') AS BRANCHNAME,
	REPLACE(T.TITLENAME,'&AMP;','&') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE='WEEKLY OFF' AND ANATTENDANCECODE='WEEKLY OFF' THEN	'-' 
			WHEN PD.FNATTENDANCECODE='HOLIDAY'OR ANATTENDANCECODE='HOLIDAY' THEN '-'
			ELSE PD.SUPPOSEDWORKHOURS 
	END 'SUPPOSEDWORKHOURS',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN 'BL' THEN ' - ' ELSE '' END + ISNULL(PD.STATUS,'')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),0,CHARINDEX(':',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE WHEN PD.SHIFT_ID='-1' THEN 'WEEKLY OFF' ELSE SHF.SHIFT_SHORTNAME +'('+SHF.Shift_StartTime+'-' +SHF.Shift_EndTime +')' END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN '-' 
				 WHEN PD.SHIFT_ID=-1 THEN '-'
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),'00:00'
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'NORMOTMINS',
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'WEEKOFFOTMINS',
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'HOLIDAYOTMINS',
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN '-' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	'00:00',
	'00:00',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+'/'+
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude,PD.SHIFT_ID as Shiftidforchart
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME='Superadmin' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'')='' or dbo.ConvertHoursToMinites(isnull(HRSWORK,'00:00'))>=@TOTALMIN)
		
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()


DECLARE @TotalMinutes INT = DATEPART(HOUR, @Hours) * 60 + DATEPART(MINUTE, @Hours);
DECLARE @HalfMinutes INT = @TotalMinutes / 2;

--SELECT Shift_Id, Shift_StartTime as Before,CONVERT(VARCHAR(5), DATEADD(MINUTE, @HalfMinutes, Shift_StartTime), 108) AS b1,
--CONVERT(VARCHAR(5), DATEADD(MINUTE, @TotalMinutes, Shift_StartTime), 108) as b2 into #TempShiftChartData from TA_Tbl_Shift where Shift_ShortName !='NOS'  order by Shift_Id

SELECT 
   Shift_Id, Shift_StartTime AS Before,
   FORMAT(DATEADD(MINUTE, @HalfMinutes, Shift_StartTime), 'hh:mm tt') AS b1,
   FORMAT(DATEADD(MINUTE, @TotalMinutes, Shift_StartTime), 'hh:mm tt') AS b2 into #TempShiftChartData
FROM 
   TA_Tbl_Shift 
ORDER BY 
   Shift_Id;


--Select * from TA_Tbl_Shift


	IF(@EXPORT=0)
	BEGIN
		SELECT	 
	EMPLOYEE_ID,
		EMPNAME,
		BRANCHNAME,
		DESIGNATION,
		#TEMPMONTHLYATTENDANCE.SHIFT_ID,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,
		#TempShiftChartData.Before,
		#TempShiftChartData.b1,
		#TempShiftChartData.b2,
		case when ( INTIME < #TempShiftChartData.Before and INTIME != #TempShiftChartData.Before and INTIME != '') then 1 else 0 end as ChartBefore,
		case when ( INTIME between #TempShiftChartData.Before and #TempShiftChartData.b1) then 1 else 0 end as ChartB1,
		case when ( INTIME between #TempShiftChartData.b1 and #TempShiftChartData.b2) then 1 else 0 end as ChartB2,
		case when ( INTIME > #TempShiftChartData.b2) then 1 else 0 end as LateBeyondlimit,
		case when ( INTIME = '' or INTIME = null or INTIME = '00:00' or isnull( INTIME ,'00:00')='00:00') then 1 else 0 end as LeaveEmployees into #TempChartforCount
		FROM #TEMPMONTHLYATTENDANCE 
		Inner Join #TempShiftChartData on #TempShiftChartData.Shift_Id = #TEMPMONTHLYATTENDANCE.SHIFT_ID
		where #TEMPMONTHLYATTENDANCE.SHIFT_ID=@Shift
		ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)

	END
		--Select * from #TempChartforCount
	Select Before as ShiftBeforeTime,b1 as ShiftB1,b2 as ShiftB2, Sum(ChartBefore) as BeforeShift,Sum(ChartB1)as Betweeen1,Sum(ChartB2) as Between2,Sum(LateBeyondlimit) as LateBeyondlimit,Sum(LeaveEmployees) as LeaveEmployees
	from #TempChartforCount group by Before,b1,b2


	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_RptAttendanceDetail]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), @SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @PresentDays As Varchar(50)
	Declare @AbsentDays as varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)
	Declare @In_Out_Sql as varchar(4000)
	Declare @TestInDate as Varchar(50)
	Declare @TestOutDate as Varchar(50)
	Declare @TestEmployeeId as Varchar(50)
	Declare @WeekOff as int
	Set @WeekOff = 0
	select @WeekOff = dbo.udf_CompleteWeekRange(convert(varchar, @FromDate, 101), convert(varchar, @ToDate, 101), 1)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Set @PresentDays = '0'
	Set @AbsentDays = '0'
	Set @LateComingDays = '0'
	Set @TotalLateEntryHrs = '00:00'
	Set @LateExitDays = '0'
	Set @TotalLateExitHrs = '00:00'
	Set @TotalLeaves = '0'
	Set @ESILeaves = '0'
	Select @AbsentDays = case when sum(NumberOfDays) is not null then sum(NumberOfDays) else '0' end From TA_Tbl_LeaveApplication where Employee_Id = @TestEmployeeId and IsDeleted = 1 And (( Leave_FromDate  between @FromDate  And @ToDate ) or (Leave_ToDate between @FromDate  And @ToDate  ))
	Select @TotalLeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else '0' end From TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = @TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate and (LT.LeaveType = 'CL' or LT.LeaveType = 'EL' or LT.LeaveType = 'SL')
	Select @ESILeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else '0' end From TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = @TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 and LT.LeaveType = 'ESI' And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 - @WeekOff as varchar)
	if (@FromDate = NULL and  @ToDate = NULL)
	Begin
		DECLARE d CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_InDate, Clk_OutDate from TA_Tbl_ClockDetails where Clk_EmpId = @TestEmployeeId
	End
	Else
	Begin
		DECLARE d CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_InDate from TA_Tbl_ClockDetails where ((Clk_InDate >= @FromDate and Clk_InDate <= @ToDate)) and Clk_EmpId = @TestEmployeeId
	End	
	OPEN d 
	FETCH NEXT FROM d INTO @TestInDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @LateBy as Varchar(50)
	Declare @LateByTime as varchar(50)
	Declare @ActIn as varchar(50)
	Declare @Grace as varchar(50)
	Declare @CheckSunday as int
	Set @CheckSunday = 0
	select @CheckSunday = dbo.udf_CompleteWeekRange(convert(varchar, @TestInDate, 101), convert(varchar, @TestInDate, 101), 1)
	Select @ActIn = Shift_StartTime , @Grace = Case len(Shift_GraceInTime) when 1 then '00:0' when 2 then '00:' End + Shift_GraceInTime From TA_Tbl_Shift where Shift_Id = 1
	--SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101) - convert(datetime,@Grace,101) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = @TestEmployeeId
	SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101)  FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = @TestEmployeeId
	--if (convert(varchar,@LateBy,101) > convert(datetime,'Dec 30 1899 12:00AM',101))
	if (convert(varchar,@LateBy,101) > convert(datetime,@Grace,101))
	Begin
	--Set @LateByTime = left(right(convert(datetime,@LateBy,101) + convert(datetime,@Grace,101),7),5)
	Set @LateByTime = left(right(convert(datetime,@LateBy,101) ,7),5)
	if (left(@LateByTime,2)='12')
	Begin
		Set @LateByTime = '00:' + right(@LateByTime,2)
	end
	if (left(@LateByTime,1)='')
	Begin
		Set @LateByTime = '0' + right(@LateByTime,4)
	end
	if(@CheckSunday <> 1)
	Begin
		Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1) as int) + cast(left(@LateByTime,charindex(':',@LateByTime,1)-1) as int) as varchar) + ':' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)) as int) + cast(right(@LateByTime,charindex(':',@LateByTime,1)-1) as int) as varchar)
		Set @LateComingDays = @LateComingDays + 1
	End
	End
	FETCH NEXT FROM d INTO @TestInDate
	END 
	CLOSE d 
	DEALLOCATE d
	DECLARE e CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_OutDate from TA_Tbl_ClockDetails where ((Clk_OutDate >= @FromDate and Clk_OutDate <= @ToDate)) and Clk_EmpId = @TestEmployeeId
	OPEN e
	FETCH NEXT FROM e INTO @TestOutDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @EarlyBy as Varchar(50)
	Declare @EarlyByTime as varchar(50)
	Declare @ActOut as varchar(50)
	Declare @GraceOut as varchar(50)	
	Set @CheckSunday = 0
	select @CheckSunday = dbo.udf_CompleteWeekRange(convert(varchar, @TestOutDate, 101), convert(varchar, @TestOutDate, 101), 1)
	Select  @ActOut = Shift_EndTime , @GraceOut = Case len(Shift_GraceOutTime) when 1 then '00:0' when 2 then '00:' End + Shift_GraceOutTime From TA_Tbl_Shift where Shift_Id = 1	
	SELECT @EarlyBy = max(convert(datetime,Clk_OutTime,101)) - convert(datetime,@ActOut,101) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestOutDate,101) and Clk_EmpId = @TestEmployeeId
	--if (convert(varchar,@EarlyBy,101) > convert(datetime,'Dec 30 1899 12:00AM',101))
	if (convert(varchar,@EarlyBy,101) > convert(datetime,@GraceOut,101))
	Begin
	Set @EarlyByTime = left(right(convert(datetime,@EarlyBy,101),7),5)
	if (left(@EarlyByTime,2)='12')
	Begin
		Set @EarlyByTime = '00:' + right(@EarlyByTime,2)
	end
	if (left(@EarlyByTime,1)='')
	Begin
		Set @EarlyByTime = '0' + right(@EarlyByTime,4)
	end
	if(@CheckSunday <> 1)
	Begin
		Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1) as int) + cast(left(@EarlyByTime,charindex(':',@EarlyByTime,1)-1) as int) as varchar) + ':' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)) as int) + cast(right(@EarlyByTime,charindex(':',@EarlyByTime,1)-1) as int) as varchar)
		Set @LateExitDays = @LateExitDays + 1
	End
	End
	FETCH NEXT FROM e INTO @TestOutDate
	END 
	CLOSE e
	DEALLOCATE e
	Declare @Test as int
	Set @Test = cast((right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)))/60 as int)
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1) as int) + @Test as varchar) + ':' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)) as int) - (@Test * 60) as varchar)
	Select @TotalLateEntryHrs =
	(Case len (left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1)) + ':' +
	Case len (right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1))))	
	Set @Test = cast((right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)))/60 as int)
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1) as int) + @Test as varchar) + ':' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)) as int) - (@Test * 60) as varchar)
	Select @TotalLateExitHrs =
	(Case len (left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1)) + ':' +
	Case len (right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1))))	
	Set @SelectSQL = ' ' 
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    	Set @SelectSQL = @SelectSQL + 'D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, '
    	Set @SelectSQL = @SelectSQL + 'C.Company_Logo AS Logo,R.Region_Name AS Region, ''' + @PresentDays + ''',''' + @AbsentDays + ''', ''' + @LateComingDays + ''',''' + @TotalLateEntryHrs + ''', ''' + @LateExitDays + ''', ''' + @TotalLateExitHrs + ''', ''' + @TotalLeaves + ''', ''' + @ESILeaves + ''' FROM TA_Tbl_Employee ED LEFT OUTER JOIN '
    	Set @SelectSQL = @SelectSQL + 'TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id LEFT OUTER JOIN TA_Tbl_Title T ON ED.Designation_Id = T.TitleId LEFT OUTER JOIN '
    	Set @SelectSQL = @SelectSQL + 'TA_Tbl_Section S ON ED.Section_Id = S.Section_Id LEFT OUTER JOIN '
    	Set @SelectSQL = @SelectSQL + 'TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id LEFT OUTER JOIN '
    	Set @SelectSQL = @SelectSQL + 'TA_Tbl_Region R ON ED.Region_Id = R.Region_Id '
    	Set @SelectSQL = @SelectSQL + 'Where ED.IsDeleted = ''1'' '
	Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @TestEmployeeId + ''' '
	If Not (@CompanyID = '' Or @CompanyID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Company_Id = ''' + @CompanyID + ''' '
	End
	If Not (@RegionID = '' Or @RegionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Region_Id = ''' + @RegionID + ''' '
	End
	If Not (@BranchID = '' Or @BranchID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Branch_Id = ''' + @BranchID + ''' '
	End
	If Not (@DeptID = '' Or @DeptID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Dept_Id = ''' + @DeptID + ''' '
	End
	If Not (@SectionID = '' Or @SectionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Section_Id = ''' + @SectionID + ''' '
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  PresentDays, AbsentDays, LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
	Set @EmployeeName = @EmployeeName + '%'
	--If Not (@EmployeeId = '' Or @EmployeeId = '0')  
	If (@EmployeeId = '' Or @EmployeeId = '0') 
	Begin
		Select * From #TempReportTable where EmployeeName like @EmployeeName
	End
	Else
	Begin		Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetailold]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_RptAttendanceDetailold]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @PresentDays As Varchar(50)
	Declare @AbsentDays as varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)
	Declare @TestInDate as Varchar(50)
	Declare @TestOutDate as Varchar(50)
	Declare @TestEmployeeId as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Set @PresentDays = '0'
	Set @AbsentDays = '0'
	Set @LateComingDays = '0'
	Set @TotalLateEntryHrs = '00:00'
	Set @LateExitDays = '0'
	Set @TotalLateExitHrs = '00:00'
	Set @TotalLeaves = '0'
	Set @ESILeaves = '0'
	Select @AbsentDays = case when sum(NumberOfDays) is not null then sum(NumberOfDays) else '0' end From 
TA_Tbl_LeaveApplication where Employee_Id = @TestEmployeeId and IsDeleted = 1 And Leave_FromDate >= @FromDate and 
Leave_ToDate <= @ToDate
	Select @TotalLeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else '0' end From 
TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = 
@TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate 
and (LT.LeaveType = 'CL' or LT.LeaveType = 'EL' or LT.LeaveType = 'SL')
	Select @ESILeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else '0' end From 
TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = 
@TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 and LT.LeaveType = 'ESI' And LA.Leave_FromDate >= @FromDate and 
LA.Leave_ToDate <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 as varchar)
	DECLARE d CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct Clk_InDate, Clk_OutDate from TA_Tbl_ClockDetails where (Clk_InDate >= @FromDate and Clk_InDate <= 
@ToDate) or (Clk_OutDate >= @FromDate and Clk_OutDate <= @ToDate) and Clk_EmpId = @TestEmployeeId
	OPEN d 
	FETCH NEXT FROM d INTO @TestInDate,@TestOutDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @LateBy as Varchar(50)
	Declare @LateByTime as varchar(50)
	Declare @ActIn as varchar(50)
	Declare @Grace as varchar(50)
	Declare @EarlyBy as Varchar(50)
	Declare @EarlyByTime as varchar(50)
	Declare @ActOut as varchar(50)
	Declare @GraceOut as varchar(50)	
	Select @ActIn = Shift_StartTime , @Grace = Case len(Shift_GraceInTime) when 1 then '00:0' when 2 then '00:' End + 
Shift_GraceInTime, @ActOut = Shift_EndTime , @GraceOut = Case len(Shift_GraceOutTime) when 1 then '00:0' when 2 then '00:' 
End + Shift_GraceOutTime From TA_Tbl_Shift where Shift_Id = 1
	SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101) - convert(datetime,@Grace,101) 
FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = 
@TestEmployeeId
	if (convert(varchar,@LateBy,101) > convert(datetime,'Dec 30 1899 12:00AM',101))
	Begin
	Set @LateByTime = left(right(convert(datetime,@LateBy,101) + convert(datetime,@Grace,101),7),5)
	if (left(@LateByTime,2)='12')
	Begin
		Set @LateByTime = '00:' + right(@LateByTime,2)
	end
	if (left(@LateByTime,1)='')
	Begin
		Set @LateByTime = '0' + right(@LateByTime,4)
	end
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1) as int) + 
cast(left(@LateByTime,charindex(':',@LateByTime,1)-1) as int) as varchar) + ':' + 
cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)) as int) + 
cast(right(@LateByTime,charindex(':',@LateByTime,1)-1) as int) as varchar)
	Set @LateComingDays = @LateComingDays + 1
	End
	SELECT @EarlyBy = max(convert(datetime,Clk_OutTime,101)) - convert(datetime,@ActOut,101) FROM TA_Tbl_ClockDetails 
Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestOutDate,101) and Clk_EmpId = @TestEmployeeId
	if (convert(varchar,@EarlyBy,101) > convert(datetime,'Dec 30 1899 12:00AM',101))
	Begin
	Set @EarlyByTime = left(right(convert(datetime,@EarlyBy,101),7),5)
	if (left(@EarlyByTime,2)='12')
	Begin
		Set @EarlyByTime = '00:' + right(@EarlyByTime,2)
	end
	if (left(@EarlyByTime,1)='')
	Begin
		Set @EarlyByTime = '0' + right(@EarlyByTime,4)
	end
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1) as int) + 
cast(left(@EarlyByTime,charindex(':',@EarlyByTime,1)-1) as int) as varchar) + ':' + 
cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)) as int) + 
cast(right(@EarlyByTime,charindex(':',@EarlyByTime,1)-1) as int) as varchar)
	Set @LateExitDays = @LateExitDays + 1
	End
	FETCH NEXT FROM d INTO @TestInDate,@TestOutDate
	END 
	CLOSE d 
	DEALLOCATE d
	Declare @Test as int
	Set @Test = cast((right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)))/60 as int)
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1) as int) + @Test as 
varchar) + ':' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)) as int) - 
(@Test * 60) as varchar)
	Select @TotalLateEntryHrs =
	(Case len (left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(left(@TotalLateEntryHrs,charindex(':',@TotalLateEntryHrs,1)-1)) + ':' +
	Case len (right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1)))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex(':',@TotalLateEntryHrs,1))))	
	Set @Test = cast((right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)))/60 as int)
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1) as int) + @Test as 
varchar) + ':' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)) as int) - 
(@Test * 60) as varchar)
	Select @TotalLateExitHrs =
	(Case len (left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1))
	when 1 then '0'
	when 2 then ''
	End + 
	rtrim(left(@TotalLateExitHrs,charindex(':',@TotalLateExitHrs,1)-1)) + ':' +
	Case len (right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1)))
	when 1 then '0'
	when 2 then ''
	End +
	rtrim(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex(':',@TotalLateExitHrs,1))))	
	Set @SelectSQL = ' ' 
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName 
as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    Set @SelectSQL = @SelectSQL + 'D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, '
    Set @SelectSQL = @SelectSQL + 'C.Company_Logo AS Logo,R.Region_Name AS Region, ''' + @PresentDays + ''',''' + @AbsentDays 
+ ''', ''' + @LateComingDays + ''',''' + @TotalLateEntryHrs + ''', ''' + @LateExitDays + ''', ''' + @TotalLateExitHrs + ''', 
''' + @TotalLeaves + ''', ''' + @ESILeaves + ''' FROM TA_Tbl_Employee ED INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Region R ON ED.Region_Id = R.Region_Id '
    Set @SelectSQL = @SelectSQL + 'Where ED.IsDeleted = ''1'' '
	Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @TestEmployeeId + ''' '
	If Not (@CompanyID = '' Or @CompanyID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Company_Id = ''' + @CompanyID + ''' '
	End
	If Not (@RegionID = '' Or @RegionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Region_Id = ''' + @RegionID + ''' '
	End
	If Not (@BranchID = '' Or @BranchID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Branch_Id = ''' + @BranchID + ''' '
	End
	If Not (@DeptID = '' Or @DeptID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Dept_Id = ''' + @DeptID + ''' '
	End
	If Not (@SectionID = '' Or @SectionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Section_Id = ''' + @SectionID + ''' '
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  PresentDays, AbsentDays, 
LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
	Set @EmployeeName = @EmployeeName + '%'
	If Not (@EmployeeId = '' Or @EmployeeId = '0') 
	Begin
	Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName  
	End
	Else 
	Begin
	Select * From #TempReportTable where EmployeeName like @EmployeeName 
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE  PROCEDURE [dbo].[Proc_TA_RptAttendanceDetails]
(@EmployeeID VarChar(50), @LevelID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Designation VarChar(255),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @AbsentDays as varchar(50)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)	
	Declare @PresentDays As Varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Set @AbsentDays = '0'
	Set @TotalLeaves = '0'
	Set @ESILeaves = '0'
	Set @PresentDays = '0'
	Set @LateComingDays = '0'
	Set @TotalLateEntryHrs = '00:00'
	Set @LateExitDays = '0'
	Set @TotalLateExitHrs = '00:00'
	Declare @TestEmployeeId as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Select @AbsentDays = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else '0' end From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND Attendance='Absent'
	Select @TotalLeaves = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else '0' end From TA_Tbl_ProcessedData PD  where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND (PD.Attendance = 'CL' or PD.Attendance = 'EL' or PD.Attendance = 'SL')
    Select @ESILeaves = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else '0' end From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId and PD.Attendance = 'ESI' And Date >= @FromDate and Date <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 as varchar)
	Select @LateComingDays= case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else '0' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND LateIn <> '00:00:00' AND LateIn <> '0' AND LateIn is not null
	--Select 	@TotalLateEntryHrs=case when sum(PD.HrsLess) is not null then sum(PD.HrsLess) else '0' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND LateIn <> '00:00:00' AND LateIn <> '0' AND LateIn is not null
	Select @LateExitDays= case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else '0' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND HrsOT <> '0' AND HrsOT is not null
	--Select 	@TotalLateExitHrs=case when sum(PD.HrsOT) is not null then sum(PD.HrsOT) else '0' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND HrsOT <> '0' AND HrsOT is not null
	Set @SelectSQL = ' ' 
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    Set @SelectSQL = @SelectSQL + ' T.TitleName AS Designation, '
    Set @SelectSQL = @SelectSQL + '''' + @PresentDays + ''',''' + @AbsentDays + ''', ''' + @LateComingDays + ''',''' + @TotalLateEntryHrs + ''', ''' + @LateExitDays + ''', ''' + @TotalLateExitHrs + ''', ''' + @TotalLeaves + ''', ''' + @ESILeaves + ''' FROM TA_Tbl_Employee ED INNER JOIN '
    Set @SelectSQL = @SelectSQL + ' TA_Tbl_Title T ON ED.Designation_Id = T.TitleId  '
    Set @SelectSQL = @SelectSQL + 'Where ED.IsDeleted = ''1'' '
	Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @TestEmployeeId + ''' '
	If Not (@LevelID = '' Or @LevelID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Level_Id = ''' + @LevelID + ''' '
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName,  Designation, PresentDays, AbsentDays, LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
--	Set @EmployeeName = @EmployeeName + '%'
--	If Not (@EmployeeId = '' Or @EmployeeId = '0') 
--	Begin
--	Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName  
--	End
--	Else 
--	Begin
--	Select * From #TempReportTable where EmployeeName like @EmployeeName 
--	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAuditTrail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Procedure Name : 
Proc_TA_RptAuditTrail '07/07/2008','07/08/2015','Manual Time Entry',''  
Description : Audit Trail Report - get operation(insert,update,delete) details with required information   
Tables Included : TA_Tbl_AuditTable,TA_Tbl_AuditField,TA_Tbl_AuditOperation,TA_Tbl_Employee    
Created By : Christoper S, Senthil Kumar NP    
Created On : 11-Jan-08    
Modified By :
Modified On :*/  
CREATE   PROCEDURE [dbo].[Proc_TA_RptAuditTrail]
(	
	@fromDate as dateTime,
	@toDate as dateTime,
	@TableDescription as nvarchar(100),
	@opr as nvarchar(10)
)	
AS
BEGIN
	set nocount on
	Create table #TempStarting(id int,TableID int,RecordID int,FieldID int)
	Insert into #TempStarting 
	select AO.ID,AO.TableID,AO.RecordID,AO.FieldID from TA_Tbl_AuditOperation AO
	inner join TA_Tbl_AuditTable AT on AO.TableID=AT.TableID
	inner join TA_Tbl_AuditField AF on AO.TableID =AF.TableID and AO.FieldID=AO.FieldID
	where 	
	(AO.OldValue<>isnull(AO.NewValue,'') or AO.OldValue is null) And AT.Status = 1 AND AF.Status = 1 AND 
	(datediff(dd, cast (@fromDate as nvarchar(11)),AO.OprDate)>=0 and datediff(dd, cast(@toDate as nvarchar(11)),AO.OprDate)<=0 )
	declare @sql as varchar(max)
	set @sql=''
	set @sql = @sql + 'SELECT TA_Tbl_AuditTable.TableDescription AS TableName, 
						TA_Tbl_AuditField.FieldDescription AS FieldName, 
						TA_Tbl_AuditOperation.Opr AS Operation,'
	set @sql = @sql + ' 
	case	when TA_Tbl_AuditTable.TableDescription=''Leave Application'' and TA_Tbl_AuditField.FieldName=''Employee_Id''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''Permission'' and TA_Tbl_AuditField.FieldName=''Employee_Id''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''Terminal Master'' and TA_Tbl_AuditField.FieldName=''TerminalDatatype_ID''
				and TA_Tbl_AuditOperation.OldValue is not null then (select Raw_Data_Format from TA_Tbl_Terminaldatatype where terminaldatatype_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee1_Id''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee2_Id''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee1_ActualShift''
				and TA_Tbl_AuditOperation.OldValue is not null then (select case when shift_shortName is null then ''off'' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee2_ActualShift''
				and TA_Tbl_AuditOperation.OldValue is not null then (select case when shift_shortName is null then ''off'' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.OldValue is null then ''''
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.OldValue=0 then ''Manual Time Entry''
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.OldValue=1 then ''Manual Time Entry Import''				
			else TA_Tbl_AuditOperation.OldValue end,
	case	when TA_Tbl_AuditTable.TableDescription=''Leave Application'' and TA_Tbl_AuditField.FieldName=''Employee_Id''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''Permission'' and TA_Tbl_AuditField.FieldName=''Employee_Id''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=NewValue)
			when TA_Tbl_AuditTable.TableDescription=''Terminal Master'' and TA_Tbl_AuditField.FieldName=''TerminalDatatype_ID''
				and TA_Tbl_AuditOperation.NewValue is not null then (select Raw_Data_Format from TA_Tbl_Terminaldatatype where terminaldatatype_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee1_Id''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee2_Id''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)	
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee1_ActualShift''
				and TA_Tbl_AuditOperation.NewValue is not null then 
				(select case when NewValue=-1 then ''off'' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''ShiftExchange'' and TA_Tbl_AuditField.FieldName=''Employee2_ActualShift''
				and TA_Tbl_AuditOperation.NewValue is not null then (select case when NewValue=-1 then ''off'' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.NewValue is null then ''''
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.NewValue=0 then ''Manual Time Entry''
			when TA_Tbl_AuditTable.TableDescription=''Manual Time Entry'' and TA_Tbl_AuditField.FieldName=''IsImported''
				and TA_Tbl_AuditOperation.NewValue=1 then ''Manual Time Entry Import''	
			else TA_Tbl_AuditOperation.NewValue end , 
						TA_Tbl_AuditOperation.EmployeeID,TA_Tbl_AuditOperation.OprDate,'
	set @sql = @sql + ' TA_Tbl_Employee.Employee_Code_Id, isnull(TA_Tbl_Employee.Employee_FirstName,'''')+ ' 
	set @sql = @sql + ' '' '' +isnull(TA_Tbl_Employee.Employee_LastName,'''') as EmployeeName,
		case when  Datatype=''datetime'' then convert(datetime,TA_Tbl_AuditOperation.NewValue) 
						end as Newvaluedatetime,Datatype,TA_Tbl_AuditOperation.RecordID,
		case when  Datatype=''datetime'' then convert(datetime,TA_Tbl_AuditOperation.OldValue) 
						end as Oldvaluedatetime,TA_Tbl_AuditOperation.ID
		FROM TA_Tbl_AuditTable'	
	set @sql = @sql + ' INNER JOIN TA_Tbl_AuditField ON TA_Tbl_AuditTable.TableID = TA_Tbl_AuditField.TableID'
	set @sql = @sql + ' INNER JOIN TA_Tbl_AuditOperation  ON TA_Tbl_AuditField.FieldID = TA_Tbl_AuditOperation.FieldID'
	set @sql = @sql + ' Left JOIN  #TempStarting TS ON TA_Tbl_AuditOperation.RecordID = TS.RecordID
	and TS.TableID=TA_Tbl_AuditOperation.FieldID and TA_Tbl_AuditTable.TableID=ts.TableID
	'
	set @sql = @sql + ' Left JOIN TA_Tbl_Employee ON TA_Tbl_AuditOperation.EmployeeID = TA_Tbl_Employee.Employee_Id'
	set @sql = @sql + ' WHERE TA_Tbl_AuditTable.Status = 1 AND TA_Tbl_AuditField.Status = 1 AND (TA_Tbl_AuditOperation.OprDate >= CONVERT(DATETIME,''' + convert(nvarchar(20),@fromDate,101) + ' 00:00:000'', 102) and TA_Tbl_AuditOperation.OprDate <=  CONVERT(DATETIME,''' + convert(nvarchar(20),@toDate,101) +' 23:59:000'', 102)) '
	--set @sql = @sql + ' WHERE TA_Tbl_AuditTable.Status = 1 AND TA_Tbl_AuditField.Status = 1 AND (TA_Tbl_AuditOperation.OprDate >= CONVERT(char(11),''' + cast (@fromDate as nvarchar(11)) + ''', 101) and TA_Tbl_AuditOperation.OprDate <=  CONVERT(char(11),''' + cast(@toDate as nvarchar(11)) +''', 101)) '
	--set @sql = @sql + ' WHERE 1=1 '
	--		set @sql = @sql + ' TA_Tbl_AuditOperation.OprDate Between ''' + cast (@fromDate as nvarchar(11)) + ''' and  ''' + cast(@toDate as nvarchar(11)) +''') '
	if Not (@opr='' or @opr='All')		
		Begin
			set @sql = @sql + ' And TA_Tbl_AuditOperation.Opr=''' +@opr + ''' '
		End
	if Not(@TableDescription='' or @TableDescription='All')
		Begin
			set @sql = @sql + ' And TA_Tbl_AuditTable.TableDescription=''' +@TableDescription + ''' '
		End		
	set @sql = @sql + ' ORDER BY TA_Tbl_AuditOperation.OprDate, TA_Tbl_AuditOperation.RecordID'
	Create table #TempFinal(TableName nvarchar(max),fieldName nvarchar(max),Operation nvarchar(max),Oldvalue varchar(max),NewValue nvarchar(max),
	EmployeeID varchar(max),oprDate datetime,Employee_Code_Id varchar(max),EmployeeName varchar(max),Newvaluedatetime datetime,DataType nvarchar(max)
	,RecordID int,Oldvaluedatetime datetime,Orderby int
	)
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)	
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	insert into #TempFinal exec (@sql)	
	select 
	TableName,fieldName,Operation,
	case when DataType='datetime' then 
	case when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Oldvaluedatetime,106),' ','-')
		 when cast(@dateFormat as varchar(100))=103 then CONVERT(VARCHAR, Oldvaluedatetime, 103) 
		 else CONVERT(VARCHAR, Oldvaluedatetime, 101) 
	end 
	else Oldvalue end Oldvalue,
	EmployeeID ,oprDate ,Employee_Code_Id ,EmployeeName	,
	case when DataType='datetime' then 
	case when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Newvaluedatetime,106),' ','-')
		 when cast(@dateFormat as varchar(100))=103 then CONVERT(VARCHAR, Newvaluedatetime, 103) 
		 else CONVERT(VARCHAR, Newvaluedatetime, 101) 
	end 
	else NewValue end NewValue,RecordID 
	from #TempFinal order by orderby,oprdate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptCanteenReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
	created By		:	Velumani
	Created Date	:	02-Dec-2019
	Description		:	Display of punch type based report
*/
---- Proc_TA_RptCanteenReport '','','01/Jan/2019','30/Nov/2019','',0,0,0,'SuperAdmin','0',0,0,'Both','all',0,0
-- Proc_TA_RptCanteenReport '','0,1','01/Dec/2019','30/Dec/2019','',0,0,0,'SuperAdmin','0',0,0,'Both','Shift In',0,0
-- select * from ta_tbl_clockdetails where clk_date='' and clk_Empid in (1,2)
CREATE PROCEDURE [dbo].[Proc_TA_RptCanteenReport]      
(
	@EmployeeID varchar(50), 
	@LevelID varchar(8000),  
	@FromDate varchar(50), 
	@ToDate varchar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@punchTypeValue varchar(50),
	@EmpAutoId bigint,
	@ExportType int
)      
AS      
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID varchar(50)
	DECLARE @local_LevelID varchar(8000)
	DECLARE @local_FromDate varchar(50) 
	DECLARE @local_ToDate varchar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_punchTypeValue=@punchTypeValue
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE TABLE #TempCanteenClockDetails
	(
		[Clk_EmpId] nvarchar(20) ,
		[Clk_PunchType] nvarchar(20) ,
		[Clk_Punchdatetime] datetime,
		[Clk_Date] datetime
	)
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End	
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @CanteenData1 varchar(8000)
	set @CanteenData1 = ' insert into  #TempCanteenClockDetails 
		select  [Clk_EmpId],[clk_Inpunchtype] ,	Clk_InDate + Clk_InTime as Punchdatetime,[Clk_Date]  from ta_tbl_clockdetails
		UNION
		select  [Clk_EmpId] ,[Clk_OutPunchType] , Clk_OutDate+Clk_OutTime as Punchdatetime,[Clk_Date]  from ta_tbl_clockdetails
		where ta_tbl_clockdetails.IsVoid=0 and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,'''+cast(@local_FromDate as nvarchar(20))+''', 102) 
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(20))+''', 102) 
		and (Clk_InDate + Clk_InTime is not null or Clk_OutDate+Clk_OutTime is not null) order by Punchdatetime
		'
	Execute(@CanteenData1);	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime
	)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date
	from TA_Tbl_ProcessedData 
	inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	Declare @SelectSQL As varchar(max)
	Set @SelectSQL = ' '        
	create table #TempFinal(employee_Code_Id varchar(50),Employee_FirstName varchar(250)
	,[Level Name] varchar(250),Clk_Punchdatetime datetime,Clk_PunchType varchar(100),shift_shortname varchar(25),
	clk_date datetime)
	    Set @SelectSQL = @SelectSQL + 'insert into #TempFinal select isnull(ED.employee_Code_Id,'''') as employee_Code_Id, 
	    isnull(ED.Employee_FirstName,'''')+  SPACE(1) + ISNULL(ED.EMPLOYEE_LASTNAME,'''') as Employee_FirstName,
	    isnull(replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&''),'''') AS ''Level Name'',
	    isnull(CD.Clk_Punchdatetime,'''') as Clk_Punchdatetime,
	    isnull(CD.Clk_PunchType,'''') as Clk_PunchType,
	    isnull(SH.shift_shortname,'''') + SPACE(1) + ''('' + ISNULL(SH.Shift_StartTime,'''') + SPACE(1) + ISNULL(SH.Shift_EndTime,'''') + '')'' as shift_shortname,
	    isnull(convert(varchar,CD.Clk_Date,101),'''') as Clk_Date
		FROM TA_Tbl_Employee ED '  
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempCanteenClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID '  
	Set @SelectSQL = @SelectSQL + ''       
	Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and CD.Clk_Punchdatetime is not null and  ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) '
	if(@local_Gender<>'Both')
		begin
			set @SelectSQL = @SelectSQL + ' and ED.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@punchTypeValue<>'all')
		Begin
			set @SelectSQL = @SelectSQL +  ' And  CD.Clk_PunchType = ''' +  cast(@punchTypeValue  as nvarchar(50)) +''''  
		End
		Set @SelectSQL = @SelectSQL + ' order by CD.Clk_Punchdatetime'  
	Exec (@SelectSQL)
	select employee_Code_Id,Employee_FirstName,[Level Name],Clk_Punchdatetime,
	case when shift_shortname=' ( )' then '' else shift_shortname end as shift_shortname, convert(varchar,clk_date,110) as clk_date,Clk_PunchType from #TempFinal
	--select * from #TempFinal
	select isnull(convert(varchar,clk_date,110),'') as Punchdate
	,isnull(Clk_PunchType,'') as punchtypename
	,isnull([Level Name],'') as LevelName
	,case when shift_shortname=' ( )' then '' else shift_shortname end  as shift_shortname
	,isnull(count(Clk_PunchType),'') as DeptwisePunchCount
	from #TempFinal
	group by [Level Name], clk_date,Clk_PunchType,shift_shortname order by Punchdate
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempCanteenClockDetails 
	drop table #TempProcessedData
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptContractorAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
/*

Proc_TA_RptContractorAttendance_backup24022023 @MINWORKHOURS=N'',@FROMDAT='2023-02-01 00:00:00',@TODAT='2023-02-23 00:00:00',
@EMPLOYEENAME=N'',@LEVELID=N'',@EMPLOYEEID=N'',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'',@EMPSWIPECARD=N'',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N'both',@SHIFT=2,@DATALOADING=0,@EMPAUTOID=2,@EXPORT=0

*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptContractorAttendance]
	-- Add the parameters for the stored procedure here
	(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		LevelID int
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!='Superadmin')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER='BOTH' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME='Superadmin')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			--updated by velumani for Abraj Monthly attendance design issue
			--case when vp.INTIME='00:00' then '' else vp.INTIME end,
			--case when vp.OUTTIME='00:00' then '' else vp.OUTTIME end,
			--vp.SHIFT_ID,
			--case when vp.HRSWORK='00:00' then '' else vp.HRSWORK end,
			(case when  vp.INTIME is null or vp.INTIME='00:00'  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME='00:00' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK='00:00' then null else vp.HRSWORK end) as HRSWORK,
		-------------------------
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude,
			vp.Level_Id
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY'))))
		AND ((INTIME IS NOT NULL OR not(INTIME='00:00')) OR (OUTTIME IS NOT NULL OR not(OUTTIME='00:00')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))
	)

	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID

	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,'00:00'))
	if(@TOTALMIN='') set @TOTALMIN=0

	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(50),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)
	)	

	--Select * From #EMPLEVEL 

	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	CASE	WHEN PD.FNATTENDANCECODE='PRESENT' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,'FN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION='M' then ' #' else '' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE ='PRESENT' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,'AN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION='M' then ' #' else '' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'') AS EMPNAME,
	Replace(dbo.Fun_TA_GetBranchName(PD.LevelID),'&AMP;','&')As BRANCHNAME,
	--REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,'&AMP;','&') AS BRANCHNAME,
	REPLACE(T.TITLENAME,'&AMP;','&') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE='WEEKLY OFF' AND ANATTENDANCECODE='WEEKLY OFF' THEN	'-' 
			WHEN PD.FNATTENDANCECODE='HOLIDAY'OR ANATTENDANCECODE='HOLIDAY' THEN '-'
			ELSE PD.SUPPOSEDWORKHOURS 
	END 'SUPPOSEDWORKHOURS',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN 'BL' THEN ' - ' ELSE '' END + ISNULL(PD.STATUS,'')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),0,CHARINDEX(':',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE WHEN PD.SHIFT_ID='-1' THEN 'WEEKLY OFF' ELSE SHF.SHIFT_SHORTNAME +'('+SHF.Shift_StartTime+'-' +SHF.Shift_EndTime +')' END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN '-' 
				 WHEN PD.SHIFT_ID=-1 THEN '-'
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),'00:00'
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'NORMOTMINS',
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'WEEKOFFOTMINS',
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'HOLIDAYOTMINS',
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN '-' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	'00:00',
	'00:00',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+'/'+
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME='Superadmin' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'')='' or dbo.ConvertHoursToMinites(isnull(HRSWORK,'00:00'))>=@TOTALMIN)
	
	-- BranchName Update --

	--Declare @TblLevelID table (EmpAutoId int,levelId int, branchname varchar(20),processDate datetime)
	--insert into @TblLevelID (EmpAutoId,levelId,branchname,processDate)
	--Select TP.EMPAUTOID,TP.LevelID,dbo.Fun_TA_GetBranchName(TP.LevelID),TP.DATE From #TEMPPROCESSEDDATA TP 

	--update #TEMPMONTHLYATTENDANCE Set BRANCHNAME=tl.branchname From #TEMPMONTHLYATTENDANCE TP inner Join @TblLevelID tL on TP.DATE=tl.processDate
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()


	--Select * From #TEMPMONTHLYATTENDANCE 



	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		BRANCHNAME,
		DESIGNATION,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,
		BREAKHOURS,
		LUNCHHOURS ,	
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION,
		
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		
		
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'' as Intime1,
		'' as OutTime1,		 
		'' as Intime2,
		'' as OutTime2,
		'' as Intime3,
		'' as OutTime3,
		'' as Intime4,
		'' as OutTime4,
		'' as Intime5,
		'' as OutTime5,
		'' as AcutalWorkedHours,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	else IF(@EXPORT=8)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'' as Intime1,
		'' as OutTime1,		 
		'' as Intime2,
		'' as OutTime2,
		'' as Intime3,
		'' as OutTime3,
		'' as Intime4,
		'' as OutTime4,
		'' as Intime5,
		'' as OutTime5,
		'' as AcutalWorkedHours,
		InLocation,
		OutLocation ,
		InLatitude,
		InLongitude,
		OutLatitude ,
		OutLongitude,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)desc
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking

	END
	ELSE
	BEGIN
		SELECT	DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth,DENSE_RANK()OVER(ORDER BY EMPLOYEE_ID) AS [SL.NO],
				BRANCHNAME AS LEVEL,
				EMPLOYEE_ID AS [EMPLOYEE ID],
				EMPNAME AS [EMPLOYEE NAME],
				DESIGNATION,
				CATEGORYNAME AS [EMPLOYEE CATEGORY],
				GENDER,
				CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
						ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) 
				END AS DATE,	
				CASE	WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' 
						ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME 
				END [SHIFT SHORTNAME],
				INTIME AS [IN TIME],
				OUTTIME AS [OUT TIME],
				HRSWORK AS [HOURS WORKED],	
				SHIFT_TOTALWORKINGHOURS AS [DEFINED WORK HOURS],
				FIRSTSESSION AS [FIRST SESSION],
				SECONDSESSION AS [SECOND SESSION],
				SPEC_NormOT1,
				SPEC_NormOT2,		
				SPEC_OffOT1,
				SPEC_OffOT2,
				SPEC_HOLOT1,
				SPEC_HOLOT2,
				SUPPOSEDWORKHOURS,
				CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
				Case when FNATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end as present,
				Case when FNATTENDANCECODE in('Absent') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Absent') then 0.5 else 0.0 end as Absent,
				Case when FNATTENDANCECODE in('Weekly Off') then 0.5 else 0.0 end + case when ANATTENDANCECODE IN('Weekly Off') then 0.5 else 0.0 end as WeeklyOff,
				Case when FNATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end as Holiday,
				Case when FNATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH')then 0.5 else 0.0 end as Leave
				,StatusCode,
				EARLYOUT,
				LATEIN,
				OVERTIME,
				NORMOTMIN,
				OFFOTMIN,
				HOLOTMIN,
				NORMOT,
				OFFOT,
				HOLOT,
				LATEINMIN,
				EARLYOUTMIN,
				TOTDEFWORKHRS,
				TOTSUPWORKHRS,
				OVERTIMESTATUS,
				NIGHTORMORN,
				LUNCHINTIME,
				LUNCHOUTTIME
				,INNOTATION,
				OUTNOTATION
				,BREAKHOURS,
				LUNCHHOURS ,
				BREAKHOURSMINS,
				LUNCHHOURSMINS,
				SHIFT_STARTTIME,
				SHIFT_ENDTIME,
				WEEKDAY_WORKHRS,
				WEEKNUMBER ,
				FNATTENDANCECODE,
				ANATTENDANCECODE,
				DESIGNATION,
				BRANCHNAME,DATE processDate
				,'' as Intime1,
				'' as OutTime1,		 
				'' as Intime2,
				'' as OutTime2,
				'' as Intime3,
				'' as OutTime3,
				'' as Intime4,
				'' as OutTime4,
				'' as Intime5,
				'' as OutTime5,
				'' as AcutalWorkedHours,
				MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,MonthNo,WEEKNUMBER
	END	
	
	select EMPLOYEE_ID,
	TotLate_Hours =dbo.ConvertMinsToHours(SUM(isnull(LATEINMIN,0))),
	TotEarlyOut_Hours =dbo.ConvertMinsToHours(SUM(isnull(EARLYOUTMIN,0))),
	TotOT_Hours =dbo.ConvertMinsToHours(SUM(isnull(OVERTIME,0))),
	TotWrk_Hours =dbo.ConvertMinsToHours(SUM(CONVERT(INT,ISNULL(TOTALMINSWORKED,'0')))),
	Prsnt_Days=	SUM(CASE WHEN FNATTENDANCECODE='Present' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Present' THEN 0.5 ELSE 0 END), 
	Absnt_Days=	SUM(CASE WHEN FNATTENDANCECODE='Absent' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Absent' THEN 0.5 ELSE 0 END) ,
	Wkoff_Days=	SUM(CASE WHEN FNATTENDANCECODE='Weekly Off' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Weekly Off' THEN 0.5 ELSE 0 END), 
	H_Days=		SUM(CASE WHEN FNATTENDANCECODE='Holiday' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Holiday' THEN 0.5 ELSE 0 END) ,
	LOP_Days=	SUM(CASE WHEN FNATTENDANCECODE='LOP' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='LOP' THEN 0.5 ELSE 0 END),
	Leave_Days=	SUM(CASE WHEN FNATTENDANCECODE not in('Present','Absent','Weekly off','Holiday','LOP') THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE not in('Present','Absent','Weekly off','Holiday','LOP') THEN 0.5 ELSE 0 END),
	Totcalen_Days=DATEDIFF(d,@FROMDAT,@TODAT)	
	FROM #TEMPMONTHLYATTENDANCE
	group by EMPLOYEE_ID order by EMPLOYEE_ID
	
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
PROC_TA_RPTDAILYATTENDANCE @MINWORKHOURS=N'',@FROMDAT='2019-04-01 00:00:00',
@EMPLOYEENAME=N'',@EMPLOYEEID=N'787',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'0',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N'BOTH',@SHIFT=0,@EMPAUTOID=0,@LOCATIONID=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyAttendance]
(   
--Passing filter values from Application

	@MINWORKHOURS AS NVARCHAR(10)=null,-- From Applic		
	@FROMDAT DATETIME=null,-- From Applic
	@EMPLOYEENAME NVARCHAR(MAX)=null, -- From Applic	
	@EMPLOYEEID NVARCHAR(MAX)=null,-- From Applic
	@EMPLOYEECATEGORY INT=null,-- From Applic
	@EMPLOYEETYPE INT=0,-- From Applic		
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,-- From Applic
	@GENDER NVARCHAR(10)=null,-- From Applic	
	@SHIFT INT=0,-- From Applic	
	@EMPAUTOID BIGINT=0,
	@LOCATIONID INT
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	
	--Declare local variables to increase execution efficiency
	
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT	
	DECLARE @local_EMPAUTOID BIGINT
    DECLARE @local_LOCATIONID INT
	
	--Assign values to local varibles
	
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))  
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))     
    SET @local_LOCATIONID		= LTRIM(RTRIM(@LOCATIONID))

	
	
	--Temp query construction and execution	
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)	
	
	
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10)
	)
	
	DECLARE @ISREPORTINGTO AS INT	
	DECLARE @ISINDIVIDUAL AS INT
	
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
	
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF not(@local_GENDER='BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@local_GENDER AS NVARCHAR(8)) + ''' '  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@local_TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@local_EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	IF NOT (@local_EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			vp.INTIME,
			vp.OUTTIME,
			vp.SHIFT_ID,
			vp.HRSWORK,
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			vp.ActOTMins,
			vp.ActNormOT,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	
	--UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	--INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	--------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	--(
	--	SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
	--	(
	--		SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
	--		FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
	--	)
	--	AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
	--	WHERE
	--	(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
	--	AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	--)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	----------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	--(
	--	SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
	--	(
	--		SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
	--		FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
	--	)
	--	AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
	--	WHERE
	--	(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
	--	AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	--)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
	--												WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
	--												ELSE 0 END 
	--FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	DECLARE @POS AS INT  
	SET @POS = CHARINDEX(':',@local_MINWORKHOURS)  
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = SUBSTRING(@local_MINWORKHOURS,0,@POS)*60 + SUBSTRING(@local_MINWORKHOURS,@POS+1,2)  
	CREATE TABLE #TEMPDAILYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(5)
		,		
		PHOTO image,
		LocationName varchar(225)
	
	)
	--CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_INNOTATION_OUTNOTATION] ON [DBO].#TEMPDAILYATTENDANCE(FIRSTSESSION,SECONDSESSION,INNOTATION,OUTNOTATION) ON [PRIMARY]  
	--CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_DATE] ON [DBO].#TEMPDAILYATTENDANCE(FIRSTSESSION,SECONDSESSION,DATE) ON [PRIMARY]  
	IF (@local_MINWORKHOURS<>'') 

		BEGIN  
			DECLARE @SQLQUERYTEMP AS VARCHAR(MAX)    
			SET @SQLQUERYTEMP=''   
			SET @SQLQUERYTEMP =  'SELECT PD.EMPLOYEE_CODE_ID AS SWIPECARDNO,PD.DATE AS DATE,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALWORKMINS FROM TA_TBL_EMPLOYEE E '
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPDESIGNATION EDESIG ON E.EMPLOYEE_ID = EDESIG.EMPLOYEEID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' LEFT JOIN TA_TBL_SHIFT SH ON SH.SHIFT_ID = PD.SHIFT_ID '
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' WHERE  (	(E.EMPLOYEE_STATUS = 1) OR 	
			(E.EMPLOYEE_STATUS = 0 AND  CONVERT(NVARCHAR(11), E.INACTIVEDATE,102) >= CONVERT(NVARCHAR(11),PD.DATE,102)
			)) AND (E.ISDELETED = 0) AND (E.REPORT_EXCLUDE = 0)'
			INSERT INTO #EMPPROCESSEDDATA EXEC(@SQLQUERYTEMP)  
		END

	DECLARE @SQLQUERY AS VARCHAR(MAX)    

	SET @SQLQUERY=''    	

	SET @SQLQUERY = 'SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''PRESENT'' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''FN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END 
			ELSE PD.FNATTENDANCECODE
	END
	AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''PRESENT'' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''AN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END  
			ELSE PD.ANATTENDANCECODE
	END
	AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''')   +  SPACE(1) + ''#'' + ISNULL(E.Mobile_Number,'''')   AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
	WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
	ELSE PD.SUPPOSEDWORKHOURS END ''SUPPOSEDWORKHOURS'',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED'  
	SET @SQLQUERY = @SQLQUERY + ' ,(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
						 WHEN PD.SHIFT_ID=-1 THEN ''-''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''00:00''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.OFFOT IS NOT NULL	THEN
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 ELSE 0
	END OVERTIME,
	
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00''	THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''NORMOTMINS'',
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''WEEKOFFOTMINS'',
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''HOLIDAYOTMINS'',
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(NORMOT AS VARCHAR(50)) 
																		END 
		 END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(OFFOT AS VARCHAR(50)) 
																		END
		 END,
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																			ELSE CAST(HOLOT AS VARCHAR(50)) 
																	END
		 END,
	LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' ELSE OVERTIMESTATUS END,NIGHTORMORN,''00:00'',''00:00'',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CATEGORYNAME,WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),FNATTENDANCECODE,ANATTENDANCECODE,
	Case when FNATTENDANCECODE=ANATTENDANCECODE then 
					case	when ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
							else ANATTENDANCECODE
					end
		 else 
				case	when FNATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(FNATTENDANCECODE,1,1)
						else FNATTENDANCECODE
				end
				+''/''+
				case	when ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
						else ANATTENDANCECODE
				end
		end'
		 
	SET @SQLQUERY = @SQLQUERY  + ', isnull(E.PHOTO,''''),  isnull(LVL.name,'''')' 
	
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN  TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
	SET @SQLQUERY = @SQLQUERY + ' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID'  
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN  #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID '

	--two tables for showing location name
    SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN TA_tbl_ShiftAdd_Location LOC ON (convert(nvarchar,LOC.EmployeeId) = E.Employee_Id) and (PD.Date = LOC.ShiftDate) '
	SET @SQLQUERY = @SQLQUERY + ' LEFT OUTER JOIN TA_TBL_LEVELDETAILS LVL on (LVL.Id = LOC.LocationId) '
	
	
	IF (@local_MINWORKHOURS<>'')  
		 
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID'  
		END   
		SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0  and ('+ CAST(@local_LOCATIONID AS NVARCHAR(11)) +'= 0 or CAST(LOC.LocationId AS NVARCHAR(11)) ='+CAST(@local_LOCATIONID AS NVARCHAR(11))+') and ((E.EMPLOYEE_STATUS=1) 
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, ''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + ''', 102) AND PD.DATE <= CONVERT(DATETIME, ''' + CAST(@local_TODAT AS NVARCHAR(11)) + ''', 102)))'    
	IF(@local_USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @local_GRADELEVEL + ''  
		END	
	IF (@local_MINWORKHOURS<>'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + 'AND #EMPPROCESSEDDATA.TOTALWORKMINS >= ' + CAST(@TOTALMIN AS NVARCHAR(8))    
		END

    
	INSERT INTO #TEMPDAILYATTENDANCE EXEC(@SQLQUERY)	
	
	--select * from #TEMPDAILYATTENDANCE
	--UPDATE #TEMPDAILYATTENDANCE SET 
	--FIRSTSESSION=
	--	CASE	WHEN FIRSTSESSION IN('PRESENT','*PRESENT','HOLIDAY','*HOLIDAY','WEEKLY OFF','*WEEKLY OFF') AND INNOTATION='M' THEN  FIRSTSESSION+' #'	
	--			ELSE #TEMPDAILYATTENDANCE.FIRSTSESSION 
	--	END,
	--SECONDSESSION=
	--	CASE	WHEN SECONDSESSION IN('PRESENT','*PRESENT','HOLIDAY','*HOLIDAY','WEEKLY OFF','*WEEKLY OFF') AND OUTNOTATION='M' THEN  SECONDSESSION+' #'
	--			ELSE #TEMPDAILYATTENDANCE.SECONDSESSION 
	--	END
	--FROM #TEMPDAILYATTENDANCE
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()	

	DECLARE @CaseDecider AS INT

		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPDAILYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		PHOTO,
		LocationName,
		
		CASE		
		WHEN (FIRSTSESSION='Present' or SECONDSESSION='Present') THEN 1 
		WHEN (FIRSTSESSION='Absent' and SECONDSESSION='Absent') THEN   2 
		WHEN (FIRSTSESSION='WEEKLY OFF' or SECONDSESSION='WEEKLY OFF') THEN  3
		WHEN (FIRSTSESSION='HOLIDAY' or SECONDSESSION='HOLIDAY')  THEN 4
		ELSE 5 
		END as CaseDecider

		FROM #TEMPDAILYATTENDANCE ORDER BY CaseDecider
		

		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	

	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPDAILYATTENDANCE	
	
	  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Created By : Manjula .P     
Created on : 11-Apr-2014
Descriptions	: creating daily deviation report procedure based on monthly attendance report.
				: Kindly update this procedure when you update rptMonthlyAttendance procedure.
				[Proc_TA_RptDailyDeviation] '2016-07-01','2016-07-20','',0,'','0','0','Superadmin',0,'',0,0,0,'Both',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyDeviation]  
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	   
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@ParentID INT,
	@DesignationID int,
	@Gender varchar(10),
	@Export int
AS  
BEGIN
	SET NOCOUNT ON;
	--Temporary table's creation
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)	
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--insert in Temporary table	
	Declare @sqlCommon nvarchar(4000)
		--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	set @sqlCommon=''
	If Not (@EmployeeId = '')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id '
			End
	If Not (@EmployeeName = '')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id '
			End		
	DECLARE @sqlEmpLevel nVARCHAR(4000)	
	SET @sqlEmpLevel=
	'INSERT INTO #EmpLevel 	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from	(
	SELECT	max(el.EffectiveDate) as EffectiveDate,	el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId '
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nVARCHAR(50))+''', 102) and EL.LevelId is not null'			
	EXECUTE(@sqlEmpLevel)	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	create table #Leave
	(
		EmpId int,
		Leave_FromDate datetime,
		Hrs varchar(20)
	)
	Declare @sqlLeave varchar(max)
	set @sqlLeave='
	insert into #Leave select E.Employee_Id ,Leave_FromDate,
	case when LA.Status=''Approved'' then
	case when substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''.'',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))!=0
	then substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''.'',isnull(LA.NumberOfDays,0)))*8*60 + 
	4*60
	else
	substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''.'',isnull(LA.NumberOfDays,0)))*8*60 + 
	substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''.'',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))*4*60
	end
	else
	0 end
	as [Leave Hrs] 
	from TA_Tbl_Employee E 
	left join TA_Tbl_LeaveApplication LA on LA.Employee_Id=E.Employee_Id 
	left join TA_Tbl_ProcessedData pd on (pd.Date=LA.Leave_FromDate )'
	If Not (@EmployeeId = '')  
			BEGIN  
				SET @sqlLeave = @sqlLeave + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id '
			End
	If Not (@EmployeeName = '')  
			BEGIN  
				SET @sqlLeave = @sqlLeave + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id '
			End		
	set @sqlLeave= @sqlLeave+'
	where 
	convert(varchar(12),LA.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)  and
	LA.IsDeleted=0
	and pd.Date between CONVERT(DATETIME,'''+convert(varchar(50),@fromDat)+''', 102) and CONVERT(DATETIME,'''+convert(varchar(20),@ToDat)+''', 102)
	group by E.Employee_Id ,E.Employee_Code_Id,NumberOfDays,Leave_FromDate,LA.Status'
	Execute(@sqlLeave)
	create table #Permission
	(
	EmpId int,
	Permission_Date datetime,
	Hrs  varchar(20)
	)
	Declare @SQLPermission varchar(max)
	set @SQLPermission ='insert into #Permission
	select E.Employee_Id ,Permission_Date,
	case when C.Sat_WorkHrs<8 then 0 else
	case when P.Permission_Status=''Approved'' then 
	substring(Permission_Hours,0,charindex('':'',Permission_Hours))*60 + 
	substring(Permission_Hours,charindex('':'',Permission_Hours)+1,LEN(Permission_Hours))
	else
	0 
	end
	end
	as [Permission Hrs] 
	from TA_Tbl_Employee E 
	inner join #EmpCategory on #EmpCategory.EmployeeId=E.Employee_Id
	inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
	left join  TA_Tbl_Permission P on P.Employee_Id=E.Employee_Id
	left join TA_Tbl_ProcessedData pd on ( pd.Date=P.Permission_Date)	'
	If Not (@EmployeeId = '')  
			BEGIN  
				SET @SQLPermission = @SQLPermission + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id '
			End
	If Not (@EmployeeName = '')  
			BEGIN  
				SET @SQLPermission = @SQLPermission + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id '
			End		
	set @SQLPermission= @SQLPermission+
	' where 
	convert(varchar(12),P.Permission_Date,111)=convert(varchar(12), pd.Date,111)  and
	P.IsDeleted=0
	and pd.Date between CONVERT(DATETIME,'''+cast(@fromDat as nvarchar(50))+''', 102) and CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102)	
	group by E.Employee_Id ,E.Employee_Code_Id,Permission_Date,P.Permission_Status,Permission_Hours,C.Sat_WorkHrs'
	Execute(@SQLPermission)
	CREATE TABLE #TempAttendanceDetails (Employee_Id NVARCHAR(10), empName NVARCHAR(250),
	BranchName NVARCHAR(250), Designation NVARCHAR(250), Date datetime, InTime NVARCHAR(25), OutTime NVARCHAR(25), HrsWork NVARCHAR(10),
	Status NVARCHAR(50), TotalMinsWorked INT, Shift_ShortName VARCHAR(100), shift_TotalWorkingHours NVARCHAR(50), ValidWorkHrs BIT,
	WeekDayWrkHrs decimal(18,2),LeavePermissionHrs varchar(20),
	TargetWorkedHrs varchar(20),
	DeviationWorkedHrs varchar(20),
	EmployeeCategory nvarchar(50),
	TotaldeviationHrs varchar(20),
	Gender varchar(10), ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10)
	)	
	declare @sqlQuery as varchar(max)  
	set @sqlQuery=''  
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,
													isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,
													replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,
													replace(T.TitleName,''&amp;'',''&'') as Designation,
													convert(varchar(20),pd.date,101) as Date,
													pd.InTime,
													pd.OutTime,
													ISNULL(pd.HrsWork, ''-''),
													(pd.Attendance +  CASE pd.Status WHEN ''BL'' THEN '' - '' ELSE '''' END + isnull(pd.Status,'''')) as Status,
													((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))) as TotalMinsWorked'
	set @sqlQuery = @sqlQuery + ' ,(shf.Shift_ShortName + '' ('' + shf.Shift_StartTime + '' - ''  + shf.Shift_EndTime + '')'') as Shift_ShortName,
													shf.shift_TotalWorkingHours, 
	(CASE WHEN ((DATENAME(DW,pd.date) != ''Saturday'') AND (ISNULL(REPLACE(cat.WeekDay_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''Saturday'') AND (ISNULL(REPLACE(cat.Sat_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END) as ValidWorkHrs ' 
	set @sqlQuery = @sqlQuery + ' ,case when DATENAME(DW, pd.date)<>''Saturday'' then  REPLACE(cat.WeekDay_WorkHrs, ''.5'', ''.3'') else cat.Sat_WorkHrs end as [WeekDay_WorkHrs] ,
	convert(int,isnull(#Permission.Hrs,0))+convert(int,isnull(#Leave.Hrs,0)) as [Leave/Permission Hrs], 
	case when (pd.ANAttendanceCode=''Weekly Off'' or pd.ANAttendanceCode=''Holiday'') and (pd.FNAttendanceCode=''Holiday'' 
	or pd.FNAttendanceCode=''Weekly Off'') then 0 
	else  case when  DATENAME(DW, pd.date)<>''Saturday'' then  
	(convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''.'',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''.'',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	else (convert(int,cat.Sat_WorkHrs)*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	end   
	end as TargetWorkHrs ,
	case when (pd.ANAttendanceCode=''Weekly Off'' or pd.ANAttendanceCode=''Holiday'') 
	and (pd.FNAttendanceCode=''Holiday'' or pd.FNAttendanceCode=''Weekly Off'')  then 0 
	else  case when  DATENAME(DW, pd.date)<>''Saturday'' then   
	case  when ((convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''.'',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''.'',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))
			- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) 
			+ (substring(isnull(pd.HrsWork,''00:00''),4,2))))/60, ''0'')))>0  
			then ((convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''.'',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''.'',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
	convert(int,substring(pd.HrsWork,0,charindex('':'',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('':'',pd.HrsWork)+1,LEN(pd.HrsWork))))
		else 0 
	end 
	else  case  when ((cat.Sat_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))))/60, ''0'')))>0  
		then ((convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
	convert(int,substring(pd.HrsWork,0,charindex('':'',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('':'',pd.HrsWork)+1,LEN(pd.HrsWork))))
	else 0 
	end  
	end  
	end  as [DeviationWorkedHrs],
			cat.CategoryName,0,e.Gender, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')),
			ISNULL(SS.MaxWorkPlaceInHours, ''00:10''), NULL from Ta_Tbl_Employee e '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id'    
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '	
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'   
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'	
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay ON e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId '
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'
	SET @sqlQuery = @sqlQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId '
	set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Category cat on cat.CategoryId = TA_Tbl_EmployeeCategory.CategoryId '
	set @sqlQuery = @sqlQuery + ' left join #Leave on #Leave.Leave_FromDate=Pd.Date and  #Leave.EmpId=e.Employee_Id left join #Permission on #Permission.Permission_Date=Pd.Date and #Permission.EmpId=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId '		
		if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
	end	  
	If Not (@EmployeeId = '')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End	
	if(isnull(@Gender,'Both')<>'Both')
	begin
	set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	--if(@EmpAutoId > 0)
	--BEGIN
	--	set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
	--END
	if(@fromDat!='' and @ToDat!='')
	begin
	set @sqlQuery = @sqlQuery + ' and((pd.date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102)))'   
	end
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'   
	INSERT INTO #TempAttendanceDetails 
	exec(@sqlQuery) 
	--select * from #TempAttendanceDetails 
	INSERT INTO @TempExecptionHrs
	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	WHERE [Date] BETWEEN @FromDat AND @ToDat
	GROUP BY EmployeeCodeId, [Date];
	UPDATE #TempAttendanceDetails SET
	HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
	TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
	DeviationWorkedHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN EH.TotalHrs ELSE (AD.DeviationWorkedHrs + EH.TotalHrs) END) ELSE DeviationWorkedHrs END)
	FROM #TempAttendanceDetails AD
	RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Id AND EH.[Date] = AD.[Date] 
	--select * from #TempAttendanceDetails where DeviationWorkedHrs>0
	create table #TotalDeviation(Id int identity(1,1),Employee_Code varchar(50),totalDeviation varchar(20))
	if not(@EmployeeId='')  
	begin  
		insert into #TotalDeviation
		select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 and Employee_Id in (select value from split(@EmployeeId,','))
		group by Employee_Id
	end 		
	else
	begin
		insert into #TotalDeviation
		select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
		group by Employee_Id
	end
		--select * from #TotalDeviation 
		--Get current date time format.
		DECLARE @dateFormat as int
		DECLARE @date as nvarchar(25)			
		SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
		IF(@date='dd/MM/yyyy')
			BEGIN
				SET @dateFormat = 103
			END
		ELSE IF(@date='MM/dd/yyyy')
			BEGIN
				SET @dateFormat = 101
			END
		ELSE
			BEGIN
				SET @dateFormat = 106
			END	
		declare @count int;
		set @count=(select COUNT(*) from #TotalDeviation)
		while(@count>0)
		begin 
			update #TempAttendanceDetails set TotaldeviationHrs=(select convert(int,totalDeviation) from #TotalDeviation where Employee_Code = (select top 1 Employee_Id from #TotalDeviation where Id=@count))
			set @count=@count-1;
		end
		if(@Export=0)
		begin
			SELECT  Employee_Id , empName ,
		BranchName , Designation , 
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Date, @dateFormat) 
		end AS Date
		, InTime , OutTime , HrsWork ,
		Status , TotalMinsWorked , Shift_ShortName , shift_TotalWorkingHours , ValidWorkHrs ,	
		'0' + REPLACE(WeekDayWrkHrs, '.', ':') WeekDayWrkHrs ,
		case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
		'0'+ convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
		'0'+ convert(varchar(20),LeavePermissionHrs/60)+':'+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
		else
		convert(varchar(20),LeavePermissionHrs/60) +':'+convert(varchar(20),LeavePermissionHrs%60) 
		end 
		as
		LeavePermissionHrs,
		case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
		'0'+ convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
		'0'+ convert(varchar(20),TargetWorkedHrs/60)+':'+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
		convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
		else
		convert(varchar(20),TargetWorkedHrs/60) +':'+convert(varchar(20),TargetWorkedHrs%60) 
		end 
		as TargetWorkedHrs ,
		case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
		'0'+ convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
		'0'+ convert(varchar(20),DeviationWorkedHrs/60)+':'+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
		convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
		else
		convert(varchar(20),DeviationWorkedHrs/60)+':' +convert(varchar(20),DeviationWorkedHrs%60) 
		end 
		as 
		DeviationWorkedHrs,
		EmployeeCategory,
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60)+':'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +':'+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs,Gender FROM #TempAttendanceDetails 
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
		end
		else
		begin
			SELECT 
			dense_rank()over(order by BranchName,EMPLOYEE_ID) as [Sl.No],
			BranchName as level,Employee_Id as [Emp. No], empName as [Employee Name],
			Designation ,Gender ,EmployeeCategory as [Employee Category], 
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, Date, @dateFormat) 
			end AS Date
			,		
			'0' + REPLACE(WeekDayWrkHrs, '.', ':') as [Daily Minimum Working Hrs],
			case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
			'0'+ convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
			when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
			'0'+ convert(varchar(20),LeavePermissionHrs/60)+':'+convert(varchar(20),LeavePermissionHrs%60) 
			when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
			convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
			else
			convert(varchar(20),LeavePermissionHrs/60) +':'+convert(varchar(20),LeavePermissionHrs%60) 
			end 
			as
			[Leave/Permission Hrs],
			case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
			'0'+ convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
			when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
			'0'+ convert(varchar(20),TargetWorkedHrs/60)+':'+convert(varchar(20),TargetWorkedHrs%60) 
			when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
			convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
			else
			convert(varchar(20),TargetWorkedHrs/60) +':'+convert(varchar(20),TargetWorkedHrs%60) 
			end 
			as [Target Worked Hrs],
			HrsWork as [Actual Worked Hrs],
			case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
			'0'+ convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
			when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
			'0'+ convert(varchar(20),DeviationWorkedHrs/60)+':'+convert(varchar(20),DeviationWorkedHrs%60) 
			when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
			convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
			else
			convert(varchar(20),DeviationWorkedHrs/60)+':' +convert(varchar(20),DeviationWorkedHrs%60) 
			end 
			as 
			[Deviated Hrs],
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60)+':'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +':'+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs FROM #TempAttendanceDetails 
			where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 order by BranchName,Employee_Id 
		end
		--select * from #EmployeeIds
		--Remove the temporary tables here   
		drop table #EmpLevel
		drop table #EmpDesignation
		drop table #EmpType
		drop table #EmpCategory	
		drop table #EmployeeIds
		DROP TABLE #TempAttendanceDetails
		drop table #leave
		drop table #permission
		drop table #LevelRights
		drop table #TotalDeviation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation_New]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select * from TA_Tbl_ProcessedData where Employee_Code_Id='ang1' and Date='2013-05-03'
/*  
Procedure Name : Proc_TA_RptDailyDeviation_New 
Proc_TA_RptDailyDeviation_New '06/01/2014','06/20/2014','','0','',0,0,'SuperAdmin',0,'',''
Tables  : TA_Tbl_Employee and TA_Tbl_ProcessedData  
Created By : Manjula .P     
Created on : 17-May-2013
Descriptions	: creating daily deviation report procedure based on monthly attendance report.
				: Kindly update this procedure when you update rptMonthlyAttendance procedure.
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyDeviation_New]  
 --@MinWorkHours as varchar(10), 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),	   
 @EmpSwipeCard varchar(20),
 @EmpAutoId bigint
AS  
BEGIN  
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
DECLARE @TempExecptionHrs TABLE(Employee_Code_Id BIGINT, [Date] DATETIME, TotalHrs BIGINT)
create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate],[PayId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
create table #Leave
(
EmpId int,
Leave_FromDate datetime,
Hrs varchar(20)
)
insert into #Leave
select E.Employee_Id ,Leave_FromDate,
case when LA.Status='Approved' then 	
 case when substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex('.',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))!=0
		then substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex('.',isnull(LA.NumberOfDays,0)))*8*60 + 
		4*60
	else
		substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex('.',isnull(LA.NumberOfDays,0)))*8*60 + 
 substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex('.',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))*4*60
 end
else
0 end
as [Leave Hrs] 
from TA_Tbl_Employee E 
left join TA_Tbl_LeaveApplication LA on LA.Employee_Id=E.Employee_Id 
left join TA_Tbl_ProcessedData pd on (pd.Date=LA.Leave_FromDate )
--inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id and EC.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)
where 
 convert(varchar(12),LA.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)  and
 LA.IsDeleted=0
and pd.Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--and (Permission_Status='Approved' or LA.Status='Approved')
group by E.Employee_Id ,E.Employee_Code_Id,NumberOfDays,Leave_FromDate,LA.Status
create table #Permission
(
EmpId int,
Permission_Date datetime,
Hrs  varchar(20)
)
insert into #Permission
select E.Employee_Id ,Permission_Date,
case when C.Sat_WorkHrs<8 then 0 else
case when P.Permission_Status='Approved' then 
 substring(Permission_Hours,0,charindex(':',Permission_Hours))*60 + 
 substring(Permission_Hours,charindex(':',Permission_Hours)+1,LEN(Permission_Hours))
else
0 
end
end
as [Permission Hrs] 
from TA_Tbl_Employee E 
inner join #EmpCategory on #EmpCategory.EmployeeId=E.Employee_Id
inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
left join  TA_Tbl_Permission P on P.Employee_Id=E.Employee_Id
left join TA_Tbl_ProcessedData pd on ( pd.Date=P.Permission_Date)
--inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id and EC.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)
where 
 convert(varchar(12),P.Permission_Date,111)=convert(varchar(12), pd.Date,111)  and
 P.IsDeleted=0
and pd.Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--and (Permission_Status='Approved' or LA.Status='Approved')
group by E.Employee_Id ,E.Employee_Code_Id,Permission_Date,P.Permission_Status,Permission_Hours,C.Sat_WorkHrs
--select * from #Leave
--select * from #Permission where EmpId=52
	CREATE TABLE #TempAttendanceDetails (FirstSession NVARCHAR(15), SecondSession NVARCHAR(15), Employee_Id NVARCHAR(10), empName NVARCHAR(250),
		BranchName NVARCHAR(250), Designation NVARCHAR(250), Date VARCHAR(20), InTime NVARCHAR(25), OutTime NVARCHAR(25), HrsWork NVARCHAR(10),
		Status NVARCHAR(50), TotalMinsWorked INT, Shift_ShortName VARCHAR(100), shift_TotalWorkingHours NVARCHAR(50), ValidWorkHrs BIT,
		WeekDayWrkHrs decimal(18,2),LeavePermissionHrs varchar(20),
		TargetWorkedHrs varchar(20),
		DeviationWorkedHrs varchar(20),
		EmployeeCategory nvarchar(50),
		TotaldeviationHrs varchar(20), ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10)
		)	
    declare @sqlQuery as varchar(max)  
  	set @sqlQuery=''  
  	set @sqlQuery = 'select  pd.fnAttendanceCode + case  when pd.Status is null then '''' else ''(BL)'' end as FirstSession,pd.anAttendanceCode + case  when pd.Status is null then '''' else ''(BL)'' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,convert(varchar(20),pd.date,101) as Date,pd.InTime,pd.OutTime,ISNULL(pd.HrsWork, ''-''),(pd.Attendance +  CASE pd.Status WHEN ''BL'' THEN '' - '' ELSE '''' END + isnull(pd.Status,'''')) as Status,((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))) as TotalMinsWorked'
	set @sqlQuery = @sqlQuery + ' ,(shf.Shift_ShortName + '' ('' + shf.Shift_StartTime + '' - ''  + shf.Shift_EndTime + '')'') as Shift_ShortName,shf.shift_TotalWorkingHours, (CASE WHEN ((DATENAME(DW,pd.date) != ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END) as ValidWorkHrs ' 
	set @sqlQuery = @sqlQuery + ' ,case when DATENAME(DW, pd.date)<>''Saturday'' then  cat.WeekDay_WorkHrs else cat.Sat_WorkHrs end as [WeekDay_WorkHrs] ,
	convert(int,isnull(#Permission.Hrs,0))+convert(int,isnull(#Leave.Hrs,0)) as [Leave/Permission Hrs], 
	case when (pd.ANAttendanceCode=''Weekly Off'' or pd.ANAttendanceCode=''Holiday'') and (pd.FNAttendanceCode=''Holiday'' 
	          or pd.FNAttendanceCode=''Weekly Off'') then 0 
		 else  case when  DATENAME(DW, pd.date)<>''Saturday'' then  
						 (convert(int,cat.WeekDay_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
				    else (convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	           end   
		 end as TargetWorkHrs ,
	case when (pd.ANAttendanceCode=''Weekly Off'' or pd.ANAttendanceCode=''Holiday'') 
	          and (pd.FNAttendanceCode=''Holiday'' or pd.FNAttendanceCode=''Weekly Off'')  then 0 
	     else  case when  DATENAME(DW, pd.date)<>''Saturday'' then   
	                      case  when ((cat.WeekDay_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))
									- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) 
									+ (substring(isnull(pd.HrsWork,''00:00''),4,2))))/60, ''0'')))>0  
									then ((convert(int,cat.WeekDay_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
convert(int,substring(pd.HrsWork,0,charindex('':'',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('':'',pd.HrsWork)+1,LEN(pd.HrsWork))))
								else 0 
							end 
			   else  case  when ((cat.Sat_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))))/60, ''0'')))>0  
			                    then ((convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
convert(int,substring(pd.HrsWork,0,charindex('':'',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('':'',pd.HrsWork)+1,LEN(pd.HrsWork))))
							else 0 
					 end  
				end  
	end  as [DeviationWorkedHrs],
	                               cat.CategoryName,0, DATEDIFF(MI, ''00:00'', ISNULL(''00:05'', ''00:05'')),ISNULL(''00:05'', ''00:05''), NULL  from Ta_Tbl_Employee e '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id'    
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
  	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '	
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'   
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
  	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay ON e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId '
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'
    set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Category cat on cat.CategoryId = TA_Tbl_EmployeeCategory.CategoryId '
    set @sqlQuery = @sqlQuery + ' left join #Leave on #Leave.Leave_FromDate=Pd.Date and  #Leave.EmpId=e.Employee_Id left join #Permission on #Permission.Permission_Date=Pd.Date and #Permission.EmpId=e.Employee_Id '
    --' left join #LeavePermission  on #LeavePermission.EmpId = e.Employee_Id and  (convert(varchar(12),#LeavePermission.Permission_Date,111)=convert(varchar(12), pd.Date,111) or  convert(varchar(12),#LeavePermission.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)) '
    --set @sqlQuery = @sqlQuery + ' left join TA_Tbl_LeaveApplication  on TA_Tbl_LeaveApplication.Employee_Id = e.Employee_Id and  convert(varchar(12),TA_Tbl_LeaveApplication.Leave_FromDate,111)=convert(varchar(12), pd.Date,111) '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	if not(@EmployeeName='')  
		begin  
			set @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName + isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end 
	if not(@EmployeeId='')  
		begin  
			set @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
		end 
	If Not (@EmpSwipeCard = '')  
			 Begin  
			  Set @sqlQuery = @sqlQuery + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			 End
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
		end
    if(@EmpAutoId = 0)
	    BEGIN
			if not(@LevelID='' or @LevelID='0')  
			begin  
			   set @sqlQuery = @sqlQuery + ' And (#EmpLevel.levelId In (' + @LevelID + '))'  
			End
		END
		ELSE
			BEGIN
			   set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
			END
    if(@fromDat!='' and @ToDat!='')
		begin
			set @sqlQuery = @sqlQuery + ' and((pd.date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102)))'   
		end
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'   
	INSERT INTO #TempAttendanceDetails exec(@sqlQuery) 
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDat AND @ToDat
	GROUP BY EmployeeCodeId, [Date];
	UPDATE #TempAttendanceDetails SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
		DeviationWorkedHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN EH.TotalHrs ELSE (AD.DeviationWorkedHrs + EH.TotalHrs) END) ELSE DeviationWorkedHrs END)
	FROM #TempAttendanceDetails AD
		RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Id AND EH.[Date] = AD.[Date] 
	--select * from #TempAttendanceDetails where DeviationWorkedHrs>0
	----WHERE ValidWorkHrs = 1 AND
	---- ((FirstSession NOT IN ('Present', 'Absent', 'Holiday', 'Weekly Off') AND SecondSession = 'Present')
	----	OR (SecondSession NOT IN ('Present', 'Absent', 'Holiday', 'Weekly Off') AND FirstSession = 'Present'))
	---- AND TotalMinsWorked >= 240
	----UPDATE #TempAttendanceDetails SET ValidWorkHrs = 0 WHERE HrsWork = '-' 
	---- SELECT FirstSession,SecondSession,Employee_Id,empName,BranchName,Designation,Date,InTime,OutTime,HrsWork,Status,TotalMinsWorked,Shift_ShortName,shift_TotalWorkingHours,ValidWorkHrs,replace (WeekDayWrkHrs,'.',':') as WeekDayWrkHrs,replace (LeavePermissionHrs,'.',':') as LeavePermissionHrs,REPLACE(TargetWorkedHrs,'.',':') as TargetWorkedHrs , 
	--case when len(DeviationWorkedHrs)=4 then  RIGHT(0,DeviationWorkedHrs) else DeviationWorkedHrs end as DeviationWorkedHrs,EmployeeCategory FROM #TempAttendanceDetails where Date between @fromDat and @ToDat and DeviationWorkedHrs>0
	create table #TotalDeviation(Id int identity(1,1),Employee_Code varchar(50),totalDeviation varchar(20))
	if not(@EmployeeId='')  
		begin  
		insert into #TotalDeviation
			select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 and Employee_Id in (select value from split(',',@EmployeeId))
	group by Employee_Id
		end 
		else
			insert into #TotalDeviation
	select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
	group by Employee_Id
	--select * from #TotalDeviation 
	declare @count int;
	set @count=(select COUNT(*) from #TotalDeviation)
	while(@count>0)
	begin 
	update #TempAttendanceDetails set TotaldeviationHrs=(select convert(int,totalDeviation) from #TotalDeviation where Employee_Code = (select top 1 Employee_Id from #TotalDeviation where Id=@count))
	set @count=@count-1;
	end
	SELECT FirstSession , SecondSession, Employee_Id , empName ,
		BranchName , Designation , Date , InTime , OutTime , HrsWork ,
		Status , TotalMinsWorked , Shift_ShortName , shift_TotalWorkingHours , ValidWorkHrs ,
		--case when len(WeekDayWrkHrs/60)=1 and len(WeekDayWrkHrs%60)=1 then 
		--'0'+ convert(varchar(20),WeekDayWrkHrs/60) +':0'+convert(varchar(20),WeekDayWrkHrs%60) 
		--when len(WeekDayWrkHrs/60)=1 and len(WeekDayWrkHrs%60)!=1 then 
		--'0'+ convert(varchar(20),WeekDayWrkHrs/60)+':'+convert(varchar(20),WeekDayWrkHrs%60) 
		--when len(WeekDayWrkHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		--convert(varchar(20),WeekDayWrkHrs/60) +':0'+convert(varchar(20),WeekDayWrkHrs%60) 
		--else
		--convert(varchar(20),WeekDayWrkHrs/60) +':'+convert(varchar(20),WeekDayWrkHrs%60) 
		--end 
		--  as
		WeekDayWrkHrs ,
		case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
		'0'+ convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
		'0'+ convert(varchar(20),LeavePermissionHrs/60)+':'+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		convert(varchar(20),LeavePermissionHrs/60) +':0'+convert(varchar(20),LeavePermissionHrs%60) 
		else
		convert(varchar(20),LeavePermissionHrs/60) +':'+convert(varchar(20),LeavePermissionHrs%60) 
		end 
		  as
		  LeavePermissionHrs,
		case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
		'0'+ convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
		'0'+ convert(varchar(20),TargetWorkedHrs/60)+':'+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
		convert(varchar(20),TargetWorkedHrs/60) +':0'+convert(varchar(20),TargetWorkedHrs%60) 
		else
		convert(varchar(20),TargetWorkedHrs/60) +':'+convert(varchar(20),TargetWorkedHrs%60) 
		end 
		  as TargetWorkedHrs ,
		case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
		'0'+ convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
		'0'+ convert(varchar(20),DeviationWorkedHrs/60)+':'+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
		convert(varchar(20),DeviationWorkedHrs/60) +':0'+convert(varchar(20),DeviationWorkedHrs%60) 
		else
		convert(varchar(20),DeviationWorkedHrs/60)+':' +convert(varchar(20),DeviationWorkedHrs%60) 
		end 
		as 
		DeviationWorkedHrs,
		EmployeeCategory,
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		'0'+ convert(varchar(20),TotaldeviationHrs/60)+':'+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +':0'+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +':'+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs FROM #TempAttendanceDetails 
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpPay 
	drop table #EmpProcessedData
	drop table #EmployeeIds
	DROP TABLE #TempAttendanceDetails
	--drop table #LeavePermission
	drop table #leave
drop table #permission
	--drop table #TotalDeviation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [Proc_TA_RptDailyLeaves] '01/May/2014','3','P',0,0,0,3,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeaves]  
 @fromDat datetime,  
 @LevelID varchar(8000),  
 @IntimationType varchar(1),  
 @EmpAutoId bigint,
 @ReportingTo bigint,
 @SanctioningAuthority bigint,
 @ParentId int,
 @UserGroupName varchar(250)
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
--Temporary table's creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
 --Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.  
 create table #EmployeeIds(EmpAutoId int)  
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId    
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Basic Pay Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay]   
(  
 [PayId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--Employee Pay insert in Temporary table  
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (  
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep  
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpBpay  
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId  
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null  
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''    
  set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, '  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '  
  set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name'  
  set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'  
  set @sqlQuery = @sqlQuery + ' left outer JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'  
     set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'  
  set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ' 
   set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '	 
 --dbo.TA_Tbl_LeaveApplication.Type=''Leave'' and   
  set @sqlQuery = @sqlQuery + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '  
  set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ' 
  set @sqlQuery = @sqlQuery + ' AND ((dbo.TA_Tbl_LeaveApplication.Leave_FromDate >= CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) ) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate >=CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))  + ''', 102)  ))'  
  --      if(@EmpAutoId = 0)  
		--	  BEGIN   
		--		   if not(@LevelID='' or @LevelID='0')  
		--		   begin  
		--			set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'  
		--		   end   
		--	  END  
		--ELSE  
 if(@EmpAutoId > 0)
	BEGIN  
		set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '    
	END  
  if (@IntimationType='P') --planned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.status<>''Rejected'' and TA_Tbl_LeaveApplication.IntimationType=''P'' '   end    
  if (@IntimationType='U') -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.status<>''Rejected'' and  TA_Tbl_LeaveApplication.IntimationType <> ''P'' '  
  end  
   --based on reporting to
    if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
  end  
create table #EmpLeave(Employee_Id varchar(15),  
applicationDate datetime,  
fromDate datetime,  
todate datetime,  
NumberOfDays decimal(18,1),  
leavetype varchar(100),  
Leave_SessionFrom varchar(100),  
Leave_SessionTo varchar(100),  
Reason varchar(1050),  
status varchar(50),  
Remarks varchar(1050),  
TitleName varchar(500),  
empname varchar(500),  
[name] varchar(500),  
)  
insert into #EmpLeave exec(@sqlQuery)  
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)  
select empname as 'Executive Name',name as Department,fromDate as 'FromDate',toDate as ToDate,  
NumberOfDays, Leave_SessionFrom, Leave_SessionTo,status  
 from #EmpLeave order by fromDate,name,Employee_Id asc  
--select * from #EmpLeave order by Employee_Id,fromDate asc  
drop table #EmpLeave  
--Remove the temporary tables here    
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #EmpPay  
drop table #EmployeeIds  
	 drop table #LevelRights
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves_Email]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [Proc_TA_RptDailyLeaves] '01/May/2014','3','P',0,0,0,3,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeaves_Email]  
 @fromDat datetime,  
 @LevelID varchar(8000),  
 @IntimationType varchar(1),  
 @EmpAutoId bigint,
 @ReportingTo bigint,
 @SanctioningAuthority bigint,
 @ParentId int,
 @UserGroupName varchar(250)
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
--Temporary table's creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
 --Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.  
 create table #EmployeeIds(EmpAutoId int)  
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId    
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Basic Pay Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay]   
(  
 [PayId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--Employee Pay insert in Temporary table  
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (  
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep  
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpBpay  
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId  
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null  
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''    
  set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, '  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '  
  set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name'  
  set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'  
  set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'  
  set @sqlQuery = @sqlQuery + ' left outer JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'  
     set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'  
  set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'  
  set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '  
  set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ' 
   set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '	 
 --dbo.TA_Tbl_LeaveApplication.Type=''Leave'' and   
  set @sqlQuery = @sqlQuery + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '  
  set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ' 
  set @sqlQuery = @sqlQuery + ' AND ((dbo.TA_Tbl_LeaveApplication.Leave_FromDate >= CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) ) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate >=CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))  + ''', 102)  ))'  
  --      if(@EmpAutoId = 0)  
		--	  BEGIN   
		--		   if not(@LevelID='' or @LevelID='0')  
		--		   begin  
		--			set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'  
		--		   end   
		--	  END  
		--ELSE  
 if(@EmpAutoId > 0)
	BEGIN  
		set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '    
	END  
  if (@IntimationType='P') --planned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.status<>''Rejected'' and TA_Tbl_LeaveApplication.IntimationType=''P'' '   end    
  if (@IntimationType='U') -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.status<>''Rejected'' and  TA_Tbl_LeaveApplication.IntimationType <> ''P'' '  
  end  
   --based on reporting to
    if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
   set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
  end  
create table #EmpLeave(Employee_Id varchar(15),  
applicationDate datetime,  
fromDate datetime,  
todate datetime,  
NumberOfDays decimal(18,1),  
leavetype varchar(100),  
Leave_SessionFrom varchar(100),  
Leave_SessionTo varchar(100),  
Reason varchar(1050),  
status varchar(50),  
Remarks varchar(1050),  
TitleName varchar(500),  
empname varchar(500),  
[name] varchar(500),  
)  
insert into #EmpLeave exec(@sqlQuery)  
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)  
select empname as 'Executive Name',name as Department,fromDate as 'FromDate',toDate as ToDate,  
NumberOfDays, Leave_SessionFrom, Leave_SessionTo,status  
 from #EmpLeave order by fromDate,name,Employee_Id asc  
--select * from #EmpLeave order by Employee_Id,fromDate asc  
drop table #EmpLeave  
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #EmpPay  
drop table #EmployeeIds  
	 drop table #LevelRights
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeavesUnplanned]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- ALTER  date:
-- Description:	
-- Modified By : 
-- Modified On : 
-- Description :
-- [Proc_TA_RptDailyLeavesUnplanned] '02/09/2010','1,2,3,4,5,6,7','P'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeavesUnplanned]
	@fromDat datetime,
	@LevelID varchar(8000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''		
		set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, '
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name'
		set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' where dbo.TA_Tbl_LeaveApplication.Type=''Leave'' and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlQuery = @sqlQuery + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102)))'
		if not(@LevelID='' or @LevelID='0')
		begin
			set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
		end	
		declare @IntimationType as varchar(1)
		set @IntimationType='U'
		if (@IntimationType='P') --planned leave
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.IntimationType=''P'' '
		end		
		if (@IntimationType='U') -- unplanned leave
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_LeaveApplication.IntimationType <> ''P'' '
		end
create table #EmpLeave(Employee_Id varchar(15),
applicationDate datetime,
fromDate datetime,
todate datetime,
NumberOfDays decimal(18,1),
leavetype varchar(100),
Leave_SessionFrom varchar(100),
Leave_SessionTo varchar(100),
Reason varchar(1050),
status varchar(50),
Remarks varchar(1050),
TitleName varchar(500),
empname varchar(500),
[name] varchar(500),
)
insert into #EmpLeave exec(@sqlQuery)
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
select empname as 'Executive Name',name as Department,fromDate as 'FromDate',toDate as ToDate from #EmpLeave order by fromDate,Employee_Id asc
--select * from #EmpLeave order by Employee_Id,fromDate asc
drop table #EmpLeave
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_RptDailyPermission '01/Jun/2010','3','P',0,0,0,3,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyPermission]
(    
	@fromDat datetime,	
	@LevelID varchar(8000),	
	@Type varchar(1),
	@EmpAutoId bigint,
	@ReportingTo bigint,
	@SanctioningAuthority bigint,
	@ParentId int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
	[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
	[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Basic Pay Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
	(
	[PayId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
		--Employee Level insert in Temporary table
		insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) ELevel
		inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
		--Employee Designation insert in Temporary table
		insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
		--Employee Type insert in Temporary table
		insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
		--Employee Category insert in Temporary table
		insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		--Employee Pay insert in Temporary table
		insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
		select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
		inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpBpay
		inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
		AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(MAX)
		set @sqlQuery=''		
		set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_MiddleName,'''')  +  space(1) + isnull(e.Employee_LastName,'''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation,TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,convert(varchar(5),DateAdd(minute,datediff(mi,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime),0),108) as TotalHours from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'		
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '		
		set @sqlQuery = @sqlQuery + ' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 and e.employee_Status=1	and TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) '
		if (@Type='U')
			begin
				set @sqlQuery = @sqlQuery + ' And (TA_Tbl_Permission.UnPlanned=1) and TA_Tbl_Permission.Permission_Status<>''Rejected'' '
			End
		else
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_Permission.Permission_Status<>''Rejected'' and (TA_Tbl_Permission.UnPlanned=0) and (TA_Tbl_Permission.UnPlanned is not null) '
			End
		if(@EmpAutoId > 0)
			BEGIN
				set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
			END
		--based on reporting to
		if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + ' and e.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
			end  
		--based on Sanctioning Person to
		if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + ' and e.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
			end  
		--based on Sanctioning Person to
		if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + ' and e.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
				set @sqlQuery = @sqlQuery + ' and e.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
			end  
		set @sqlQuery = @sqlQuery + ' Group by TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_MiddleName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName order by TA_Tbl_Permission.Permission_Date, Ta_Tbl_levelDetails.name,e.Employee_Code_Id,e.Employee_FirstName,TA_Tbl_Title.TitleName ASC'	
		exec(@sqlQuery)
		--Remove the temporary tables here  
		drop table #EmpLevel
		drop table #EmpDesignation
		drop table #EmpType
		drop table #EmpCategory
		drop table #EmpPay
		drop table #EmployeeIds
		drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission_email]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_RptDailyPermission '01/Jun/2010','3','P',0,0,0,3,'SuperAdmin'
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyPermission_email]
 (    
    @fromDat datetime,	
	@LevelID varchar(8000),	
	@Type varchar(1),
	@EmpAutoId bigint,
	@ReportingTo bigint,
	@SanctioningAuthority bigint,
    @ParentId int,
	@UserGroupName varchar(250)
 )
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''		
		set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_MiddleName,'''')  +  space(1) + isnull(e.Employee_LastName,'''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation,TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,convert(varchar(5),DateAdd(minute,datediff(mi,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime),0),108) as TotalHours from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'		
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID'
   		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '		
		set @sqlQuery = @sqlQuery + ' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 and e.employee_Status=1	and TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) '
		if (@Type='U')
			begin
				set @sqlQuery = @sqlQuery + ' And (TA_Tbl_Permission.UnPlanned=1) and TA_Tbl_Permission.Permission_Status<>''Rejected'' '
			End
		else
			begin
				set @sqlQuery = @sqlQuery + ' and TA_Tbl_Permission.Permission_Status<>''Rejected'' and (TA_Tbl_Permission.UnPlanned=0) and (TA_Tbl_Permission.UnPlanned is not null) '
			End
			if(@EmpAutoId > 0)
		   BEGIN
			  set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
		   END
		   --based on reporting to
			if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + ' and e.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
		  end  
		   --based on Sanctioning Person to
			if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + ' and e.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
		  end  
		   --based on Sanctioning Person to
			if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + ' and e.Leave_Sanc_Authority = ' + cast(@SanctioningAuthority as nvarchar(50)) 
		   set @sqlQuery = @sqlQuery + ' and e.Reporting_To = ' + cast(@ReportingTo as nvarchar(50)) 
		  end  
		set @sqlQuery = @sqlQuery + ' Group by TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_MiddleName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName order by TA_Tbl_Permission.Permission_Date, Ta_Tbl_levelDetails.name,e.Employee_Code_Id,e.Employee_FirstName,TA_Tbl_Title.TitleName ASC'	
	        exec(@sqlQuery)
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyWagesPenalty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
[Proc_TA_RptDailyWagesPenalty] @FROMDAT='2020-01-21 00:00:00',@TODAT='2020-02-20 00:00:00',
@EMPLOYEENAME=N'',@LEVELID=N'',@EMPLOYEEID=N'57090',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'0',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N'BOTH',@SHIFT=0,@EMPAUTOID=0,@isDetailed_Summary=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyWagesPenalty]
(   
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@EMPAUTOID BIGINT=0,
	@isDetailed_Summary bit=0	
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_EMPAUTOID BIGINT
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		Shift_DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		EARLYOUTMIN INT,
		CompanyID INT,
		isRemove_LateIn int,
		isRemove_EarlyOut int
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF not(@local_GENDER='BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@local_GENDER AS NVARCHAR(8)) + ''' '  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@local_TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@local_EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	IF NOT (@local_EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			LATEINMINS,
			EARLYOUT,
			LATEIN,
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			#EMPLEVEL.LEVELID,
			0,
			0
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  	
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and(isnull(LateInMins,0)!=0 or isnull(EarlyOutMins,0)!=0)
	and(FNAttendanceCode='Present' and ANAttendanceCode='Present')
	order by vp.EMPLOYEE_CODE_ID,Date

	
	update #TEMPPROCESSEDDATA set CompanyID=dbo.[Func_TA_GetParentIds](CompanyID)
	,LATEINMIN=case when isRemove_LateIn=1 then 0 else LATEINMIN end
	,EARLYOUTMIN=case when isRemove_EarlyOut=1 then 0 else EARLYOUTMIN end	
	
	update #TEMPPROCESSEDDATA set isRemove_LateIn=a.rowNumber from #TEMPPROCESSEDDATA TP
	inner join
	(	
		select rowNumber=ROW_NUMBER() over(partition by EMPLOYEE_CODE_ID order by EMPLOYEE_CODE_ID,shift_date),Shift_DATE,
		EMPLOYEE_CODE_ID
		from #TEMPPROCESSEDDATA 	where LATEINMIN!=0
	)as a on (TP.EMPLOYEE_CODE_ID=a.EMPLOYEE_CODE_ID and TP.Shift_DATE=a.Shift_DATE)
	
	update #TEMPPROCESSEDDATA set isRemove_EarlyOut=a.rowNumber from #TEMPPROCESSEDDATA TP
	inner join
	(	
		select rowNumber=ROW_NUMBER() over(partition by EMPLOYEE_CODE_ID order by EMPLOYEE_CODE_ID,shift_date),Shift_DATE,
		EMPLOYEE_CODE_ID
		from #TEMPPROCESSEDDATA 	where EARLYOUTMIN!=0
	)as a on (TP.EMPLOYEE_CODE_ID=a.EMPLOYEE_CODE_ID and TP.Shift_DATE=a.Shift_DATE)
	
	--update #TEMPPROCESSEDDATA set LATEINMIN=0 where isRemove_LateIn=1	
	--update #TEMPPROCESSEDDATA set EARLYOUTMIN=0 where isRemove_EarlyOut=1	
	
	--select * from #TEMPPROCESSEDDATA 
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		Shift_DATE DATETIME,
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		CompanyID INT,
		Category int,
		BasicSalary decimal(18,3) default(0),
		LateInDeduction decimal(18,3) default(0),
		EarlyOutDeduction decimal(18,3) default(0),
		WhichDuration int default(0),
		Whichpercentage int default(0)
	)
	
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,
	REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.Shift_DATE,101) AS DATE,
	PD.EARLYOUT,
	PD.LATEIN,
	LATEINMIN,
	EARLYOUTMIN,
	CompanyID,
	E.penalty,
	E.Basic_Salary,0,0,0,0'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID '
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.Shift_DATE,102)) )
		AND((PD.Shift_DATE >= CONVERT(DATETIME, ''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + ''', 102) AND PD.Shift_DATE <= CONVERT(DATETIME, ''' + CAST(@local_TODAT AS NVARCHAR(11)) + ''', 102)))'    
	IF(@local_USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @local_GRADELEVEL + ''  
		END
	SET @SQLQUERY = @SQLQUERY + ' order by E.EMPLOYEE_CODE_ID,pd.Shift_DATE'
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	--select * from #TEMPMONTHLYATTENDANCE
	update #TEMPMONTHLYATTENDANCE set Category=case when Category=0 then 2 else Category end
	
	--SELECT t1.EMPLOYEE_ID,NOoftimes=CASE WHEN t1.Category=1 then
	--						CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
	--								WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
	--								WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 3
	--								WHEN t1.LATEINMIN > t.EndTime3Mins then 3
	--								ELSE 1000
	--						END
	--					when t1.Category=2 then 
	--						CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 4 
	--								WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 5 
	--								WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 6
	--								WHEN t1.LATEINMIN > t.EndTime3Mins then 6
	--								else 1000
	--						END
	--					ELSE 1000
	--				END,				
	--				Day1,Day2,Day3,Day4,Day5,Day6,Day7,Day8,Day9,Day10,Day11,Day12,Shift_DATE
	--		from #TEMPMONTHLYATTENDANCE t1 
	--		inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
	--		where (isnull(LATEINMIN,0)!=0)
	--	return
	--As per cleint requisition the value 30 mentioned as defualt value on 14-Oct-2019 10:52 AM by Manikandan.RR
	Update #TEMPMONTHLYATTENDANCE set LateInDeduction=
	--select 
	(isnull(BasicSalary,0)/30.0)*
	(CASE	WHEN NOoftimes=1 and ROWNUMBER=1	THEN Day1/100.0
			WHEN NOoftimes=1 and ROWNUMBER=2	THEN Day2/100.0
			WHEN NOoftimes=1 and ROWNUMBER=3	THEN Day3/100.0
			WHEN NOoftimes=1 and ROWNUMBER>=4	THEN Day4/100.0
			WHEN NOoftimes=2 and ROWNUMBER=1	THEN Day5/100.0
			WHEN NOoftimes=2 and ROWNUMBER=2	THEN Day6/100.0
			WHEN NOoftimes=2 and ROWNUMBER=3	THEN Day7/100.0
			WHEN NOoftimes=2 and ROWNUMBER>=4	THEN Day8/100.0
			when NOoftimes=3 and ROWNUMBER=1	THEN Day9/100.0
			when NOoftimes=3 and ROWNUMBER=2	THEN Day10/100.0
			when NOoftimes=3 and ROWNUMBER=3	THEN Day11/100.0
			when NOoftimes=3 and ROWNUMBER>=4	THEN Day12/100.0
			
			WHEN NOoftimes=4 and ROWNUMBER=1	THEN Day1/100.0
			WHEN NOoftimes=4 and ROWNUMBER=2	THEN Day2/100.0
			WHEN NOoftimes=4 and ROWNUMBER=3	THEN Day3/100.0
			WHEN NOoftimes=4 and ROWNUMBER>=4	THEN Day4/100.0
			WHEN NOoftimes=5 and ROWNUMBER=1	THEN Day5/100.0
			WHEN NOoftimes=5 and ROWNUMBER=2	THEN Day6/100.0
			WHEN NOoftimes=5 and ROWNUMBER=3	THEN Day7/100.0
			WHEN NOoftimes=5 and ROWNUMBER>=4	THEN Day8/100.0
			when NOoftimes=6 and ROWNUMBER=1	THEN Day9/100.0
			when NOoftimes=6 and ROWNUMBER=2	THEN Day10/100.0
			when NOoftimes=6 and ROWNUMBER=3	THEN Day11/100.0
			when NOoftimes=6 and ROWNUMBER>=4	THEN Day12/100.0
	END)
	,WhichDuration=NOoftimes,
	Whichpercentage=ROWNUMBER
	from #TEMPMONTHLYATTENDANCE MA
	inner join	
	(
		SELECT *,ROWNUMBER=ROW_NUMBER()OVER(PARTITION BY EMPLOYEE_ID,NOoftimes ORDER BY EMPLOYEE_ID,Shift_DATE) from
		(
			SELECT t1.EMPLOYEE_ID,NOoftimes=CASE WHEN t1.Category=1 then
							CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
									WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
									WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 3
									WHEN t1.LATEINMIN > t.EndTime3Mins then 3
									ELSE 1000
							END
						when t1.Category=2 then 
							CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 4 
									WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 5 
									WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 6
									WHEN t1.LATEINMIN > t.EndTime3Mins then 6
									else 1000
							END
						ELSE 1000
					END,				
					Day1,Day2,Day3,Day4,Day5,Day6,Day7,Day8,Day9,Day10,Day11,Day12,Shift_DATE
			from #TEMPMONTHLYATTENDANCE t1 
			inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
			where (isnull(LATEINMIN,0)!=0)
		)AS A where NOoftimes!=0
	)AS B on (MA.EMPLOYEE_ID=B.EMPLOYEE_ID and MA.Shift_DATE=B.Shift_DATE) 
	--and ROWNUMBER!=1
	where (isnull(LATEINMIN,0)!=0)
	
	--delete from #TEMPMONTHLYATTENDANCE  where WhichDuration=1000
	--select * from #TEMPMONTHLYATTENDANCE 
	--where EMPLOYEE_ID='IT163'
	
	Update #TEMPMONTHLYATTENDANCE set EarlyOutDeduction=
	--select 
	(isnull(BasicSalary,0)/30.0)*
	(CASE	WHEN NOoftimes=1 and ROWNUMBER=1	THEN Day1/100.0
			WHEN NOoftimes=1 and ROWNUMBER=2	THEN Day2/100.0
			WHEN NOoftimes=1 and ROWNUMBER=3	THEN Day3/100.0
			WHEN NOoftimes=1 and ROWNUMBER>=4	THEN Day4/100.0
			
	END)
	,WhichDuration=NOoftimes,
	Whichpercentage=ROWNUMBER
	from #TEMPMONTHLYATTENDANCE MA
	inner join	
	(
		SELECT *,ROWNUMBER=ROW_NUMBER()OVER(PARTITION BY EMPLOYEE_ID,NOoftimes ORDER BY EMPLOYEE_ID,Shift_DATE) from
		(
			SELECT t1.EMPLOYEE_ID,NOoftimes= CASE WHEN t1.EARLYOUTMIN>= t.StartTime1Mins THEN 1 
									ELSE 0
								END,				
					Day1,Day2,Day3,Day4,Shift_DATE
			from #TEMPMONTHLYATTENDANCE t1 
			inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=3)
			where (isnull(EARLYOUTMIN,0)!=0)
		)AS A where NOoftimes!=0
	)AS B on (MA.EMPLOYEE_ID=B.EMPLOYEE_ID and MA.Shift_DATE=B.Shift_DATE) 
	--and ROWNUMBER!=1
	where (isnull(EARLYOUTMIN,0)!=0)

	--Update #TEMPMONTHLYATTENDANCE set EarlyOutDeduction=(BasicSalary/30) 
	--*
	--(CASE	WHEN ROWNUMBER=1	THEN Day1/100.0
	--		WHEN ROWNUMBER=2	THEN Day2/100.0
	--		WHEN ROWNUMBER=3	THEN Day3/100.0
	--		WHEN ROWNUMBER>=4	THEN Day4/100.0			
	--END)
	--from #TEMPMONTHLYATTENDANCE MA
	--inner join		
	--(
	--	SELECT t1.EMPLOYEE_ID,ROWNUMBER=
	--				CASE	WHEN t1.EARLYOUTMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
	--								WHEN t1.EARLYOUTMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
	--								WHEN t1.EARLYOUTMIN between t.StartTime3Mins and t.EndTime3Mins then 3
	--								WHEN t1.EARLYOUTMIN > t.EndTime3Mins then 3
	--								ELSE 0
	--						END,
	--		Day1,Day2,Day3,Day4,Shift_DATE
	--		from #TEMPMONTHLYATTENDANCE t1 
	--		inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
	--	where (isnull(EARLYOUTMIN,0)!=0)		
	--)AS B on (MA.EMPLOYEE_ID=B.EMPLOYEE_ID and MA.Shift_DATE=B.Shift_DATE)
	--where (isnull(EARLYOUTMIN,0)!=0)
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	if(@isDetailed_Summary=0)
	begin
		SELECT	
		[Employee ID]=EMPLOYEE_ID,
		[Employee Name]=EMPNAME,
		Designation,
		Department=BRANCHNAME,
		[Shift Date]=CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
							REPLACE(CONVERT(VARCHAR, Shift_DATE,@DATEFORMAT),' ','-') 
					ELSE CONVERT(VARCHAR, Shift_DATE, @DATEFORMAT) END,		
		[Late Hours]=LATEIN,
		LateInDeduction=isnull(LateInDeduction,0),
		[Early Out Hours]=EARLYOUT,
		EarlyOutDeduction=isnull(EarlyOutDeduction,0),
		[Total Amount]=isnull(LateInDeduction,0)+isnull(EarlyOutDeduction,0)		
		--,
		--LATEINMIN,	
		--EARLYOUTMIN,	
		--Category,
		--BasicSalary,	
		--WhichDuration,
		--Whichpercentage
		FROM #TEMPMONTHLYATTENDANCE 
		--where (LateInDeduction!=0 or EarlyOutDeduction!=0) 
		ORDER BY EMPLOYEE_ID,CONVERT(datetime,Shift_DATE)
	end
	else
	begin
		SELECT	
		[Employee ID]=EMPLOYEE_ID,
		[Employee Name]=EMPNAME,
		Designation,
		Department=BRANCHNAME,
		[Month of Deduction]=datename(month,Shift_DATE),
		TotalLateIn=ISNULL(dbo.ConvertMinsToHours(SUM(isnull(LATEINMIN,0))),'00:00'),	
		LateInDeduction=CONVERT(DECIMAL(18,3),SUM(isnull(LateInDeduction,0))),
		TotalEarlyOut=ISNULL(dbo.ConvertMinsToHours(SUM(isnull(EARLYOUTMIN,0))),'00:00'),
		EarlyOutDeduction=CONVERT(DECIMAL(18,3),SUM(isnull(EarlyOutDeduction,0))),
		[Total Amount]=CONVERT(DECIMAL(18,3),SUM(isnull(LateInDeduction,0)))+CONVERT(DECIMAL(18,3),SUM(isnull(EarlyOutDeduction,0))),
		MonthNo=datepart(month,Shift_DATE)
		FROM #TEMPMONTHLYATTENDANCE 
		--where (LateInDeduction!=0 or EarlyOutDeduction!=0)
		GROUP BY EMPLOYEE_ID,EMPNAME,Designation,BRANCHNAME,datename(month,Shift_DATE),datepart(month,Shift_DATE)
		ORDER BY EMPLOYEE_ID,datepart(month,Shift_DATE)
	end
	
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDashBoardPunchDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*	
Proc_TA_RptEmployeeInOutSummary @EmployeeId='',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',
@UserGroupName='superadmin',@GradeLevel='1',@EmpSwipeCard='',@ParentId=0,@Fromdate1='2022/11/01',@Todate1='2022/11/30',@DesignationID=0,@Gender='Both',@EmpAutoID=1


exec Proc_TA_RptEmployeeInOutSummary @DesignationID=N'0',@ToDate1=N'2024/02/05 00:00:00',@Gender=N'Both',
@EmployeeId=N'BB002',@EmpAutoId=N'0',@ParentId=N'37',@FromDate1=N'2024/02/05 00:00:00',@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@LevelID=N'37',@employeeType=N'0',@employeeCategory=N'0',@EmployeeName=N''

	exec Proc_TA_RptDashBoardPunchDetails @EmployeeId=N'',@EmployeeName=N'',@LevelID=N'9',
	@employeeCategory=N'0',@employeeType=N'0',@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',
	@ParentId=0,@Fromdate1=N'01/July/2024',@Todate1=N'04/July/2024',@DesignationID=0,@Gender=N'Both',@EmpAutoID=1

*/
CREATE PROCEDURE [dbo].[Proc_TA_RptDashBoardPunchDetails] 
	@EmployeeId NVARCHAR(50),
	@EmployeeName NVARCHAR(50),  
	@LevelID NVARCHAR(1000), 	 
	@employeeCategory NVARCHAR(50),
	@employeeType NVARCHAR(50)	,
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20)	,
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50),
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@EmpAutoID INT
AS
BEGIN
	SET NOCOUNT ON;
	--DECLARE @InputDate NVARCHAR(50) = @Fromdate1
	--DECLARE @InputDates NVARCHAR(50) = @Todate1
	--DECLARE @DateInDateTime DATETIME
	--DECLARE @DateInDateTimes DATETIME

 --Convert the input string to datetime
	--SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
	--SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
 --Convert the datetime to the desired format
	--Set @Fromdate1= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
	--Set @Todate1= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)

	print @Fromdate1
	Print @Todate1

	--Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(50),FatherName NVARCHAR(50),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),Present NUMERIC(18,1),
		Absent NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
		F_Day1 NVARCHAR(100) DEFAULT '-',F_Day2 NVARCHAR(100) DEFAULT '-',F_Day3 NVARCHAR(100) DEFAULT '-',F_Day4 NVARCHAR(100) DEFAULT '-',F_Day5 NVARCHAR(100) DEFAULT '-',F_Day6 NVARCHAR(100) DEFAULT '-',F_Day7 NVARCHAR(100) DEFAULT '-',F_Day8 NVARCHAR(100) DEFAULT '-',F_Day9 NVARCHAR(100) DEFAULT '-',F_Day10 NVARCHAR(100) DEFAULT '-',F_Day11 NVARCHAR(100) DEFAULT '-',F_Day12 NVARCHAR(100) DEFAULT '-',F_Day13 NVARCHAR(100) DEFAULT '-',F_Day14 NVARCHAR(100) DEFAULT '-',F_Day15 NVARCHAR(100) DEFAULT '-',F_Day16 NVARCHAR(100) DEFAULT '-',F_Day17 NVARCHAR(100) DEFAULT '-',F_Day18 NVARCHAR(100) DEFAULT '-',F_Day19 NVARCHAR(100) DEFAULT '-',F_Day20 NVARCHAR(100) DEFAULT '-',F_Day21 NVARCHAR(100) DEFAULT '-',F_Day22 NVARCHAR(100) DEFAULT '-',F_Day23 NVARCHAR(100) DEFAULT '-',F_Day24 NVARCHAR(100) DEFAULT '-',F_Day25 NVARCHAR(100) DEFAULT '-',F_Day26 NVARCHAR(100) DEFAULT '-',F_Day27 NVARCHAR(100) DEFAULT '-',F_Day28 NVARCHAR(100) DEFAULT '-',F_Day29 NVARCHAR(100) DEFAULT '-',F_Day30 NVARCHAR(100) DEFAULT '-',F_Day31 NVARCHAR(100) DEFAULT '-',
	    A_Day1 NVARCHAR(100) DEFAULT '-',A_Day2 NVARCHAR(100) DEFAULT '-',A_Day3 NVARCHAR(100) DEFAULT '-',A_Day4 NVARCHAR(100) DEFAULT '-',A_Day5 NVARCHAR(100) DEFAULT '-',A_Day6 NVARCHAR(100) DEFAULT '-',A_Day7 NVARCHAR(100) DEFAULT '-',A_Day8 NVARCHAR(100) DEFAULT '-',A_Day9 NVARCHAR(100) DEFAULT '-',A_Day10 NVARCHAR(100) DEFAULT '-',A_Day11 NVARCHAR(100) DEFAULT '-',A_Day12 NVARCHAR(100) DEFAULT '-',A_Day13 NVARCHAR(100) DEFAULT '-',A_Day14 NVARCHAR(100) DEFAULT '-',A_Day15 NVARCHAR(100) DEFAULT '-',A_Day16 NVARCHAR(100) DEFAULT '-',A_Day17 NVARCHAR(100) DEFAULT '-',A_Day18 NVARCHAR(100) DEFAULT '-',A_Day19 NVARCHAR(100) DEFAULT '-',A_Day20 NVARCHAR(100) DEFAULT '-',A_Day21 NVARCHAR(100) DEFAULT '-',A_Day22 NVARCHAR(100) DEFAULT '-',A_Day23 NVARCHAR(100) DEFAULT '-',A_Day24 NVARCHAR(100) DEFAULT '-',A_Day25 NVARCHAR(100) DEFAULT '-',A_Day26 NVARCHAR(100) DEFAULT '-',A_Day27 NVARCHAR(100) DEFAULT '-',A_Day28 NVARCHAR(100) DEFAULT '-',A_Day29 NVARCHAR(100) DEFAULT '-',A_Day30 NVARCHAR(100) DEFAULT '-',A_Day31 NVARCHAR(100) DEFAULT '-',	
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)  
	)
	--Assign Variable into some values
	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=CONVERT(Datetime, @Fromdate1,105),@loca_Todate1=CONVERT(Datetime, @Todate1,105),@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
    IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN
		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	
	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
    INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
    --For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel     SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0
    
	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)
	
	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	INSERT INTO #EmpInOutDetails 
	SELECT	E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))
	
	---Updating OD Notation 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    
    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN 
											  END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	INSERT INTO #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar)
	SELECT DISTINCT Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar FROM #EmpInOutDetails 
	
	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance
	UPDATE #AllEmpInOutDetails set PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1, PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	
	SET @Count=1
	DECLARE @SQLUS NVARCHAR(max)
	DECLARE @SQLHeader NVARCHAR(max)
	WHILE(@Count <=31)
	BEGIN
		--Creating Table Header
		SET @SQLHeader=''
		SET @SQLUS=''
		SET @SQLHeader = @SQLHeader + ' UPDATE #TempHeader SET Day'+CAST(@Count as NVARCHAR(10)) + '=' + CAST (datepart(d,@loca_Fromdate1)as NVARCHAR(10)) + 'WHERE id=1'	
		EXEC(@SQLHeader)
		--Updating data of particular date.
		IF(@Count <=@Diff)
		BEGIN			
			SET @SQLUS = @SQLUS + ' UPDATE AD SET F_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceFN,A_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceAN'
			SET @SQLUS = @SQLUS + ' FROM  #EmpInOutDetails ED INNER JOIN #AllEmpInOutDetails AD on AD.Employee_code_id=	ED.Employee_code_id AND ED.date =   CONVERT(DATETIME, ''' + @loca_Fromdate1 + ''' , 102)'
			EXEC(@SQLUS)
		END		
		SET @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
		SET @Count=@Count +1
	END
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	

	


	
	SELECT	A.Employee_Code_Id,
			A.Name,
			Designation,
			--#Ta_Tbl_levelDetail.name,
			--#Ta_Tbl_levelDetail.id,
			CLAvailed,
			F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,
			F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
			FatherName,
			Present,
			Absent,
			Leave,
			Holiday,
			TotalOT,			
			DesignationID,
			Grade_Level,
			OrderBy,
			PD,
			AD,
			WOD,
			HD,
			LD,
			LOPD,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			TOTD,
			Aadhar,
			A_Day1,A_Day2,A_Day3,A_Day4,A_Day5,A_Day6,A_Day7,A_Day8,A_Day9,A_Day10,A_Day11,A_Day12,A_Day13,A_Day14,A_Day15,
			A_Day16,A_Day17,A_Day18,A_Day19,A_Day20,A_Day21,A_Day22,A_Day23,A_Day24,A_Day25,A_Day26,A_Day27,A_Day28,A_Day29,A_Day30,A_Day31,			
			AFDay1=REPLACE(F_Day1,'#','')+' / '+REPLACE(A_Day1,'#',''),
			AFDay2=REPLACE(F_Day2,'#','')+' / '+REPLACE(A_Day2,'#',''),
			AFDay3=REPLACE(F_Day3,'#','')+' / '+REPLACE(A_Day3,'#',''),
			AFDay4=REPLACE(F_Day4,'#','')+' / '+REPLACE(A_Day4,'#',''),
			AFDay5=REPLACE(F_Day5,'#','')+' / '+REPLACE(A_Day5,'#',''),
			AFDay6=REPLACE(F_Day6,'#','')+' / '+REPLACE(A_Day6,'#',''),
			AFDay7=REPLACE(F_Day7,'#','')+' / '+REPLACE(A_Day7,'#',''),
			AFDay8=REPLACE(F_Day8,'#','')+' / '+REPLACE(A_Day8,'#',''),
			AFDay9=REPLACE(F_Day9,'#','')+' / '+REPLACE(A_Day9,'#',''),
			AFDay10=REPLACE(F_Day10,'#','')+' / '+REPLACE(A_Day10,'#',''),
			AFDay11=REPLACE(F_Day11,'#','')+' / '+REPLACE(A_Day11,'#',''),
			AFDay12=REPLACE(F_Day12,'#','')+' / '+REPLACE(A_Day12,'#',''),
			AFDay13=REPLACE(F_Day13,'#','')+' / '+REPLACE(A_Day13,'#',''),
			AFDay14=REPLACE(F_Day14,'#','')+' / '+REPLACE(A_Day14,'#',''),
			AFDay15=REPLACE(F_Day15,'#','')+' / '+REPLACE(A_Day15,'#',''),
			AFDay16=REPLACE(F_Day16,'#','')+' / '+REPLACE(A_Day16,'#',''),
			AFDay17=REPLACE(F_Day17,'#','')+' / '+REPLACE(A_Day17,'#',''),
			AFDay18=REPLACE(F_Day18,'#','')+' / '+REPLACE(A_Day18,'#',''),
			AFDay19=REPLACE(F_Day19,'#','')+' / '+REPLACE(A_Day19,'#',''),
			AFDay20=REPLACE(F_Day20,'#','')+' / '+REPLACE(A_Day20,'#',''),
			AFDay21=REPLACE(F_Day21,'#','')+' / '+REPLACE(A_Day21,'#',''),
			AFDay22=REPLACE(F_Day22,'#','')+' / '+REPLACE(A_Day22,'#',''),
			AFDay23=REPLACE(F_Day23,'#','')+' / '+REPLACE(A_Day23,'#',''),
			AFDay24=REPLACE(F_Day24,'#','')+' / '+REPLACE(A_Day24,'#',''),
			AFDay25=REPLACE(F_Day25,'#','')+' / '+REPLACE(A_Day25,'#',''),
			AFDay26=REPLACE(F_Day26,'#','')+' / '+REPLACE(A_Day26,'#',''),
			AFDay27=REPLACE(F_Day27,'#','')+' / '+REPLACE(A_Day27,'#',''),
			AFDay28=REPLACE(F_Day28,'#','')+' / '+REPLACE(A_Day28,'#',''),
			AFDay29=REPLACE(F_Day29,'#','')+' / '+REPLACE(A_Day29,'#',''),
			AFDay30=REPLACE(F_Day30,'#','')+' / '+REPLACE(A_Day30,'#',''),
			AFDay31=REPLACE(F_Day31,'#','')+' / '+REPLACE(A_Day31,'#','')			
	FROM #AllEmpInOutDetails A 
	--inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = A.Employee_Code_Id
	--inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	--left Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
	ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),A.Name


	if(@LevelID != '0')
	begin 

    SELECT id, levelId, parentId, name, description into #RecursiveCTE
    FROM Ta_Tbl_levelDetails 
    WHERE id = @LevelID  

	 SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetails
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #RecursiveCTE r ON t.parentId = r.id

	SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetail
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #Ta_Tbl_levelDetails r ON t.parentId = r.id

	 SELECT
        #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0 ELSE Case when F_Day1='p' then 0.5 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0 ELSE Case when A_Day1='p' then 0.5 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0 ELSE Case when F_Day2='p' then 0.5 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0 ELSE Case when A_Day2='p' then 0.5 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0 ELSE Case when F_Day3='p' then 0.5 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0 ELSE Case when A_Day3='p' then 0.5 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0 ELSE Case when F_Day4='p' then 0.5 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0 ELSE Case when A_Day4='p' then 0.5 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0 ELSE Case when F_Day5='p' then 0.5 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0 ELSE Case when A_Day5='p' then 0.5 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0 ELSE Case when F_Day6='p' then 0.5 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0 ELSE Case when A_Day6='p' then 0.5 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0 ELSE Case when F_Day7='p' then 0.5 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0 ELSE Case when A_Day7='p' then 0.5 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0 ELSE Case when F_Day8='p' then 0.5 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0 ELSE Case when A_Day8='p' then 0.5 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0 ELSE Case when F_Day9='p' then 0.5 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0 ELSE Case when A_Day9='p' then 0.5 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0 ELSE Case when F_Day10='p' then 0.5 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0 ELSE Case when A_Day10='p' then 0.5 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0 ELSE Case when F_Day11='p' then 0.5 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0 ELSE Case when A_Day11='p' then 0.5 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0 ELSE Case when F_Day12='p' then 0.5 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0 ELSE Case when A_Day12='p' then 0.5 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0 ELSE Case when F_Day13='p' then 0.5 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0 ELSE Case when A_Day13='p' then 0.5 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0 ELSE Case when F_Day14='p' then 0.5 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0 ELSE Case when A_Day14='p' then 0.5 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0 ELSE Case when F_Day15='p' then 0.5 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0 ELSE Case when A_Day15='p' then 0.5 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0 ELSE Case when F_Day16='p' then 0.5 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0 ELSE Case when A_Day16='p' then 0.5 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0 ELSE Case when F_Day17='p' then 0.5 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0 ELSE Case when A_Day17='p' then 0.5 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0 ELSE Case when F_Day18='p' then 0.5 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0 ELSE Case when A_Day18='p' then 0.5 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0 ELSE Case when F_Day19='p' then 0.5 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0 ELSE Case when A_Day19='p' then 0.5 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0 ELSE Case when F_Day20='p' then 0.5 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0 ELSE Case when A_Day20='p' then 0.5 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0 ELSE Case when F_Day21='p' then 0.5 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0 ELSE Case when A_Day21='p' then 0.5 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0 ELSE Case when F_Day22='p' then 0.5 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0 ELSE Case when A_Day22='p' then 0.5 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0 ELSE Case when F_Day23='p' then 0.5 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0 ELSE Case when A_Day23='p' then 0.5 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0 ELSE Case when F_Day24='p' then 0.5 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0 ELSE Case when A_Day24='p' then 0.5 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0 ELSE Case when F_Day25='p' then 0.5 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0 ELSE Case when A_Day25='p' then 0.5 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0 ELSE Case when F_Day26='p' then 0.5 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0 ELSE Case when A_Day26='p' then 0.5 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0 ELSE Case when F_Day27='p' then 0.5 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0 ELSE Case when A_Day27='p' then 0.5 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0 ELSE Case when F_Day28='p' then 0.5 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0 ELSE Case when A_Day28='p' then 0.5 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0 ELSE Case when F_Day29='p' then 0.5 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0 ELSE Case when A_Day29='p' then 0.5 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0 ELSE Case when F_Day30='p' then 0.5 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0 ELSE Case when A_Day30='p' then 0.5 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0 ELSE Case when F_Day31='p' then 0.5 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0 ELSE Case when A_Day31='p' then 0.5 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount into #TempCountData
    FROM #AllEmpInOutDetails
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = #AllEmpInOutDetails.Employee_Code_Id
	inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	left Join #Ta_Tbl_levelDetail on #Ta_Tbl_levelDetail.id= TA_Tbl_EmployeeLevel.LevelId
    GROUP BY #Ta_Tbl_levelDetail.name,#Ta_Tbl_levelDetail.id

	Declare @EmployeeCount Int
	Select @EmployeeCount=Count(*) from #TempCountData

 Select #TempCountData.id,#TempCountData.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge

from #TempCountData  where #TempCountData.id!=''
GROUP BY #TempCountData.id,#TempCountData.name
	drop Table #TempCountData
	end 
	else 
	begin 

    SELECT id, levelId, parentId, name, description into #RecursiveCTEs
    FROM Ta_Tbl_levelDetails  

	 SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetailss
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #RecursiveCTEs r ON t.parentId = r.id

	SELECT t.id, t.levelId, t.parentId, t.name, t.description into #Ta_Tbl_levelDetaill
    FROM Ta_Tbl_levelDetails t
    INNER JOIN #Ta_Tbl_levelDetailss r ON t.parentId = r.id

	 SELECT
        #Ta_Tbl_levelDetaill.name,#Ta_Tbl_levelDetaill.id,
        SUM(CASE WHEN F_Day1 = 'A' THEN 0 ELSE Case when F_Day1='p' then 0.5 else case when  F_Day1= 'OD' then 0.5 else case when F_Day1='L' then 0 else Case when F_Day1='OFF' then 0 else case when F_Day1='CL' then 0 else case when F_Day1='H' then 0 else case when F_Day1='RH' then 0 else  case when F_Day1='EL' then 0 else Case when F_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1Count,
        SUM(CASE WHEN A_Day1 = 'A' THEN 0 ELSE Case when A_Day1='p' then 0.5 else case when  A_Day1= 'OD' then 0.5 else case when A_Day1='L' then 0 else Case when A_Day1='OFF' then 0 else case when A_Day1='CL' then 0 else case when A_Day1='H' then 0 else case when A_Day1='RH' then 0 else  case when A_Day1='EL' then 0 else Case when A_Day1='Co' then 0 else 0 END END END END END END END END END END) AS A1ACount,
        SUM(CASE WHEN F_Day2 = 'A' THEN 0 ELSE Case when F_Day2='p' then 0.5 else case when  F_Day2= 'OD' then 0.5 else case when F_Day2='L' then 0 else Case when F_Day2='OFF' then 0 else case when F_Day2='CL' then 0 else case when F_Day2='H' then 0 else case when F_Day2='RH' then 0 else  case when F_Day2='EL' then 0 else Case when F_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2Count,
        SUM(CASE WHEN A_Day2 = 'A' THEN 0 ELSE Case when A_Day2='p' then 0.5 else case when  A_Day2= 'OD' then 0.5 else case when A_Day2='L' then 0 else Case when A_Day2='OFF' then 0 else case when A_Day2='CL' then 0 else case when A_Day2='H' then 0 else case when A_Day2='RH' then 0 else  case when A_Day2='EL' then 0 else Case when A_Day2='Co' then 0 else 0 END END END END END END END END END END) AS A2ACount,
        SUM(CASE WHEN F_Day3 = 'A' THEN 0 ELSE Case when F_Day3='p' then 0.5 else case when  F_Day3= 'OD' then 0.5 else case when F_Day3='L' then 0 else Case when F_Day3='OFF' then 0 else case when F_Day3='CL' then 0 else case when F_Day3='H' then 0 else case when F_Day3='RH' then 0 else  case when F_Day3='EL' then 0 else Case when F_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3Count,
        SUM(CASE WHEN A_Day3 = 'A' THEN 0 ELSE Case when A_Day3='p' then 0.5 else case when  A_Day3= 'OD' then 0.5 else case when A_Day3='L' then 0 else Case when A_Day3='OFF' then 0 else case when A_Day3='CL' then 0 else case when A_Day3='H' then 0 else case when A_Day3='RH' then 0 else  case when A_Day3='EL' then 0 else Case when A_Day3='Co' then 0 else 0 END END END END END END END END END END) AS A3ACount,
        SUM(CASE WHEN F_Day4 = 'A' THEN 0 ELSE Case when F_Day4='p' then 0.5 else case when  F_Day4= 'OD' then 0.5 else case when F_Day4='L' then 0 else Case when F_Day4='OFF' then 0 else case when F_Day4='CL' then 0 else case when F_Day4='H' then 0 else case when F_Day4='RH' then 0 else  case when F_Day4='EL' then 0 else Case when F_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4Count,
        SUM(CASE WHEN A_Day4 = 'A' THEN 0 ELSE Case when A_Day4='p' then 0.5 else case when  A_Day4= 'OD' then 0.5 else case when A_Day4='L' then 0 else Case when A_Day4='OFF' then 0 else case when A_Day4='CL' then 0 else case when A_Day4='H' then 0 else case when A_Day4='RH' then 0 else  case when A_Day4='EL' then 0 else Case when A_Day4='Co' then 0 else 0 END END END END END END END END END END) AS A4ACount,
        SUM(CASE WHEN F_Day5 = 'A' THEN 0 ELSE Case when F_Day5='p' then 0.5 else case when  F_Day5= 'OD' then 0.5 else case when F_Day5='L' then 0 else Case when F_Day5='OFF' then 0 else case when F_Day5='CL' then 0 else case when F_Day5='H' then 0 else case when F_Day5='RH' then 0 else  case when F_Day5='EL' then 0 else Case when F_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5Count,
        SUM(CASE WHEN A_Day5 = 'A' THEN 0 ELSE Case when A_Day5='p' then 0.5 else case when  A_Day5= 'OD' then 0.5 else case when A_Day5='L' then 0 else Case when A_Day5='OFF' then 0 else case when A_Day5='CL' then 0 else case when A_Day5='H' then 0 else case when A_Day5='RH' then 0 else  case when A_Day5='EL' then 0 else Case when A_Day5='Co' then 0 else 0 END END END END END END END END END END) AS A5ACount,
        SUM(CASE WHEN F_Day6 = 'A' THEN 0 ELSE Case when F_Day6='p' then 0.5 else case when  F_Day6= 'OD' then 0.5 else case when F_Day6='L' then 0 else Case when F_Day6='OFF' then 0 else case when F_Day6='CL' then 0 else case when F_Day6='H' then 0 else case when F_Day6='RH' then 0 else  case when F_Day6='EL' then 0 else Case when F_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6Count,
        SUM(CASE WHEN A_Day6 = 'A' THEN 0 ELSE Case when A_Day6='p' then 0.5 else case when  A_Day6= 'OD' then 0.5 else case when A_Day6='L' then 0 else Case when A_Day6='OFF' then 0 else case when A_Day6='CL' then 0 else case when A_Day6='H' then 0 else case when A_Day6='RH' then 0 else  case when A_Day6='EL' then 0 else Case when A_Day6='Co' then 0 else 0 END END END END END END END END END END) AS A6ACount,
        SUM(CASE WHEN F_Day7 = 'A' THEN 0 ELSE Case when F_Day7='p' then 0.5 else case when  F_Day7= 'OD' then 0.5 else case when F_Day7='L' then 0 else Case when F_Day7='OFF' then 0 else case when F_Day7='CL' then 0 else case when F_Day7='H' then 0 else case when F_Day7='RH' then 0 else  case when F_Day7='EL' then 0 else Case when F_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7Count,
        SUM(CASE WHEN A_Day7 = 'A' THEN 0 ELSE Case when A_Day7='p' then 0.5 else case when  A_Day7= 'OD' then 0.5 else case when A_Day7='L' then 0 else Case when A_Day7='OFF' then 0 else case when A_Day7='CL' then 0 else case when A_Day7='H' then 0 else case when A_Day7='RH' then 0 else  case when A_Day7='EL' then 0 else Case when A_Day7='Co' then 0 else 0 END END END END END END END END END END) AS A7ACount,
        SUM(CASE WHEN F_Day8 = 'A' THEN 0 ELSE Case when F_Day8='p' then 0.5 else case when  F_Day8= 'OD' then 0.5 else case when F_Day8='L' then 0 else Case when F_Day8='OFF' then 0 else case when F_Day8='CL' then 0 else case when F_Day8='H' then 0 else case when F_Day8='RH' then 0 else  case when F_Day8='EL' then 0 else Case when F_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8Count,
        SUM(CASE WHEN A_Day8 = 'A' THEN 0 ELSE Case when A_Day8='p' then 0.5 else case when  A_Day8= 'OD' then 0.5 else case when A_Day8='L' then 0 else Case when A_Day8='OFF' then 0 else case when A_Day8='CL' then 0 else case when A_Day8='H' then 0 else case when A_Day8='RH' then 0 else  case when A_Day8='EL' then 0 else Case when A_Day8='Co' then 0 else 0 END END END END END END END END END END) AS A8ACount,
        SUM(CASE WHEN F_Day9 = 'A' THEN 0 ELSE Case when F_Day9='p' then 0.5 else case when  F_Day9= 'OD' then 0.5 else case when F_Day9='L' then 0 else Case when F_Day9='OFF' then 0 else case when F_Day9='CL' then 0 else case when F_Day9='H' then 0 else case when F_Day9='RH' then 0 else  case when F_Day9='EL' then 0 else Case when F_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9Count,
        SUM(CASE WHEN A_Day9 = 'A' THEN 0 ELSE Case when A_Day9='p' then 0.5 else case when  A_Day9= 'OD' then 0.5 else case when A_Day9='L' then 0 else Case when A_Day9='OFF' then 0 else case when A_Day9='CL' then 0 else case when A_Day9='H' then 0 else case when A_Day9='RH' then 0 else  case when A_Day9='EL' then 0 else Case when A_Day9='Co' then 0 else 0 END END END END END END END END END END) AS A9ACount,
        SUM(CASE WHEN F_Day10 = 'A' THEN 0 ELSE Case when F_Day10='p' then 0.5 else case when  F_Day10= 'OD' then 0.5 else case when F_Day10='L' then 0 else Case when F_Day10='OFF' then 0 else case when F_Day10='CL' then 0 else case when F_Day10='H' then 0 else case when F_Day10='RH' then 0 else  case when F_Day10='EL' then 0 else Case when F_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10Count,
        SUM(CASE WHEN A_Day10 = 'A' THEN 0 ELSE Case when A_Day10='p' then 0.5 else case when  A_Day10= 'OD' then 0.5 else case when A_Day10='L' then 0 else Case when A_Day10='OFF' then 0 else case when A_Day10='CL' then 0 else case when A_Day10='H' then 0 else case when A_Day10='RH' then 0 else  case when A_Day10='EL' then 0 else Case when A_Day10='Co' then 0 else 0 END END END END END END END END END  END) AS A10ACount,
        SUM(CASE WHEN F_Day11 = 'A' THEN 0 ELSE Case when F_Day11='p' then 0.5 else case when  F_Day11= 'OD' then 0.5 else case when F_Day11='L' then 0 else Case when F_Day11='OFF' then 0 else case when F_Day11='CL' then 0 else case when F_Day11='H' then 0 else case when F_Day11='RH' then 0 else  case when F_Day11='EL' then 0 else Case when F_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11Count,
        SUM(CASE WHEN A_Day11 = 'A' THEN 0 ELSE Case when A_Day11='p' then 0.5 else case when  A_Day11= 'OD' then 0.5 else case when A_Day11='L' then 0 else Case when A_Day11='OFF' then 0 else case when A_Day11='CL' then 0 else case when A_Day11='H' then 0 else case when A_Day11='RH' then 0 else  case when A_Day11='EL' then 0 else Case when A_Day11='Co' then 0 else 0 END END END END END END END END END  END) AS A11ACount,
        SUM(CASE WHEN F_Day12 = 'A' THEN 0 ELSE Case when F_Day12='p' then 0.5 else case when  F_Day12= 'OD' then 0.5 else case when F_Day12='L' then 0 else Case when F_Day12='OFF' then 0 else case when F_Day12='CL' then 0 else case when F_Day12='H' then 0 else case when F_Day12='RH' then 0 else  case when F_Day12='EL' then 0 else Case when F_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12Count,
        SUM(CASE WHEN A_Day12 = 'A' THEN 0 ELSE Case when A_Day12='p' then 0.5 else case when  A_Day12= 'OD' then 0.5 else case when A_Day12='L' then 0 else Case when A_Day12='OFF' then 0 else case when A_Day12='CL' then 0 else case when A_Day12='H' then 0 else case when A_Day12='RH' then 0 else  case when A_Day12='EL' then 0 else Case when A_Day12='Co' then 0 else 0 END END END END END END END END END  END) AS A12ACount,
        SUM(CASE WHEN F_Day13 = 'A' THEN 0 ELSE Case when F_Day13='p' then 0.5 else case when  F_Day13= 'OD' then 0.5 else case when F_Day13='L' then 0 else Case when F_Day13='OFF' then 0 else case when F_Day13='CL' then 0 else case when F_Day13='H' then 0 else case when F_Day13='RH' then 0 else  case when F_Day13='EL' then 0 else Case when F_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13Count,
        SUM(CASE WHEN A_Day13 = 'A' THEN 0 ELSE Case when A_Day13='p' then 0.5 else case when  A_Day13= 'OD' then 0.5 else case when A_Day13='L' then 0 else Case when A_Day13='OFF' then 0 else case when A_Day13='CL' then 0 else case when A_Day13='H' then 0 else case when A_Day13='RH' then 0 else  case when A_Day13='EL' then 0 else Case when A_Day13='Co' then 0 else 0 END END END END END END END END END  END) AS A13ACount,
        SUM(CASE WHEN F_Day14 = 'A' THEN 0 ELSE Case when F_Day14='p' then 0.5 else case when  F_Day14= 'OD' then 0.5 else case when F_Day14='L' then 0 else Case when F_Day14='OFF' then 0 else case when F_Day14='CL' then 0 else case when F_Day14='H' then 0 else case when F_Day14='RH' then 0 else  case when F_Day14='EL' then 0 else Case when F_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14Count,
        SUM(CASE WHEN A_Day14 = 'A' THEN 0 ELSE Case when A_Day14='p' then 0.5 else case when  A_Day14= 'OD' then 0.5 else case when A_Day14='L' then 0 else Case when A_Day14='OFF' then 0 else case when A_Day14='CL' then 0 else case when A_Day14='H' then 0 else case when A_Day14='RH' then 0 else  case when A_Day14='EL' then 0 else Case when A_Day14='Co' then 0 else 0 END END END END END END END END END  END) AS A14ACount,
        SUM(CASE WHEN F_Day15 = 'A' THEN 0 ELSE Case when F_Day15='p' then 0.5 else case when  F_Day15= 'OD' then 0.5 else case when F_Day15='L' then 0 else Case when F_Day15='OFF' then 0 else case when F_Day15='CL' then 0 else case when F_Day15='H' then 0 else case when F_Day15='RH' then 0 else  case when F_Day15='EL' then 0 else Case when F_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15Count,
        SUM(CASE WHEN A_Day15 = 'A' THEN 0 ELSE Case when A_Day15='p' then 0.5 else case when  A_Day15= 'OD' then 0.5 else case when A_Day15='L' then 0 else Case when A_Day15='OFF' then 0 else case when A_Day15='CL' then 0 else case when A_Day15='H' then 0 else case when A_Day15='RH' then 0 else  case when A_Day15='EL' then 0 else Case when A_Day15='Co' then 0 else 0 END END END END END END END END END  END) AS A15ACount,
        SUM(CASE WHEN F_Day16 = 'A' THEN 0 ELSE Case when F_Day16='p' then 0.5 else case when  F_Day16= 'OD' then 0.5 else case when F_Day16='L' then 0 else Case when F_Day16='OFF' then 0 else case when F_Day16='CL' then 0 else case when F_Day16='H' then 0 else case when F_Day16='RH' then 0 else  case when F_Day16='EL' then 0 else Case when F_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16Count,
        SUM(CASE WHEN A_Day16 = 'A' THEN 0 ELSE Case when A_Day16='p' then 0.5 else case when  A_Day16= 'OD' then 0.5 else case when A_Day16='L' then 0 else Case when A_Day16='OFF' then 0 else case when A_Day16='CL' then 0 else case when A_Day16='H' then 0 else case when A_Day16='RH' then 0 else  case when A_Day16='EL' then 0 else Case when A_Day16='Co' then 0 else 0 END END END END END END END END END  END) AS A16ACount,
        SUM(CASE WHEN F_Day17 = 'A' THEN 0 ELSE Case when F_Day17='p' then 0.5 else case when  F_Day17= 'OD' then 0.5 else case when F_Day17='L' then 0 else Case when F_Day17='OFF' then 0 else case when F_Day17='CL' then 0 else case when F_Day17='H' then 0 else case when F_Day17='RH' then 0 else  case when F_Day17='EL' then 0 else Case when F_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17Count,
        SUM(CASE WHEN A_Day17 = 'A' THEN 0 ELSE Case when A_Day17='p' then 0.5 else case when  A_Day17= 'OD' then 0.5 else case when A_Day17='L' then 0 else Case when A_Day17='OFF' then 0 else case when A_Day17='CL' then 0 else case when A_Day17='H' then 0 else case when A_Day17='RH' then 0 else  case when A_Day17='EL' then 0 else Case when A_Day17='Co' then 0 else 0 END END END END END END END END END  END) AS A17ACount,
        SUM(CASE WHEN F_Day18 = 'A' THEN 0 ELSE Case when F_Day18='p' then 0.5 else case when  F_Day18= 'OD' then 0.5 else case when F_Day18='L' then 0 else Case when F_Day18='OFF' then 0 else case when F_Day18='CL' then 0 else case when F_Day18='H' then 0 else case when F_Day18='RH' then 0 else  case when F_Day18='EL' then 0 else Case when F_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18Count,
        SUM(CASE WHEN A_Day18 = 'A' THEN 0 ELSE Case when A_Day18='p' then 0.5 else case when  A_Day18= 'OD' then 0.5 else case when A_Day18='L' then 0 else Case when A_Day18='OFF' then 0 else case when A_Day18='CL' then 0 else case when A_Day18='H' then 0 else case when A_Day18='RH' then 0 else  case when A_Day18='EL' then 0 else Case when A_Day18='Co' then 0 else 0 END END END END END END END END END  END) AS A18ACount,
        SUM(CASE WHEN F_Day19 = 'A' THEN 0 ELSE Case when F_Day19='p' then 0.5 else case when  F_Day19= 'OD' then 0.5 else case when F_Day19='L' then 0 else Case when F_Day19='OFF' then 0 else case when F_Day19='CL' then 0 else case when F_Day19='H' then 0 else case when F_Day19='RH' then 0 else  case when F_Day19='EL' then 0 else Case when F_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19Count,
        SUM(CASE WHEN A_Day19 = 'A' THEN 0 ELSE Case when A_Day19='p' then 0.5 else case when  A_Day19= 'OD' then 0.5 else case when A_Day19='L' then 0 else Case when A_Day19='OFF' then 0 else case when A_Day19='CL' then 0 else case when A_Day19='H' then 0 else case when A_Day19='RH' then 0 else  case when A_Day19='EL' then 0 else Case when A_Day19='Co' then 0 else 0 END END END END END END END END END  END) AS A19ACount,
        SUM(CASE WHEN F_Day20 = 'A' THEN 0 ELSE Case when F_Day20='p' then 0.5 else case when  F_Day20= 'OD' then 0.5 else case when F_Day20='L' then 0 else Case when F_Day20='OFF' then 0 else case when F_Day20='CL' then 0 else case when F_Day20='H' then 0 else case when F_Day20='RH' then 0 else  case when F_Day20='EL' then 0 else Case when F_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20Count,
        SUM(CASE WHEN A_Day20 = 'A' THEN 0 ELSE Case when A_Day20='p' then 0.5 else case when  A_Day20= 'OD' then 0.5 else case when A_Day20='L' then 0 else Case when A_Day20='OFF' then 0 else case when A_Day20='CL' then 0 else case when A_Day20='H' then 0 else case when A_Day20='RH' then 0 else  case when A_Day20='EL' then 0 else Case when A_Day20='Co' then 0 else 0 END END END END END END END END END  END) AS A20ACount,
        SUM(CASE WHEN F_Day21 = 'A' THEN 0 ELSE Case when F_Day21='p' then 0.5 else case when  F_Day21= 'OD' then 0.5 else case when F_Day21='L' then 0 else Case when F_Day21='OFF' then 0 else case when F_Day21='CL' then 0 else case when F_Day21='H' then 0 else case when F_Day21='RH' then 0 else  case when F_Day21='EL' then 0 else Case when F_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21Count,
        SUM(CASE WHEN A_Day21 = 'A' THEN 0 ELSE Case when A_Day21='p' then 0.5 else case when  A_Day21= 'OD' then 0.5 else case when A_Day21='L' then 0 else Case when A_Day21='OFF' then 0 else case when A_Day21='CL' then 0 else case when A_Day21='H' then 0 else case when A_Day21='RH' then 0 else  case when A_Day21='EL' then 0 else Case when A_Day21='Co' then 0 else 0 END END END END END END END END END  END) AS A21ACount,
        SUM(CASE WHEN F_Day22 = 'A' THEN 0 ELSE Case when F_Day22='p' then 0.5 else case when  F_Day22= 'OD' then 0.5 else case when F_Day22='L' then 0 else Case when F_Day22='OFF' then 0 else case when F_Day22='CL' then 0 else case when F_Day22='H' then 0 else case when F_Day22='RH' then 0 else  case when F_Day22='EL' then 0 else Case when F_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22Count,
        SUM(CASE WHEN A_Day22 = 'A' THEN 0 ELSE Case when A_Day22='p' then 0.5 else case when  A_Day22= 'OD' then 0.5 else case when A_Day22='L' then 0 else Case when A_Day22='OFF' then 0 else case when A_Day22='CL' then 0 else case when A_Day22='H' then 0 else case when A_Day22='RH' then 0 else  case when A_Day22='EL' then 0 else Case when A_Day22='Co' then 0 else 0 END END END END END END END END END  END) AS A22ACount,
        SUM(CASE WHEN F_Day23 = 'A' THEN 0 ELSE Case when F_Day23='p' then 0.5 else case when  F_Day23= 'OD' then 0.5 else case when F_Day23='L' then 0 else Case when F_Day23='OFF' then 0 else case when F_Day23='CL' then 0 else case when F_Day23='H' then 0 else case when F_Day23='RH' then 0 else  case when F_Day23='EL' then 0 else Case when F_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23Count,
        SUM(CASE WHEN A_Day23 = 'A' THEN 0 ELSE Case when A_Day23='p' then 0.5 else case when  A_Day23= 'OD' then 0.5 else case when A_Day23='L' then 0 else Case when A_Day23='OFF' then 0 else case when A_Day23='CL' then 0 else case when A_Day23='H' then 0 else case when A_Day23='RH' then 0 else  case when A_Day23='EL' then 0 else Case when A_Day23='Co' then 0 else 0 END END END END END END END END END  END) AS A23ACount,
        SUM(CASE WHEN F_Day24 = 'A' THEN 0 ELSE Case when F_Day24='p' then 0.5 else case when  F_Day24= 'OD' then 0.5 else case when F_Day24='L' then 0 else Case when F_Day24='OFF' then 0 else case when F_Day24='CL' then 0 else case when F_Day24='H' then 0 else case when F_Day24='RH' then 0 else  case when F_Day24='EL' then 0 else Case when F_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24Count,
        SUM(CASE WHEN A_Day24 = 'A' THEN 0 ELSE Case when A_Day24='p' then 0.5 else case when  A_Day24= 'OD' then 0.5 else case when A_Day24='L' then 0 else Case when A_Day24='OFF' then 0 else case when A_Day24='CL' then 0 else case when A_Day24='H' then 0 else case when A_Day24='RH' then 0 else  case when A_Day24='EL' then 0 else Case when A_Day24='Co' then 0 else 0 END END END END END END END END END  END) AS A24ACount,
        SUM(CASE WHEN F_Day25 = 'A' THEN 0 ELSE Case when F_Day25='p' then 0.5 else case when  F_Day25= 'OD' then 0.5 else case when F_Day25='L' then 0 else Case when F_Day25='OFF' then 0 else case when F_Day25='CL' then 0 else case when F_Day25='H' then 0 else case when F_Day25='RH' then 0 else  case when F_Day25='EL' then 0 else Case when F_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25Count,
        SUM(CASE WHEN A_Day25 = 'A' THEN 0 ELSE Case when A_Day25='p' then 0.5 else case when  A_Day25= 'OD' then 0.5 else case when A_Day25='L' then 0 else Case when A_Day25='OFF' then 0 else case when A_Day25='CL' then 0 else case when A_Day25='H' then 0 else case when A_Day25='RH' then 0 else  case when A_Day25='EL' then 0 else Case when A_Day25='Co' then 0 else 0 END END END END END END END END END  END) AS A25ACount,
        SUM(CASE WHEN F_Day26 = 'A' THEN 0 ELSE Case when F_Day26='p' then 0.5 else case when  F_Day26= 'OD' then 0.5 else case when F_Day26='L' then 0 else Case when F_Day26='OFF' then 0 else case when F_Day26='CL' then 0 else case when F_Day26='H' then 0 else case when F_Day26='RH' then 0 else  case when F_Day26='EL' then 0 else Case when F_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26Count,
        SUM(CASE WHEN A_Day26 = 'A' THEN 0 ELSE Case when A_Day26='p' then 0.5 else case when  A_Day26= 'OD' then 0.5 else case when A_Day26='L' then 0 else Case when A_Day26='OFF' then 0 else case when A_Day26='CL' then 0 else case when A_Day26='H' then 0 else case when A_Day26='RH' then 0 else  case when A_Day26='EL' then 0 else Case when A_Day26='Co' then 0 else 0 END END END END END END END END END  END) AS A26ACount,
        SUM(CASE WHEN F_Day27 = 'A' THEN 0 ELSE Case when F_Day27='p' then 0.5 else case when  F_Day27= 'OD' then 0.5 else case when F_Day27='L' then 0 else Case when F_Day27='OFF' then 0 else case when F_Day27='CL' then 0 else case when F_Day27='H' then 0 else case when F_Day27='RH' then 0 else  case when F_Day27='EL' then 0 else Case when F_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27Count,
        SUM(CASE WHEN A_Day27 = 'A' THEN 0 ELSE Case when A_Day27='p' then 0.5 else case when  A_Day27= 'OD' then 0.5 else case when A_Day27='L' then 0 else Case when A_Day27='OFF' then 0 else case when A_Day27='CL' then 0 else case when A_Day27='H' then 0 else case when A_Day27='RH' then 0 else  case when A_Day27='EL' then 0 else Case when A_Day27='Co' then 0 else 0 END END END END END END END END END  END) AS A27ACount,
        SUM(CASE WHEN F_Day28 = 'A' THEN 0 ELSE Case when F_Day28='p' then 0.5 else case when  F_Day28= 'OD' then 0.5 else case when F_Day28='L' then 0 else Case when F_Day28='OFF' then 0 else case when F_Day28='CL' then 0 else case when F_Day28='H' then 0 else case when F_Day28='RH' then 0 else  case when F_Day28='EL' then 0 else Case when F_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28Count,
        SUM(CASE WHEN A_Day28 = 'A' THEN 0 ELSE Case when A_Day28='p' then 0.5 else case when  A_Day28= 'OD' then 0.5 else case when A_Day28='L' then 0 else Case when A_Day28='OFF' then 0 else case when A_Day28='CL' then 0 else case when A_Day28='H' then 0 else case when A_Day28='RH' then 0 else  case when A_Day28='EL' then 0 else Case when A_Day28='Co' then 0 else 0 END END END END END END END END END  END) AS A28ACount,
        SUM(CASE WHEN F_Day29 = 'A' THEN 0 ELSE Case when F_Day29='p' then 0.5 else case when  F_Day29= 'OD' then 0.5 else case when F_Day29='L' then 0 else Case when F_Day29='OFF' then 0 else case when F_Day29='CL' then 0 else case when F_Day29='H' then 0 else case when F_Day29='RH' then 0 else  case when F_Day29='EL' then 0 else Case when F_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29Count,
        SUM(CASE WHEN A_Day29 = 'A' THEN 0 ELSE Case when A_Day29='p' then 0.5 else case when  A_Day29= 'OD' then 0.5 else case when A_Day29='L' then 0 else Case when A_Day29='OFF' then 0 else case when A_Day29='CL' then 0 else case when A_Day29='H' then 0 else case when A_Day29='RH' then 0 else  case when A_Day29='EL' then 0 else Case when A_Day29='Co' then 0 else 0 END END END END END END END END END  END) AS A29ACount,
        SUM(CASE WHEN F_Day30 = 'A' THEN 0 ELSE Case when F_Day30='p' then 0.5 else case when  F_Day30= 'OD' then 0.5 else case when F_Day30='L' then 0 else Case when F_Day30='OFF' then 0 else case when F_Day30='CL' then 0 else case when F_Day30='H' then 0 else case when F_Day30='RH' then 0 else  case when F_Day30='EL' then 0 else Case when F_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30Count,
        SUM(CASE WHEN A_Day30 = 'A' THEN 0 ELSE Case when A_Day30='p' then 0.5 else case when  A_Day30= 'OD' then 0.5 else case when A_Day30='L' then 0 else Case when A_Day30='OFF' then 0 else case when A_Day30='CL' then 0 else case when A_Day30='H' then 0 else case when A_Day30='RH' then 0 else  case when A_Day30='EL' then 0 else Case when A_Day30='Co' then 0 else 0 END END END END END END END END END  END) AS A30ACount,
        SUM(CASE WHEN F_Day31 = 'A' THEN 0 ELSE Case when F_Day31='p' then 0.5 else case when  F_Day31= 'OD' then 0.5 else case when F_Day31='L' then 0 else Case when F_Day31='OFF' then 0 else case when F_Day31='CL' then 0 else case when F_Day31='H' then 0 else case when F_Day31='RH' then 0 else  case when F_Day31='EL' then 0 else Case when F_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31Count,
        SUM(CASE WHEN A_Day31 = 'A' THEN 0 ELSE Case when A_Day31='p' then 0.5 else case when  A_Day31= 'OD' then 0.5 else case when A_Day31='L' then 0 else Case when A_Day31='OFF' then 0 else case when A_Day31='CL' then 0 else case when A_Day31='H' then 0 else case when A_Day31='RH' then 0 else  case when A_Day31='EL' then 0 else Case when A_Day31='Co' then 0 else 0 END END END END END END END END END  END) AS A31ACount into #TempCountDatas
    FROM #AllEmpInOutDetails
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id = #AllEmpInOutDetails.Employee_Code_Id
	inner Join TA_Tbl_EmployeeLevel on TA_Tbl_EmployeeLevel.EmployeeId = TA_Tbl_Employee.Employee_Id
	left Join #Ta_Tbl_levelDetaill on #Ta_Tbl_levelDetaill.id= TA_Tbl_EmployeeLevel.LevelId
    GROUP BY #Ta_Tbl_levelDetaill.name,#Ta_Tbl_levelDetaill.id


	Select @EmployeeCount=Count(*) from #TempCountDatas



 Select #TempCountDatas.id,#TempCountDatas.name,
	FORMAT(ROUND(Sum(A1Count+A1ACount)/ @EmployeeCount * 100,2),'N2') as Day1_Present_Count,
	FORMAT(ROUND(Sum(A2Count+A2ACount)/ @EmployeeCount * 100,2),'N2') as Day2_Present_Count,
	FORMAT(ROUND(Sum(A3Count+A3ACount)/ @EmployeeCount * 100,2),'N2') as Day3_Present_Count,
	FORMAT(ROUND(Sum(A4Count+A4ACount)/ @EmployeeCount * 100,2),'N2') as Day4_Present_Count,
	FORMAT(ROUND(Sum(A5Count+A5ACount)/ @EmployeeCount * 100,2),'N2') as Day5_Present_Count,
	FORMAT(ROUND(Sum(A6Count+A6ACount)/ @EmployeeCount * 100,2),'N2') as Day6_Present_Count,
	FORMAT(ROUND(Sum(A7Count+A7ACount)/ @EmployeeCount * 100,2),'N2') as Day7_Present_Count,
	FORMAT(ROUND(Sum(A8Count+A8ACount)/ @EmployeeCount * 100,2),'N2') as Day8_Present_Count,
	FORMAT(ROUND(Sum(A9Count+A9ACount)/ @EmployeeCount * 100,2),'N2') as Day9_Present_Count,
	FORMAT(ROUND(Sum(A10Count+A10ACount)/ @EmployeeCount * 100,2),'N2') as Day10_Present_Count,
	FORMAT(ROUND(Sum(A11Count+A11ACount)/ @EmployeeCount * 100,2),'N2') as Day11_Present_Count,
	FORMAT(ROUND(Sum(A12Count+A12ACount)/ @EmployeeCount * 100,2),'N2') as Day12_Present_Count,
	FORMAT(ROUND(Sum(A13Count+A13ACount)/ @EmployeeCount * 100,2),'N2') as Day13_Present_Count,
	FORMAT(ROUND(Sum(A14Count+A14ACount)/ @EmployeeCount * 100,2),'N2') as Day14_Present_Count,
	FORMAT(ROUND(Sum(A15Count+A15ACount)/ @EmployeeCount * 100,2),'N2') as Day15_Present_Count,
	FORMAT(ROUND(Sum(A16Count+A16ACount)/ @EmployeeCount * 100,2),'N2') as Day16_Present_Count,
	FORMAT(ROUND(Sum(A17Count+A17ACount)/ @EmployeeCount * 100,2),'N2') as Day17_Present_Count,
	FORMAT(ROUND(Sum(A18Count+A18ACount)/ @EmployeeCount * 100,2),'N2') as Day18_Present_Count,
	FORMAT(ROUND(Sum(A19Count+A19ACount)/ @EmployeeCount * 100,2),'N2') as Day19_Present_Count,
	FORMAT(ROUND(Sum(A20Count+A20ACount)/ @EmployeeCount * 100,2),'N2') as Day20_Present_Count,
	FORMAT(ROUND(Sum(A21Count+A21ACount)/ @EmployeeCount * 100,2),'N2') as Day21_Present_Count,
	FORMAT(ROUND(Sum(A22Count+A22ACount)/ @EmployeeCount * 100,2),'N2') as Day22_Present_Count,
	FORMAT(ROUND(Sum(A23Count+A23ACount)/ @EmployeeCount * 100,2),'N2') as Day23_Present_Count,
	FORMAT(ROUND(Sum(A24Count+A24ACount)/ @EmployeeCount * 100,2),'N2') as Day24_Present_Count,
	FORMAT(ROUND(Sum(A25Count+A25ACount)/ @EmployeeCount * 100,2),'N2') as Day25_Present_Count,
	FORMAT(ROUND(Sum(A26Count+A26ACount)/ @EmployeeCount * 100,2),'N2') as Day26_Present_Count,
	FORMAT(ROUND(Sum(A27Count+A27ACount)/ @EmployeeCount * 100,2),'N2') as Day27_Present_Count,
	FORMAT(ROUND(Sum(A28Count+A28ACount)/ @EmployeeCount * 100,2),'N2') as Day28_Present_Count,
	FORMAT(ROUND(Sum(A29Count+A29ACount)/ @EmployeeCount * 100,2),'N2') as Day29_Present_Count,
	FORMAT(ROUND(Sum(A30Count+A30ACount)/ @EmployeeCount * 100,2),'N2') as Day30_Present_Count,
	FORMAT(ROUND(Sum(A31Count+A31ACount)/ @EmployeeCount * 100,2),'N2') as Day31_Present_Count,
	FORMAT(ROUND(Sum(A1Count + A2Count + A3Count + A4Count + A5Count + A6Count + A7Count + A8Count + A9Count + A10Count + 
     A11Count + A12Count + A13Count + A14Count + A15Count + A16Count + A17Count + A18Count + A19Count + 
     A20Count + A21Count + A22Count + A23Count + A24Count + A25Count + A26Count + A27Count + A28Count + 
     A29Count + A30Count + A31Count +A1ACount + A2ACount + A3ACount + A4ACount + A5ACount + A6ACount + A7ACount + A8ACount + A9ACount + 
     A10ACount + A11ACount + A12ACount + A13ACount + A14ACount + A15ACount + A16ACount + A17ACount + 
     A18ACount + A19ACount + A20ACount + A21ACount + A22ACount + A23ACount + A24ACount + A25ACount + 
     A26ACount + A27ACount + A28ACount + A29ACount + A30ACount + A31ACount)/ @EmployeeCount * 100,2),'N2') as TotalPercenatge

from #TempCountDatas where #TempCountDatas.id!=''
GROUP BY #TempCountDatas.id,#TempCountDatas.name
drop Table #TempCountDatas

	end

	--SELECT * FROM #TempHeader
	
	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
	

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendance_OracleSync]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptDetailAttendance_OracleSync '189,','','0,1','SuperAdmin','0',0,0,'Both',0,0,1,4,2022
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendance_OracleSync]   
(  
	@empId NVARCHAR(max),   
	@EmployeeName NVARCHAR(max),
	@LevelID NVARCHAR(max),  
	@UserGroupName NVARCHAR(250),  
	@GradeLevel NVARCHAR(20)  ,  
	@ParentId int,  
	@DesignationID int,  
	@Gender NVARCHAR(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int,
	@month int,
	@year int
)  
AS  
BEGIN  
	SET NOCOUNT ON
	Declare @fromDat datetime
	Declare @todat datetime
	SET @fromDat= RIGHT('00'+CONVERT(varchar(2),@month),2)+'/01/'+convert(varchar(4),@year)
	
	IF(@month in(1,3,5,7,8,10,12))
	BEGIN
		set @todat=RIGHT('00'+CONVERT(varchar(2),@month),2)+'/31/'+convert(varchar(4),@year)	
	END
	ELSE IF(@month in(4,6,9,11))
	BEGIN
		set @todat=RIGHT('00'+CONVERT(varchar(2),@month),2)+'/30/'+convert(varchar(4),@year)	
	END
	ELSE
	BEGIN
		IF(@year%4=0)
		BEGIN
			set @todat=RIGHT('00'+CONVERT(varchar(2),@month),2)+'/29/'+convert(varchar(4),@year)	
		END	
		ELSE
		BEGIN
			set @todat=RIGHT('00'+CONVERT(varchar(2),@month),2)+'/28/'+convert(varchar(4),@year)	
		END
	END
	--SELECT @fromDat,@todat	
	CREATE TABLE #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),
		[Employee Id] NVARCHAR(50),
		[Department]NVARCHAR(250),
		Present numeric(8,1),
		Absent numeric(8,1),
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		LOPCount float,
		[Total Late Days] numeric(8,1),
		[Total Late Hours] numeric(8,1),
		[Total Early Exit Days] numeric(18,1),
		[Total Early Exit Hours] numeric(8,1) default(0),
		[Total OT Days] numeric(8,1),
		[Total OT Hours] numeric(8,1),
		[Norm OT Hrs] numeric(8,1),
		[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),
		Others numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,		
		Total_HoursWorkInMins int,
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,		
		SwipeCardNo NVARCHAR(50),
		Gender NVARCHAR(20),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	DECLARE @isReportingto AS INT
	CREATE TABLE #EmployeeIds(EmpAutoId int)
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
	CREATE TABLE #EmpAttendanceDetails
	(
		EmployeeID  NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateHours numeric(8,1),
		TotalOTDays numeric(8,1),
		TotalOTHours numeric(8,1),
		NormalOTHrs numeric(8,1),
		WeekOffOTHrs numeric(8,1),
		HolidayOTHours numeric(8,1),
		EarlyOutInMins float,
		TotalEarlyOutDays numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		Total_HoursWorkInMins numeric(8,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,
		LOPCount float,
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #LevelRights(LevelId int)
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id NVARCHAR(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		Shift_Id int,
		TotalDays numeric(18,1),
		LateInMins float,
		OtMins float,
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		EarlyOutMins float,
		HoursWorkInMins decimal(18,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours float,
		PermissionDays int,
		LOPCount float,
		EmpSwipeCardNo NVARCHAR(20),
		EmployeeName nvarchar(200) ,
		Gender NVARCHAR(20),
		Department nvarchar(250),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	INSERT INTO #tempLeavetype SELECT Top 10 LeaveType  FROM ta_tbl_leavetype where LeaveType!='WFH'
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID NVARCHAR(25))
	create table #EmployeeName(EmployeeID NVARCHAR(25))
	if(@empId is not null and @empId <> '')
		begin			
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		left outer join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
		where emp.Isdeleted=0 
		and(1=1 or emp.Employee_Code_Id in(select * from #EmployeeID))
		and(isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in(select * from #EmployeeName))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= @ToDat and EL.LevelId is not null
		
	insert into #TempProcessedData 
	select	E.Employee_Id,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Attendance,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.Shift_Id,
			PD.TotalDays,
			PD.LateInMins,
			PD.OtMins,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			PD.EarlyOutMins,
			isnull(PD.HoursWorkInMins,0),
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) else isnull(PD.SPEC_NormOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins2,PD.SPEC_NormOTMins2) else isnull(PD.SPEC_NormOTMins2,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins1,PD.SPEC_OffOTMins1) else isnull(PD.SPEC_OffOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins2,PD.SPEC_OffOTMins2) else isnull(PD.SPEC_OffOTMins2,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins1,PD.SPEC_HOLOTMins1) else isnull(PD.SPEC_HOLOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins2,PD.SPEC_HOLOTMins2)else isnull(PD.SPEC_HOLOTMins2,0) end,
			Pd.PermissionHrsInMins,
			case when Pd.PermissionHrsInMins > 0 then 1 else 0 end,
			case WHEN (PD.FNAttendanceCode='LOP' and PD.ANAttendanceCode='LOP') THEN 1 WHEN (PD.FNAttendanceCode='LOP' or PD.ANAttendanceCode='LOP') THEN 0.5  ELSE 0 END,
			E.SwipeCardNo,
			E.Employee_FirstName,
			E.Gender,
			ld.name,
			Paymonth=MONTH(pd.Date),
			Payyear=year(pd.Date),
			DATENAME(MONTH,pd.Date)
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN TA_Tbl_Employee  e on E.SwipeCardNo=PD.Employee_Code_Id
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
	Inner join #EMPCATEGORY cat on cat.employeeid=e.Employee_Id 
	Inner join #EMPTYPE type on type.employeeid=e.Employee_Id 
	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	inner join ta_tbl_leveldetails ld on ld.id=#EmpLevel.LevelId	
	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
	where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 
	and (@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level >=@GradeLevel)
	and (isnull(@Gender,'Both')='Both' or  e.Gender =@Gender)
	and (isnull(@isReportingto,0)=0 or (e.Employee_ID IN (select * from #EmployeeIds)))
	and (PD.date >= CONVERT(DATETIME,@fromDat, 102)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
	INSERT INTO #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender,Department,PayMonth,PayYear,PayMonthName) 
	SELECT DISTINCT Employee_Code_Id,Employee_Code_Id,EmployeeName,Gender,Department,PayMonth,PayYear,PayMonthName FROM #TempProcessedData	
	
	INSERT INTO #EmpAttendanceDetails 
	SELECT TPD.Employee_code_Id,  
			Present= 
			sum
			(
				CASE	WHEN FNAttendanceCode='Present'	 AND ANAttendanceCode='Present'		THEN 1.0
						WHEN ((FNAttendanceCode='Present'  AND ANAttendanceCode!='Present')or(FNAttendanceCode!='Present' AND ANAttendanceCode='Present')) THEN 0.5
						WHEN FNAttendanceCode='Comp Off' AND ANAttendanceCode='Comp Off'	THEN 1.0
						WHEN FNAttendanceCode='BL' AND  ANAttendanceCode='BL'				THEN 1.0						
						ELSE 0.0
				END
			),
			Absent=
			sum
			(
				CASE	WHEN FNAttendanceCode='Absent'	 AND  ANAttendanceCode='Absent'	THEN 1.0 
						WHEN ((FNAttendanceCode='Absent' AND  ANAttendanceCode!='Absent') or (FNAttendanceCode!='Absent' AND  ANAttendanceCode='Absent')) THEN 0.5
						WHEN ((FNAttendanceCode IS NULL    AND  ANAttendanceCode IS NULL) or (FNAttendanceCode='' AND ANAttendanceCode=''))	THEN 1
						ELSE 0.0
				END
			), 
			[Total Late Days]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0 THEN  1 else 0 END),
			[Total Late Hours]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0	THEN  lateinmins END),
			[Total OT Days]		=SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN 1 else 0 END),  
			[Total Ot Hours]	=
			isnull(SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN  otmins END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT1,0)!=0 THEN  TPD.Total_Spec_NormOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT2,0)!=0 THEN  TPD.Total_Spec_NormOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT1,0)!=0 THEN  TPD.Total_Spec_OffOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT2,0)!=0 THEN  TPD.Total_Spec_OffOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT1,0)!=0 THEN  TPD.Total_Spec_HOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT2,0)!=0 THEN  TPD.Total_Spec_HOT2 END),0),  
			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,'00:00')='00:00'	THEN 0 ELSE OtMins END), 
			[Total EarlyOut Hours]=SUM(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),  
			[Total EarlyOut Days]=COUNT(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),
			0,
			0,
			0,
			'WeeklyOff'	=sum(CASE WHEN FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' THEN 1 ELSE 0 END),
			'Holiday'	=sum(CASE	WHEN FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' THEN 1 
								WHEN ((FNAttendanceCode='Holiday' and ANAttendanceCode!='Holiday') or (FNAttendanceCode!='Holiday' and ANAttendanceCode='Holiday'))THEN 0.5 
								ELSE 0 
							END), 
			'Leave'		=SUM(CASE WHEN FNAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END) + 
						 SUM(CASE WHEN ANAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END), 
			'LOP'		=SUM(CASE	WHEN FNAttendanceCode='LOP' and ANAttendanceCode='LOP' THEN 1 
									WHEN ((FNAttendanceCode='LOP' and ANAttendanceCode!='LOP') or (FNAttendanceCode!='LOP' and ANAttendanceCode='LOP')) THEN 0.5 
									ELSE 0 
							END), 
			'Total_HoursWorkInMins' =  sum(CASE WHEN isnull(HoursWorkInMins,0)!=0 THEN HoursWorkInMins else 0 END),
			isnull(SUM(TPD.Total_Spec_NormOT1),0),
			isnull(SUM(TPD.Total_Spec_NormOT2),0),
			isnull(SUM(TPD.Total_Spec_OffOT1),0),
			isnull(SUM(TPD.Total_Spec_OffOT2),0),
			isnull(SUM(TPD.Total_Spec_HOT1),0),
			isnull(SUM(TPD.Total_Spec_HOT2),0),
			isnull(SUM(TPD.PermissionHours),0),
			isnull(sum(TPD.PermissionDays),0),
			isnull(sum(TPD.LOPCount),0),
			TPD.PayMonth,
			TPD.PayYear,
			TPD.PayMonthName
			from #TempProcessedData  TPD
			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
			--Inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=TPD.Employee_Code_Id			
			group by TPD.Employee_Code_ID,TPD.PayMonth,TPD.PayYear,TPD.PayMonthName
	
	update #TempDetailedAttendance set Present = TEAD.Present,
	Absent = TEAD.Absent,  
	[Total Late Days]	= TEAD.TotalLateDays,
	[Total Late Hours]	= TEAD.TotalLateHours,  
	[Total OT Days]		= TEAD.TotalOTDays,
	[Total OT Hours]	= TEAD.TotalOTHours,  
	[Norm OT Hrs]		= TEAD.NormalOTHrs,
	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
	[Total Early Exit Hours]=TEAD.EarlyOutInMins,
	[Total Early Exit Days]= TEAD.TotalEarlyOutDays,
	EmployeeCategory	=TEAD.EmployeeCategory,
	EmpCategory			=TEAD.EmpCategory,
	EmployeeType		=TEAD.EmployeeType,
	Total_HoursWorkInMins=TEAD.Total_HoursWorkInMins,
	Total_Spec_NormOT1	=isnull(TEAD.Total_Spec_NormOT1,0),
	Total_Spec_NormOT2	=isnull(TEAD.Total_Spec_NormOT2,0),
	Total_Spec_OffOT1	=isnull(TEAD.Total_Spec_OffOT1,0),
	Total_Spec_OffOT2	=isnull(TEAD.Total_Spec_OffOT2,0),
	Total_Spec_HOT1		=isnull(TEAD.Total_Spec_HOT1,0),
	Total_Spec_HOT2		=isnull(TEAD.Total_Spec_HOT2,0),
	PermissionHours=TEAD.PermissionHours,
	PermissionDays=TEAD.PermissionDays,
	LOPCount = TEAD.LOPCount,
	WeeklyOff=TEAD.WeeklyOff,
	Holiday=TEAD.Holiday,
	PayMonthName=#TempDetailedAttendance.PayMonthName
	from #EmpAttendanceDetails TEAD 
	inner join #TempDetailedAttendance on (TEAD.EmployeeID=#TempDetailedAttendance.SwipeCardNo and TEAD.PayMonth=#TempDetailedAttendance.PayMonth and TEAD.PayYear=#TempDetailedAttendance.PayYear)
	
	
	---Sum of PermissionHours, PermissionDays,LOPCount ---
    update  a set PermissionHours = (b.PermissionHours),PermissionDays = (b.PermissionDays)
	from #TempDetailedAttendance a 
	inner join
	( 
		select EmployeeID,sum(PermissionHours) PermissionHours,sum(PermissionDays)PermissionDays,PayMonth,PayYear 
		from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	update  a set LOPCount = (b.LOPCount)
	from #TempDetailedAttendance a 
	inner join 
	(
		select EmployeeID,sum(LOPCount) LOPCount,PayMonth,PayYear from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	--Inserts the Others details in the temporary table  
	declare @SqlOthers NVARCHAR(4000)  
	create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
	Insert into #Others 
	select Employee_Code_Id ,	
	sum
	(
		CASE	WHEN (FNAttendanceCode='RH' or FNAttendanceCode='LOP' or FNAttendanceCode='ESI') THEN 0.5
				ELSE 0 
		END
	)+ 
	sum
	( 
		CASE WHEN (ANAttendanceCode='RH' or ANAttendanceCode='LOP' or ANAttendanceCode='ESI') THEN 0.5
			 ELSE 0 
		END
	)
	from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance)
	group by Employee_Code_ID
	
	Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
	INSERT INTO #tempLeaveTypeforOthers 
	SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
	LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
	WHERE TLT.Leavetype is null
	declare @LTOthersCount int  
	declare @totLeaveType int
	set @LTOthersCount=1  
	select @totLeaveType=count(*) from #tempLeaveTypeforOthers
	while(@LTOthersCount<=@totLeaveType)  
		BEGIN  
			declare @LeaveTypeForOthers NVARCHAR(10)  
			select @LeaveTypeForOthers =LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount
			declare @SqlUpdateOthers NVARCHAR(3000)
			set @SqlUpdateOthers=''
			set @SqlUpdateOthers = @SqlUpdateOthers + ' Update #Others set Others = Others + A.TotalDays from '   
			set @SqlUpdateOthers =@SqlUpdateOthers  + ' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END)'  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' + sum( CASE PD.ANAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else PD.TotalDays END else 0 END)) as TotalDays'
			set @SqlUpdateOthers = @SqlUpdateOthers + ' from #TempProcessedData PD '  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' group by PD.Employee_Code_Id) A'  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id'  
			set @LTOthersCount=@LTOthersCount+1  
			exec(@SqlUpdateOthers)  
		END
	--Updates the Others column in the temporary table  
	update #TempDetailedAttendance set Others=#Others.Others from #Others 
	inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo
	
	--Adding the Leave type column in the #TempDetailedAttendance table.  
	declare @LeaveTypeCount int  
	set @LeaveTypeCount=1  
	declare @Column NVARCHAR(max)
	set @Column=''
	declare @Column_Sum NVARCHAR(max)
	set @Column_Sum=''
	while(@LeaveTypeCount<=10)  
		BEGIN  
			declare @LeaveType nvarchar(50)  
			set @LeaveType=''
			select @LeaveType=Leavetype from #tempLeavetype where slno=@LeaveTypeCount
			if @LeaveType is not null and @LeaveType!=''
			BEGIN
				DECLARE @AlterQuery NVARCHAR(100)  
				set @AlterQuery='Alter table #TempDetailedAttendance add [' + @LeaveType + '] numeric(18,1)'  
				if(@Column='')
				begin
					set @Column=quotename(@LeaveType)
					set @Column_Sum=quotename(@LeaveType)
				end
				else
				begin
					set @Column=@Column+','+quotename(@LeaveType)
					set @Column_Sum=@Column_Sum+'+'+quotename(@LeaveType)
				end
				exec(@AlterQuery)  
				set @AlterQuery=''
				declare @UpdateQuery NVARCHAR(4000)  
				set @UpdateQuery=''
				set @UpdateQuery = @UpdateQuery + 'update #TempDetailedAttendance  set ['+ @LeaveType +']'  
				set @UpdateQuery = @UpdateQuery + '=A.TotalDays from'  
				set @UpdateQuery = @UpdateQuery +' (select Employee_Code_ID,TDA.PayMonth,TDA.PayYear,(sum(CASE WHEN PD.FNAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END) '  
				set @UpdateQuery = @UpdateQuery + ' + sum(CASE WHEN PD.ANAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END)) as TotalDays '  
				set @UpdateQuery = @UpdateQuery + ' from #TempProcessedData PD'  
				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TDA on (TDA.SwipeCardNo=PD.Employee_code_ID and TDA.PayMonth=PD.PayMonth and TDA.PayYear=PD.PayYear)'
				set @UpdateQuery = @UpdateQuery + ' group by PD.Employee_Code_ID,TDA.PayMonth,TDA.PayYear) A'  
				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID AND TempAttendance.PayMonth=A.PayMonth AND TempAttendance.PayYear=A.PayYear'  
				exec(@UpdateQuery)  
				--PRINT(@UpdateQuery)  
				set @UpdateQuery=''
			end
			set @LeaveTypeCount=@LeaveTypeCount+1  
	END  
	
		
	--SELECT * FROM #TempDetailedAttendance 
	declare @SqlPresent NVARCHAR(max)
	set @SqlPresent=''
	set @SqlPresent=@SqlPresent+' select 
		[Employee Id],
		[Employee Name],
		SwipeCardNo,				
		Gender,	
		Present,
		Absent,
		WeeklyOff,
		Holiday,				
		[Total Late Days],		
		[Total Early Exit Days],		
		[Total OT Days],		
		[Norm OT Hrs]=dbo.ConvertMinsToHours([Norm OT Hrs]),
		[WeekOff OT Hrs]=dbo.ConvertMinsToHours([WeekOff OT Hrs]),
		[Holiday OT Hrs]=dbo.ConvertMinsToHours([Holiday OT Hrs]),
		Others,
		Total_HoursWorkInMins=dbo.ConvertMinsToHours(Total_HoursWorkInMins),		
		[WD Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
		[WD Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_NormOT2),
		[WO Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_OffOT1),
		[WO Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_OffOT2),
		[H Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_HOT1),
		[H Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_HOT2),
		PermissionHours=dbo.ConvertMinsToHours(PermissionHours) 
		,PermissionDays 
		,LOPCount
		,[Total Late Hours]=dbo.ConvertMinsToHours([Total Late Hours]),
		[Total Early Exit Hours]=dbo.ConvertMinsToHours([Total Early Exit Hours]),
		[Total OT Hours]=dbo.ConvertMinsToHours([Total OT Hours]),
		PayDays=Present+WeeklyOff+Holiday+'+(@Column_Sum)+'
		,TotalDays=DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)),0))),
		[Month]=PaymonthName,
		'+(@Column)+'
		
		--,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)
	 from #TempDetailedAttendance where 1=1 order by PayMonth,paymonthName,[Employee Id] '	
	--print (@SqlPresent) 
	exec (@SqlPresent)
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpAttendanceDetails  
	drop table #Others  
	drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author        : Sashma  
-- Create date   : 06-July-2010  
-- Modified date : 12-May-2011  
-- Description   : <Description,,>  
--Modified By    : Thilakraj C  
-- Modified Date : 19-Jul-2013  
-- Description   : Due to Neuland requirement Check the Employee Inactivate Date.  
--Modified By    : Gopinath.k
-- Modified Date : 20-Dec-2013 & 11-Jan-2014
-- Description   :SQL Query Optimization & Emp name filtering
-- =============================================  
-- Proc_TA_RptDetailAttendanceDynamic '01/Jan/2016','31/Jan/2016','957','','0','SuperAdmin','0','',0,0,'Both',0
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,  
  @DesignationID int,  
  @Gender varchar(10),   
	@ParentID bigint,
	@Export int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	-------Start
	declare @query as varchar(8000)
	set @query=''
	set @query = 'select isnull(Employee_FirstName,'''') + SPACE(1) + isnull(Employee_MiddleName,'''')+ SPACE(1) + isnull(Employee_LastName,'''')  + ''$'' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],'
	set @query = @query + ' ''Present'' = sum( 
	CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END 
	When ''|'' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END)+
sum( CASE FNAttendanceCode WHEN ''CL'' THEN case when ANAttendanceCode=''Weekly Off'' then
			Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END END
			WHEN ''SL'' THEN case when ANAttendanceCode=''Weekly Off'' then
			Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END END
else 0 END) + 
sum( CASE ANAttendanceCode WHEN ''CL'' THEN case when FNAttendanceCode=''Weekly Off'' then
Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END end
WHEN ''SL'' THEN case when FNAttendanceCode=''Weekly Off'' then
Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END end
else 0 END)
	,'
	set @query = @query + ' ''Absent'' = sum( CASE FNAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	--angler Specific
	--set @query = @query + ' ''Weekly Off'' = sum( CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	set @query = @query + ' ''Weekly Off'' = sum( case when upper(DATENAME(dw,Date)) = ''SUNDAY'' then CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END END) + sum(case when upper(DATENAME(dw,Date)) = ''SUNDAY'' then CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END END),'
	set @query = @query + ' ''Holiday'' = sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	set @query = @query + ' ''CompOff'' = sum( CASE FNAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	--set @query = @query + ' ''LOP'' = 
	--sum
	--(
	--	CASE	When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN	1
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''LOP'' THEN	1	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Present'' THEN	0.5	
	--			When FNAttendanceCode=''Present'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''CL'' THEN	0.5	
	--			When FNAttendanceCode=''CL'' and ANAttendanceCode=''LOP'' THEN	0.5				
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''CompOff'' THEN	0.5	
	--			When FNAttendanceCode=''CompOff'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''SL'' THEN	0.5	
	--			When FNAttendanceCode=''SL'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Holiday'' THEN	0.5	
	--			When FNAttendanceCode=''Holiday'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			else 0 
	--	END
	--)	 ,'
     	set @query = @query + ' ''LOP'' = sum( CASE FNAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	-------
	set @query = @query + ' ''Total Late Days'' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , '
	set @query = @query + ' ''Total Late Hours'' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), '
	--angler Specific
	set @query = @query + ' ''Total Early Out Days'' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , '
	set @query = @query + ' ''Total Early Out Hours'' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), '
	set @query = @query + ' ''Total OT Days'' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , '
	set @query = @query + ' ''Total Ot Hours'' =  sum(CASE otmins WHEN otmins THEN  otmins END), '
	set @query = @query + ' ''Norm OT Hrs''=sum(CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''WeekOff OT Hrs''=sum(CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''Holiday OT Hrs''=sum(CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),'
	--For approved only
	--set @query = @query + ' ''Total OT Days'' =  count(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END) , '
	--set @query = @query + ' ''Total Ot Hours'' =  sum(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END), '
	--set @query = @query + ' replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as Level,'
	--set @query = @query + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,'
	DECLARE @sql varchar(8000)
	DECLARE @sumfunc varchar(200)
	set @sumfunc = 'sum(Totaldays)'
	DECLARE @sumfunc1 varchar(100)
	declare @pivot varchar(100)
	declare @pivot1 varchar(100)
	--set @pivot ='LeaveCode'
	set @pivot ='FNAttendanceCode'
	set @pivot1 ='ANAttendanceCode'
	Declare @TotalLeaveCount Decimal(10,5)
	Set @TotalLeaveCount=0;
	---- get the leave type details and form query
	EXEC ('SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2')
	CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
	(
	[pivot] ASC
	) ON [PRIMARY]
	exec ('INSERT INTO ##pivot select top 5 LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
	SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )
	declare @delim  varchar(1)
	SELECT  @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) 
	WHEN 0 THEN '' ELSE '''' END 
	FROM tempdb.information_schema.columns 
	WHERE table_name='##pivot' AND column_name='pivot'
	select @sql=''
	SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
	+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
	--		+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
	FROM ##pivot order by [pivot]
	if len(@sql)>0
	SELECT @sql=left(@sql, len(@sql)-1)
	-- end of leave type
	---- other leave type
	declare @SelectedLeaveType as varchar(500)
	set @SelectedLeaveType =''
	SELECT @SelectedLeaveType=@SelectedLeaveType + '''' + convert(varchar(100), [pivot]) + ''' , ' 
	FROM ##pivot
	delete  from ##pivot
	if len(@SelectedLeaveType)>0
		begin
			SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
			exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0 and leavetype not in (' + @SelectedLeaveType + ' )  order by leavetype')
		end
	else
		begin
			exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
		end
	--delete  from ##pivot
	declare @othSql as varchar(5000)
	select @othSql=''
	--SELECT @othSql=@othSql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
	/*		
	SELECT @othSql=@othSql + ' ' 
	+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
	FROM ##pivot order by [pivot]
	*/
	if (len(@othSql)>0) 
		begin
			SELECT @othSql=left(@othSql, len(@othSql)-1) + '+'
		end
	set @query = @query + ' ''Others'' =  ' + @othSql + ' sum( CASE FNAttendanceCode WHEN ''RH'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)'
	set @query = @query + ' + sum( CASE ANAttendanceCode WHEN ''RH'' THEN Case TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END),'
	set @query = @query + ' ''CL'' =   sum( CASE FNAttendanceCode WHEN ''CL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''CL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END), '
	set @query = @query + ' ''SL'' =   sum( CASE FNAttendanceCode WHEN ''SL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) +sum( CASE ANAttendanceCode WHEN ''SL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END)'
--For satoff
	--set @query=  @query + ' ,SUM(case when upper(DATENAME(dw,Date)) = ''Saturday'' then 
	--                                                       case when FNAttendanceCode = ''Absent'' and ANAttendanceCode =''Absent'' and 
	--                                              ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')
	--                                              then 1 else 0 end
	--                                                else 0 end ) as ''Saturday Off'''
	set @query=  @query + ' ,     SUM(case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
	                                                       CASE  when FNAttendanceCode = ''Absent'' or ANAttendanceCode =''Absent'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN  1
	                                                         when FNAttendanceCode = ''Absent'' and ANAttendanceCode=''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN 1
	                                                         when FNAttendanceCode= ''Weekly Off'' and ANAttendanceCode =''Absent''  and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')THEN 1
	                                                         when FNAttendanceCode = ''Weekly Off'' and ANAttendanceCode =''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') then 1 
	  													   end 
														   else 
														      0		
														   end 
							 )   as ''Saturday Off'''                                                
	              --             set @query=  @query + ' , SUM(case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
															--Case when (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Weekly Off'') then 1 
															--	 else case when ( (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Present'') or (ANAttendanceCode=''Present'' and FNAttendanceCode=''Weekly Off'') ) then 0.5  
               --                                                            else case when ( (ANAttendanceCode=''Present'' and FNAttendanceCode=''Present'')  ) then 0  
															--						 else case when (ANAttendanceCode=''Weekly Off'' or FNAttendanceCode=''Weekly Off'') then 0.5
															--end 
			            --                                    end  
															--end
															--end 
								       --                    	end
               --                                                           ) as [Intimation] '                         
	 set @query=  @query + ' , SUM(
				case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
							Case	when (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Weekly Off'') then 1 
									else	case	when ((ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Present'') 
													  or (ANAttendanceCode=''Present'' and FNAttendanceCode=''Weekly Off'') ) then 0.5  
													else 0
													--case	when ((ANAttendanceCode=''Present'' and FNAttendanceCode=''Present'')  ) then 0  
													--			else	case	when (ANAttendanceCode=''Weekly Off'' or FNAttendanceCode=''Weekly Off'') then 0.5
													--					end 
													--	 end  
											end
									end 
					end
                                                                          ) as [Intimation] '                                  
	--end of other leave type
	--if len(@sql)=0
	--SELECT @query=left(@query, len(@query)-1)
	--set @query  = @query + @sql
	declare @query1 as varchar(8000) 
	set @query1=''
	set @query1 = @query1 + ' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo'
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @query1 = @query1 + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id '
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId'
	set @query1 = @query1 + ' inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId'
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId'
	set @query1 = @query1 + ' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID '
		end
	set @query1 = @query1 + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @query1 = @query1 + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	set @query1 = @query1 + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId '
	set @query1 = @query1 + ' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId '
	set @query1 = @query1 + ' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1'
	set @query1 = @query1 + ' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
	set @query1 = @query1 + ' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel 
			--+  ' AND (ta_tbl_employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or ta_tbl_employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''') '
		end
	if not(@EmployeeName='')
		begin
		--	set @query1 = @query1 + ' and ta_tbl_employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		Declare @Tempname nvarchar(200)
    set @Tempname= '(ta_tbl_employee.Employee_FirstName + '' '' + isnull(ta_tbl_employee.Employee_LastName,'''')'
	set @query1 = @query1 + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 	
		end
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @query1 = @query1 + 'And ta_tbl_employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End
	if not (@empId='')
		begin
			set @query1 = @query1 + ' and ta_tbl_employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
	if(@DesignationID<>0)  
		 begin  
			set @query1 = @query1 + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))  
		end  
	if(@Gender<>'Both')  
		begin  
			 set @query1 = @query1 + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		 end  
	--if(@EmpAutoId = 0)
	--	BEGIN
	--		if not(@LevelID='' or @LevelID='0')
	--			begin
	--				set @query1 = @query1 + ' and #EmpLevel.LevelId IN ( ' + @LevelId + ') ' 
	--			end	
	--	END
	if(@isReportingto > 0)
		BEGIN
			set @query1 = @query1 + ' and (ta_tbl_employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	set @query1 = @query1 + ' group by  ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname'
	create table #TempFinal ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] int,[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,Others decimal(18,1),CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,Intimation DECIMAL(18,2))
	DROP TABLE ##pivot
	--exec  (@query + ' ' + @query1)
	insert into #TempFinal 
	exec  (@query + ' ' + @query1)
	--select TF.*,C.CategoryName as [Employee Category]from #TempFinal TF
	--Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	--inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	--inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId order by TF.[Employee Id] 
	--select * from #TempFinal 
    create table #TempFinal2 ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] varchar(50),[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,[Employee Category] nvarchar(500),Others decimal(18,1),CategoryId int,Intimation DECIMAL(18,2))
	Insert into #TempFinal2 
	select [Employee Name] ,[Employee Id] ,Present ,Absent ,[Weekly Off] ,
	Holiday ,CompOff ,Lop ,[Total Late Days] ,
	case when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
				+ '0' +convert(varchar(20),[Total Late Hours]/60) + ':0' + CONVERT(varchar(20),[Total Late Hours]%60)  
	     when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=2 then 
	     + '0' +convert(varchar(20),[Total Late Hours]/60) + ':' + CONVERT(varchar(20),[Total Late Hours]%60)
	     when len(convert(varchar(20),[Total Late Hours]/60))=2 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
	     convert(varchar(20),[Total Late Hours]/60) + ':0' + CONVERT(varchar(20),[Total Late Hours]%60)
	else convert(varchar(20),[Total Late Hours]/60) + ':' +CONVERT(varchar(20),[Total Late Hours]%60)  
	end 
	,[Total Early Out Days] ,[Total Early Out Hours] ,
	[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off]
	,C.CategoryName as [Employee Category],Others,C.CategoryId ,Intimation from #TempFinal TF
	Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId
	Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId 
	order by [Employee Id]	
		declare @BelowCategoryId as int
	set @BelowCategoryId=(select top 1 CategoryId from TA_Tbl_Category  order by MonToSat_WorkHrs desc,Sat_WorkHrs desc)
	update #TempFinal2 set [Saturday Off]=0 where CategoryId=@BelowCategoryId 
	update #TempFinal2 set [Intimation]=0 where CategoryId=@BelowCategoryId 
	--update #TempFinal2 set Present=Present+[Saturday Off] where [Employee Id]
	--Update #TempFinal2 Set Present =1 Where upper(DATENAME(dw,Date)) = ''Saturday'' THEN 
	--                                                       CASE  when FNAttendanceCode = ''Absent'' and ANAttendanceCode =''Absent'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN  1
	--                                                         when FNAttendanceCode = ''Absent'' and FNAttendanceCode=''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN 1
	--                                                         when FNAttendanceCode= ''Weekly Off'' and FNAttendanceCode =''Absent''  and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')THEN 1
	--                                                         when FNAttendanceCode = ''Weekly Off'' and FNAttendanceCode =''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') then 1 
	if(@Export=0)
	begin
		select [Employee Name] ,[Employee Id] ,Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,
		Holiday ,CompOff ,Lop ,[Total Late Days] ,isnull([Total Late Hours],'00:00')[Total Late Hours]  ,[Total Early Out Days] ,[Total Early Out Hours],[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off],[Employee Category],Others,CategoryId ,Intimation from #TempFinal2
	end
	else
	begin
		select ROW_NUMBER()over(order by [Employee Id])[Sl.No],[Employee Id] ,SUBSTRING([Employee Name],0,charindex('$',[Employee Name]))[Employee Name],[Employee Category],Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,[Saturday Off],
		Holiday ,CompOff ,Lop ,CL,SL,isnull([Total Late Hours],'00:00')[Total Late Hours]  ,[Total Late Days] from #TempFinal2
	end
	drop table #tempFinal
	drop table #TempFinal2
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic1]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select * from ta_tbl_processeddata where date between '2009/10/01' and '2009/10/30' and employee_code_id='501' order by date
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
--drop procedure Proc_TA_RptDetailAttendanceDynamic
--Proc_TA_RptDetailAttendanceDynamic '2010/01/01','2010/01/31','','','115','SuperAdmin','0',''
create     PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic1] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
set @fromDat='2010/01/01'
set @ToDat='2010/01/31'
set @empId=''
set @EmployeeName=''
set @LevelID='110'
set @UserGroupName='SuperAdmin'
set @GradeLevel='0'
set @EmpSwipeCard=''
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
-------Start
		declare @query as varchar(8000)
		set @query=''
		set @query = 'select isnull(Employee_FirstName,'''') + SPACE(1) + isnull(Employee_MiddleName,'''')+ SPACE(1) + isnull(Employee_LastName,'''')  + ''$'' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],'
	    	set @query = @query + ' ''Present'' = sum( CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END When ''|'' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		set @query = @query + ' ''Absent'' = sum( CASE FNAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		--angler Specific
		set @query = @query + ' ''Weekly Off'' = sum( CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		set @query = @query + ' ''Holiday'' = sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		set @query = @query + ' ''CompOff'' = sum( CASE FNAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		set @query = @query + ' ''LOP'' = sum( CASE FNAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
		-------
		set @query = @query + ' ''Total Late Days'' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , '
		set @query = @query + ' ''Total Late Hours'' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), '
		--angler Specific
		set @query = @query + ' ''Total Early Out Days'' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , '
		set @query = @query + ' ''Total Early Out Hours'' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), '
		set @query = @query + ' ''Total OT Days'' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , '
		set @query = @query + ' ''Total Ot Hours'' =  sum(CASE otmins WHEN otmins THEN  otmins END), '
		set @query = @query + ' ''Norm OT Hrs''=sum(CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''WeekOff OT Hrs''=sum(CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''Holiday OT Hrs''=sum(CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),'
--For approved only
		--set @query = @query + ' ''Total OT Days'' =  count(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END) , '
		--set @query = @query + ' ''Total Ot Hours'' =  sum(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END), '
		--set @query = @query + ' replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as Level,'
		--set @query = @query + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,'
		DECLARE @sql varchar(8000)
		DECLARE @sumfunc varchar(2000)
		set @sumfunc = 'sum(Totaldays)'
		DECLARE @sumfunc1 varchar(1000)
		declare @pivot varchar(1000)
		declare @pivot1 varchar(1000)
		--set @pivot ='LeaveCode'
		set @pivot ='FNAttendanceCode'
		set @pivot1 ='ANAttendanceCode'
---- get the leave type details and form query
		EXEC ('SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2')
CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
(
	[pivot] ASC
) ON [PRIMARY]
		exec ('INSERT INTO ##pivot select top 5 LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
		SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )
		declare @delim  varchar(1)
		SELECT  @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) 
		WHEN 0 THEN '' ELSE '''' END 
		FROM tempdb.information_schema.columns 
		WHERE table_name='##pivot' AND column_name='pivot'
		select @sql=''
		SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
		+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
--		+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' 
		+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
		+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
		FROM ##pivot order by [pivot]
		if len(@sql)>0
			SELECT @sql=left(@sql, len(@sql)-1)
-- end of leave type
---- other leave type
		declare @SelectedLeaveType as varchar(500)
		set @SelectedLeaveType =''
		SELECT @SelectedLeaveType=@SelectedLeaveType + '''' + convert(varchar(100), [pivot]) + ''' , ' 
		FROM ##pivot
delete  from ##pivot
		if len(@SelectedLeaveType)>0
			begin
				SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
				exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0 and leavetype not in (' + @SelectedLeaveType + ' )  order by leavetype')
			end
		else
			begin
				exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
			end
		--delete  from ##pivot
		declare @othSql as varchar(5000)
		select @othSql=''
		--SELECT @othSql=@othSql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
		SELECT @othSql=@othSql + ' ' 
		+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
		+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
		+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
		FROM ##pivot order by [pivot]
		if (len(@othSql)>0) 
			begin
				SELECT @othSql=left(@othSql, len(@othSql)-1) + '+'
			end
			set @query = @query + ' ''Others'' =  ' + @othSql + ' sum( CASE FNAttendanceCode WHEN ''RH'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)'
			set @query = @query + ' + sum( CASE ANAttendanceCode WHEN ''RH'' THEN Case TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END),'
--end of other leave type
if(len(@sql)=0)
begin	
SET @query=left(@query, len(@query)-1)
end
		set @query  = @query + @sql
		declare @query1 as varchar(8000) 
		set @query1=''
		set @query1 = @query1 + ' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo'
		set @query1 = @query1 + ' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @query1 = @query1 + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id '
		set @query1 = @query1 + ' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId'
		set @query1 = @query1 + ' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID '
		end
		set @query1 = @query1 + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @query1 = @query1 + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @query1 = @query1 + ' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1'
		set @query1 = @query1 + ' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
		set @query1 = @query1 + ' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
		if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		if not(@EmployeeName='')
		begin
			set @query1 = @query1 + ' and ta_tbl_employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		end
		If Not (@EmpSwipeCard = '')  
			 Begin  
			  Set @query1 = @query1 + 'And ta_tbl_employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			 End
		if not (@empId='')
		begin
			set @query1 = @query1 + ' and ta_tbl_employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
		if not(@LevelID='' or @LevelID='0')
		begin
			set @query1 = @query1 + ' and #EmpLevel.LevelId IN ( ' + @LevelId + ') ' 
		end	
		set @query1 = @query1 + ' group by ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname'
		DROP TABLE ##pivot
		exec  (@query + ' ' + @query1)
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
/*
select 'a$EIT' as [Employee Name],'1' as [Employee Id],'20' as Present,'2' as Absent,'4' as [Weekly Off],'1' as Holiday,'0' as CompOff
,'0' as LOP
,'0' as [Total Late Days]
,'0' as [Total Late Hours]
,'0' as [Total Early Out Days]
,'0' as [Total Early Out Hours]
,'0' as [Total OT Days]
,'0' as [Total Ot Hours]
,'0' as [Norm Ot Hrs]
,'0' as [WeekOff OT Hrs]
,'0' as [Holiday OT Hrs]
,'0' as Others
,'0' as CL
,'0' as ML
*/
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicExport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author        : Sashma  
-- Create date   : 06-July-2010  
-- Modified date : 12-May-2011  
-- Description   : <Description,,>  
--Modified By    : Thilakraj C  
-- Modified Date : 19-Jul-2013  
-- Description   : Due to Neuland requirement Check the Employee Inactivate Date.  
--Modified By    : Gopinath.k
-- Modified Date : 20-Dec-2013 & 11-Jan-2014
-- Description   :SQL Query Optimization & Emp name filtering
-- =============================================  
-- [Proc_TA_RptDetailAttendanceDynamicExport] '01/jul/2016','31/jul/2016','','','0','SuperAdmin','0','',0,0,'Both',0
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicExport] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,  
    @DesignationID int,  
    @Gender varchar(10),   
	@ParentID bigint
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	-------Start
	declare @query as varchar(8000)
	set @query=''
	set @query = 'select isnull(Employee_FirstName,'''') + SPACE(1) + isnull(Employee_MiddleName,'''')+ SPACE(1) + isnull(Employee_LastName,'''')  + ''$'' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],'
	set @query = @query + ' ''Present'' = sum( 
	CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END 
	When ''|'' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END)+
sum( CASE FNAttendanceCode WHEN ''CL'' THEN case when ANAttendanceCode=''Weekly Off'' then
			Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END END
			WHEN ''SL'' THEN case when ANAttendanceCode=''Weekly Off'' then
			Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END END
else 0 END) + 
sum( CASE ANAttendanceCode WHEN ''CL'' THEN case when FNAttendanceCode=''Weekly Off'' then
Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END end
WHEN ''SL'' THEN case when FNAttendanceCode=''Weekly Off'' then
Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END end
else 0 END)
	,'
	set @query = @query + ' ''Absent'' = sum( CASE FNAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Absent'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	--angler Specific
	--set @query = @query + ' ''Weekly Off'' = sum( CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	set @query = @query + ' ''Weekly Off'' = sum( case when upper(DATENAME(dw,Date)) = ''SUNDAY'' then CASE FNAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END END) + sum(case when upper(DATENAME(dw,Date)) = ''SUNDAY'' then CASE ANAttendanceCode WHEN ''Weekly Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END END),'
	set @query = @query + ' ''Holiday'' = sum( CASE FNAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Holiday'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	set @query = @query + ' ''CompOff'' = sum( CASE FNAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''Comp Off'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	--set @query = @query + ' ''LOP'' = 
	--sum
	--(
	--	CASE	When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN	1
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''LOP'' THEN	1	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Present'' THEN	0.5	
	--			When FNAttendanceCode=''Present'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''CL'' THEN	0.5	
	--			When FNAttendanceCode=''CL'' and ANAttendanceCode=''LOP'' THEN	0.5				
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''CompOff'' THEN	0.5	
	--			When FNAttendanceCode=''CompOff'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''SL'' THEN	0.5	
	--			When FNAttendanceCode=''SL'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			When FNAttendanceCode=''LOP'' and ANAttendanceCode=''Holiday'' THEN	0.5	
	--			When FNAttendanceCode=''Holiday'' and ANAttendanceCode=''LOP'' THEN	0.5	
	--			else 0 
	--	END
	--)	 ,'
     	set @query = @query + ' ''LOP'' = sum( CASE FNAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''LOP'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),'
	-------
	set @query = @query + ' ''Total Late Days'' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , '
	set @query = @query + ' ''Total Late Hours'' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), '
	--angler Specific
	set @query = @query + ' ''Total Early Out Days'' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , '
	set @query = @query + ' ''Total Early Out Hours'' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), '
	set @query = @query + ' ''Total OT Days'' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , '
	set @query = @query + ' ''Total Ot Hours'' =  sum(CASE otmins WHEN otmins THEN  otmins END), '
	set @query = @query + ' ''Norm OT Hrs''=sum(CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''WeekOff OT Hrs''=sum(CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),''Holiday OT Hrs''=sum(CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END),'
	--For approved only
	--set @query = @query + ' ''Total OT Days'' =  count(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END) , '
	--set @query = @query + ' ''Total Ot Hours'' =  sum(CASE OvertimeStatus WHEN ''Approved'' THEN  otmins END), '
	--set @query = @query + ' replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as Level,'
	--set @query = @query + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,'
	DECLARE @sql varchar(8000)
	DECLARE @sumfunc varchar(200)
	set @sumfunc = 'sum(Totaldays)'
	DECLARE @sumfunc1 varchar(100)
	declare @pivot varchar(100)
	declare @pivot1 varchar(100)
	--set @pivot ='LeaveCode'
	set @pivot ='FNAttendanceCode'
	set @pivot1 ='ANAttendanceCode'
	Declare @TotalLeaveCount Decimal(10,5)
	Set @TotalLeaveCount=0;
	---- get the leave type details and form query
	EXEC ('SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2')
	CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
	(
	[pivot] ASC
	) ON [PRIMARY]
	exec ('INSERT INTO ##pivot select top 5 LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
	SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )
	declare @delim  varchar(1)
	SELECT  @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) 
	WHEN 0 THEN '' ELSE '''' END 
	FROM tempdb.information_schema.columns 
	WHERE table_name='##pivot' AND column_name='pivot'
	select @sql=''
	SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
	+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
	--		+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5'' When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
	FROM ##pivot order by [pivot]
	if len(@sql)>0
	SELECT @sql=left(@sql, len(@sql)-1)
	-- end of leave type
	---- other leave type
	declare @SelectedLeaveType as varchar(500)
	set @SelectedLeaveType =''
	SELECT @SelectedLeaveType=@SelectedLeaveType + '''' + convert(varchar(100), [pivot]) + ''' , ' 
	FROM ##pivot
	delete  from ##pivot
	if len(@SelectedLeaveType)>0
		begin
			SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
			exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0 and leavetype not in (' + @SelectedLeaveType + ' )  order by leavetype')
		end
	else
		begin
			exec ('INSERT INTO ##pivot select LeaveType as ' + @pivot + ' from ta_tbl_leavetype where isdeleted=0  order by leavetype')
		end
	--delete  from ##pivot
	declare @othSql as varchar(5000)
	select @othSql=''
	--SELECT @othSql=@othSql + '''' + convert(varchar(100), [pivot]) + ''' = ' 
	/*		
	SELECT @othSql=@othSql + ' ' 
	+ stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5''  when null then 0 Else '   )+  ' else 0 End )+ ' +   stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot1 + ' WHEN  '
	+ @delim + convert(varchar(100), [pivot]) + @delim + ' Then (Case TotalDays When ''0.5'' Then ''0.5''  When ''1.0'' Then ''0.5'' when null then 0 Else '   ) + ' else 0 End )' + ', ' 
	FROM ##pivot order by [pivot]
	*/
	if (len(@othSql)>0) 
		begin
			SELECT @othSql=left(@othSql, len(@othSql)-1) + '+'
		end
	set @query = @query + ' ''Others'' =  ' + @othSql + ' sum( CASE FNAttendanceCode WHEN ''RH'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END)'
	set @query = @query + ' + sum( CASE ANAttendanceCode WHEN ''RH'' THEN Case TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''ESI'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END else 0 END),'
	set @query = @query + ' ''CL'' =   sum( CASE FNAttendanceCode WHEN ''CL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''CL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END), '
	set @query = @query + ' ''SL'' =   sum( CASE FNAttendanceCode WHEN ''SL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END) +sum( CASE ANAttendanceCode WHEN ''SL'' THEN Case TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else TotalDays END else 0 END)'
--For satoff
	--set @query=  @query + ' ,SUM(case when upper(DATENAME(dw,Date)) = ''Saturday'' then 
	--                                                       case when FNAttendanceCode = ''Absent'' and ANAttendanceCode =''Absent'' and 
	--                                              ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')
	--                                              then 1 else 0 end
	--                                                else 0 end ) as ''Saturday Off'''
	set @query=  @query + ' ,     SUM(case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
	                                                       CASE  when FNAttendanceCode = ''Absent'' or ANAttendanceCode =''Absent'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN  1
	                                                         when FNAttendanceCode = ''Absent'' and ANAttendanceCode=''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN 1
	                                                         when FNAttendanceCode= ''Weekly Off'' and ANAttendanceCode =''Absent''  and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')THEN 1
	                                                         when FNAttendanceCode = ''Weekly Off'' and ANAttendanceCode =''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') then 1 
	  													   end 
														   else 
														      0		
														   end 
							 )   as ''Saturday Off'''                                                
	              --             set @query=  @query + ' , SUM(case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
															--Case when (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Weekly Off'') then 1 
															--	 else case when ( (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Present'') or (ANAttendanceCode=''Present'' and FNAttendanceCode=''Weekly Off'') ) then 0.5  
               --                                                            else case when ( (ANAttendanceCode=''Present'' and FNAttendanceCode=''Present'')  ) then 0  
															--						 else case when (ANAttendanceCode=''Weekly Off'' or FNAttendanceCode=''Weekly Off'') then 0.5
															--end 
			            --                                    end  
															--end
															--end 
								       --                    	end
               --                                                           ) as [Intimation] '                         
	 set @query=  @query + ' , SUM(
				case when upper(DATENAME(dw,Date)) = ''SATURDAY'' THEN 
							Case	when (ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Weekly Off'') then 1 
									else	case	when ((ANAttendanceCode=''Weekly Off'' and FNAttendanceCode=''Present'') 
													  or (ANAttendanceCode=''Present'' and FNAttendanceCode=''Weekly Off'') ) then 0.5  
													else 0
													--case	when ((ANAttendanceCode=''Present'' and FNAttendanceCode=''Present'')  ) then 0  
													--			else	case	when (ANAttendanceCode=''Weekly Off'' or FNAttendanceCode=''Weekly Off'') then 0.5
													--					end 
													--	 end  
											end
									end 
					end
                                                                          ) as [Intimation] '                                  
	--end of other leave type
	--if len(@sql)=0
	--SELECT @query=left(@query, len(@query)-1)
	--set @query  = @query + @sql
	declare @query1 as varchar(8000) 
	set @query1=''
	set @query1 = @query1 + ' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo'
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @query1 = @query1 + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id '
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId'
	set @query1 = @query1 + ' inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId'
	set @query1 = @query1 + ' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId'
	set @query1 = @query1 + ' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID '
		end
	set @query1 = @query1 + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @query1 = @query1 + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	set @query1 = @query1 + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId '
	set @query1 = @query1 + ' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId '
	set @query1 = @query1 + ' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1'
	set @query1 = @query1 + ' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
	set @query1 = @query1 + ' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @query1 = @query1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel 
			--+  ' AND (ta_tbl_employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or ta_tbl_employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''') '
		end
	if not(@EmployeeName='')
		begin
		--	set @query1 = @query1 + ' and ta_tbl_employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		Declare @Tempname nvarchar(200)
    set @Tempname= '(ta_tbl_employee.Employee_FirstName + '' '' + isnull(ta_tbl_employee.Employee_LastName,'''')'
	set @query1 = @query1 + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 	
		end
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @query1 = @query1 + 'And ta_tbl_employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End
	if not (@empId='')
		begin
			set @query1 = @query1 + ' and ta_tbl_employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
	if(@DesignationID<>0)  
		 begin  
			set @query1 = @query1 + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))  
		end  
	if(@Gender<>'Both')  
		begin  
			 set @query1 = @query1 + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		 end  
	--if(@EmpAutoId = 0)
	--	BEGIN
	--		if not(@LevelID='' or @LevelID='0')
	--			begin
	--				set @query1 = @query1 + ' and #EmpLevel.LevelId IN ( ' + @LevelId + ') ' 
	--			end	
	--	END
	if(@EmpAutoId > 0)
		BEGIN
			set @query1 = @query1 + ' and (ta_tbl_employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	set @query1 = @query1 + ' group by  ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname'
	create table #TempFinal ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] int,[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,Others decimal(18,1),CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,Intimation DECIMAL(18,2))
	DROP TABLE ##pivot
	--exec  (@query + ' ' + @query1)
	insert into #TempFinal 
	exec  (@query + ' ' + @query1)
	--select TF.*,C.CategoryName as [Employee Category]from #TempFinal TF
	--Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	--inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	--inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId order by TF.[Employee Id] 
	--select * from #TempFinal 
    create table #TempFinal2 ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] varchar(50),[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,[Employee Category] nvarchar(500),Others decimal(18,1),CategoryId int,Intimation DECIMAL(18,2))
	Insert into #TempFinal2 
	select [Employee Name] ,[Employee Id] ,Present ,Absent ,[Weekly Off] ,
	Holiday ,CompOff ,Lop ,[Total Late Days] ,
	case when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
				+ '0' +convert(varchar(20),[Total Late Hours]/60) + ':0' + CONVERT(varchar(20),[Total Late Hours]%60)  
	     when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=2 then 
	     + '0' +convert(varchar(20),[Total Late Hours]/60) + ':' + CONVERT(varchar(20),[Total Late Hours]%60)
	     when len(convert(varchar(20),[Total Late Hours]/60))=2 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
	     convert(varchar(20),[Total Late Hours]/60) + ':0' + CONVERT(varchar(20),[Total Late Hours]%60)
	else convert(varchar(20),[Total Late Hours]/60) + ':' +CONVERT(varchar(20),[Total Late Hours]%60)  
	end 
	,[Total Early Out Days] ,[Total Early Out Hours] ,
	[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off]
	,C.CategoryName as [Employee Category],Others,C.CategoryId ,Intimation from #TempFinal TF
	Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId
	Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId 
	order by [Employee Id]	
		declare @BelowCategoryId as int
	set @BelowCategoryId=(select top 1 CategoryId from TA_Tbl_Category  order by MonToSat_WorkHrs desc,Sat_WorkHrs desc)
	update #TempFinal2 set [Saturday Off]=0 where CategoryId=@BelowCategoryId 
	update #TempFinal2 set [Intimation]=0 where CategoryId=@BelowCategoryId 
	--update #TempFinal2 set Present=Present+[Saturday Off] where [Employee Id]
	--Update #TempFinal2 Set Present =1 Where upper(DATENAME(dw,Date)) = ''Saturday'' THEN 
	--                                                       CASE  when FNAttendanceCode = ''Absent'' and ANAttendanceCode =''Absent'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN  1
	--                                                         when FNAttendanceCode = ''Absent'' and FNAttendanceCode=''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') THEN 1
	--                                                         when FNAttendanceCode= ''Weekly Off'' and FNAttendanceCode =''Absent''  and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'')THEN 1
	--                                                         when FNAttendanceCode = ''Weekly Off'' and FNAttendanceCode =''Weekly Off'' and ANAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') and  FNAttendanceCode not in(''CL'',''Holiday'',''CompOff'',''LOP'',''SL'') then 1 
	select [Employee Id],[Employee Name],Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,[Saturday Off],
	Holiday ,CompOff ,Lop ,CL,SL,isnull([Total Late Hours],'00:00')[Total Late Hours]  ,[Total Late Days] from #TempFinal2
	drop table #tempFinal
	drop table #TempFinal2
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Drop procedure Proc_TA_RptDetailAttendanceDynamicNew 
-- Proc_TA_RptDetailAttendanceDynamicNew '2019/01/01','2020/08/29','','','0,1','SuperAdmin','0','',0,0,'Both',0,0,1
/*
exec Proc_TA_RptDetailAttendanceDynamicNew @DesignationID=N'0',@fromDat=N'2024/02/06 00:00:00',@Gender=N'Both',
@EmpAutoId=N'0',@ParentId=N'37',@EmployeeCategory=N'0',@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',
@LevelID=N'37',@empId=N'BB002',@ToDat=N'2024/02/06 00:00:00',@EmployeeName=N'',@EmployeeType=N'0'

exec Proc_TA_RptDetailAttendanceDynamicNew @fromDat='2024-08-01 00:00:00',@ToDat='2024-10-21 00:00:00',@empId=N'',
@EmployeeName=N'',@LevelID=N'0',@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@DesignationId=0,
@Gender=N'Both',@EmployeeCategory=0,@EmployeeType=0,@EmpAutoID=0

*/


CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]   
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId NVARCHAR(max),   
	@EmployeeName NVARCHAR(max),
	@LevelID NVARCHAR(max),  
	@UserGroupName NVARCHAR(250),  
	@GradeLevel NVARCHAR(20)  ,  
	@EmpSwipeCard NVARCHAR(20),  
	@ParentId int,  
	@DesignationID int,  
	@Gender NVARCHAR(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON

	
CREATE TABLE #EMPLEVELs
	(
		id int identity(1,1),
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_IDs VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #LEVELRIGHTSS(LEVELID INT)
	INSERT INTO #LEVELRIGHTSS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD]('Superadmin',0) AS LEVELID  
	INSERT INTO #EMPLEVELs SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTSS ON #LEVELRIGHTSS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		--and(@local_GENDER='BOTH' or EMP.GENDER = @local_GENDER)
		--and((@ISREPORTINGTO=0 or @local_USERGROUPNAME='Superadmin')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		--and(isnull(@local_EMPLOYEEID,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		--and(isnull(@local_EMPLOYEENAME,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTSS ON #LEVELRIGHTSS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,Getdate(), 102) AND EL.LEVELID IS NOT NULL	


declare @Count int=0, @loop int=1,@SQLStr nvarchar(MAX)=''
	create table #Emptest (
		EmployeeId nvarchar(20),
		LevelId int,
		Level1Name nvarchar(200),
		Level1Details nvarchar(200),
		Level2Name nvarchar(200),
		Level2Details nvarchar(200),
		Level3Name nvarchar(200),
		Level3Details nvarchar(200),
		Level4Name nvarchar(200),
		Level4Details nvarchar(200),
		Level5Name nvarchar(200),
		Level5Details nvarchar(200)
	)
	select @Count=count(*) from #EMPLEVELs
	while(@Count>=@loop)
		begin
			Set @SQLStr=''
			declare @EmpIDs nvarchar(20),@LoopLevelID bigint
			Select @EmpIDs=EMPLOYEE_CODE_IDs,@LoopLevelID=LEVELID from #EMPLEVELs where id=@loop
			select @SQLStr=dbo.Func_TA_LoadSpace(@EmpIDs,@LoopLevelID,'#Emptest')
			execute(@SQLStr)
			Set @loop=@loop+1
		end
	
	print @SQLStr

	--select * from #Emptest

	CREATE TABLE #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),
		[Employee Id] NVARCHAR(50),
		[Department]NVARCHAR(250),
		Present numeric(8,1),
		Absent numeric(8,1),
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		LOPCount float,
		[Total Late Days] numeric(8,1),
		[Total Late Hours] numeric(8,1),
		[Total Early Exit Days] numeric(18,1),
		[Total Early Exit Hours] numeric(8,1) default(0),
		[Total OT Days] numeric(8,1),
		[Total OT Hours] numeric(8,1),
		[Norm OT Hrs] numeric(8,1),
		[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),
		Others numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,		
		Total_HoursWorkInMins int,
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,		
		SwipeCardNo NVARCHAR(50),
		Gender NVARCHAR(20),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	DECLARE @isReportingto AS INT
	CREATE TABLE #EmployeeIds(EmpAutoId int)
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
	CREATE TABLE #EmpAttendanceDetails
	(
		EmployeeID  NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateHours numeric(8,1),
		TotalOTDays numeric(8,1),
		TotalOTHours numeric(8,1),
		NormalOTHrs numeric(8,1),
		WeekOffOTHrs numeric(8,1),
		HolidayOTHours numeric(8,1),
		EarlyOutInMins float,
		TotalEarlyOutDays numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		Total_HoursWorkInMins numeric(8,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,
		LOPCount float,
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #LevelRights(LevelId int)
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id NVARCHAR(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		Shift_Id int,
		TotalDays numeric(18,1),
		LateInMins float,
		OtMins float,
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		EarlyOutMins float,
		HoursWorkInMins decimal(18,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours float,
		PermissionDays int,
		LOPCount float,
		EmpSwipeCardNo NVARCHAR(20),
		EmployeeName nvarchar(200) ,
		Gender NVARCHAR(20),
		Department nvarchar(250),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	INSERT INTO #tempLeavetype SELECT Top 10 LeaveType  FROM ta_tbl_leavetype where LeaveType!='WFH'
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID NVARCHAR(25))
	create table #EmployeeName(EmployeeID NVARCHAR(25))
	if(@empId is not null and @empId <> '')
		begin			
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		left outer join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
		where emp.Isdeleted=0 
		and(1=1 or emp.Employee_Code_Id in(select * from #EmployeeID))
		and(isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in(select * from #EmployeeName))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= @ToDat and EL.LevelId is not null
		
	insert into #TempProcessedData 
	select	E.Employee_Id,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Attendance,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.Shift_Id,
			PD.TotalDays,
			PD.LateInMins,
			PD.OtMins,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			PD.EarlyOutMins,
			isnull(PD.HoursWorkInMins,0),
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) else isnull(PD.SPEC_NormOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins2,PD.SPEC_NormOTMins2) else isnull(PD.SPEC_NormOTMins2,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins1,PD.SPEC_OffOTMins1) else isnull(PD.SPEC_OffOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins2,PD.SPEC_OffOTMins2) else isnull(PD.SPEC_OffOTMins2,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins1,PD.SPEC_HOLOTMins1) else isnull(PD.SPEC_HOLOTMins1,0) end,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins2,PD.SPEC_HOLOTMins2)else isnull(PD.SPEC_HOLOTMins2,0) end,
			Pd.PermissionHrsInMins,
			case when Pd.PermissionHrsInMins > 0 then 1 else 0 end,
			case WHEN (PD.FNAttendanceCode='LOP' and PD.ANAttendanceCode='LOP') THEN 1 WHEN (PD.FNAttendanceCode='LOP' or PD.ANAttendanceCode='LOP') THEN 0.5  ELSE 0 END,
			E.SwipeCardNo,
			E.Employee_FirstName +' ' +E.Employee_MiddleName +' ' +E.Employee_LastName as Employee_FirstName,
			E.Gender,
			ld.name,
			Paymonth=MONTH(pd.Date),
			Payyear=year(pd.Date),
			DATENAME(MONTH,pd.Date)
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN TA_Tbl_Employee  e on E.SwipeCardNo=PD.Employee_Code_Id
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
	Inner join #EMPCATEGORY cat on cat.employeeid=e.Employee_Id 
	Inner join #EMPTYPE type on type.employeeid=e.Employee_Id 
	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	inner join ta_tbl_leveldetails ld on ld.id=#EmpLevel.LevelId	
	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
	where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 
	and (@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level >=@GradeLevel)
	and (isnull(@Gender,'Both')='Both' or  e.Gender =@Gender)
	and (isnull(@isReportingto,0)=0 or (e.Employee_ID IN (select * from #EmployeeIds)))
	and (PD.date >= CONVERT(DATETIME,@fromDat, 111)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 111)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
	INSERT INTO #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender,Department,PayMonth,PayYear,PayMonthName) 
	SELECT DISTINCT Employee_Code_Id,Employee_Code_Id,EmployeeName,Gender,Department,PayMonth,PayYear,PayMonthName FROM #TempProcessedData	
	
	INSERT INTO #EmpAttendanceDetails 
	SELECT TPD.Employee_code_Id,  
			Present= 
			sum
			(
				CASE	WHEN FNAttendanceCode='Present'	 AND ANAttendanceCode='Present'		THEN 1.0
						WHEN ((FNAttendanceCode='Present'  AND ANAttendanceCode!='Present')or(FNAttendanceCode!='Present' AND ANAttendanceCode='Present')) THEN 0.5
						WHEN FNAttendanceCode='Comp Off' AND ANAttendanceCode='Comp Off'	THEN 1.0
						WHEN FNAttendanceCode='BL' AND  ANAttendanceCode='BL'				THEN 1.0						
						ELSE 0.0
				END
			),
			Absent=
			sum
			(
				CASE	WHEN FNAttendanceCode='Absent'	 AND  ANAttendanceCode='Absent'	THEN 1.0 
						WHEN ((FNAttendanceCode='Absent' AND  ANAttendanceCode!='Absent') or (FNAttendanceCode!='Absent' AND  ANAttendanceCode='Absent')) THEN 0.5
						WHEN ((FNAttendanceCode IS NULL    AND  ANAttendanceCode IS NULL) or (FNAttendanceCode='' AND ANAttendanceCode=''))	THEN 1
						ELSE 0.0
				END
			), 
			[Total Late Days]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0 THEN  1 else 0 END),
			[Total Late Hours]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0	THEN  lateinmins END),
			[Total OT Days]		=SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN 1 else 0 END),  
			[Total Ot Hours]	=
			isnull(SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN  otmins END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT1,0)!=0 THEN  TPD.Total_Spec_NormOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT2,0)!=0 THEN  TPD.Total_Spec_NormOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT1,0)!=0 THEN  TPD.Total_Spec_OffOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT2,0)!=0 THEN  TPD.Total_Spec_OffOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT1,0)!=0 THEN  TPD.Total_Spec_HOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT2,0)!=0 THEN  TPD.Total_Spec_HOT2 END),0),  
			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,'00:00')='00:00'	THEN 0 ELSE OtMins END), 
			[Total EarlyOut Hours]=SUM(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),  
			[Total EarlyOut Days]=COUNT(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),
			0,
			0,
			0,
			'WeeklyOff'	=sum(CASE WHEN FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' THEN 1 ELSE 0 END),
			'Holiday'	=sum(CASE	WHEN FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' THEN 1 
								WHEN ((FNAttendanceCode='Holiday' and ANAttendanceCode!='Holiday') or (FNAttendanceCode!='Holiday' and ANAttendanceCode='Holiday'))THEN 0.5 
								ELSE 0 
							END), 
			'Leave'		=SUM(CASE WHEN FNAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END) + 
						 SUM(CASE WHEN ANAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END), 
			'LOP'		=SUM(CASE	WHEN FNAttendanceCode='LOP' and ANAttendanceCode='LOP' THEN 1 
									WHEN ((FNAttendanceCode='LOP' and ANAttendanceCode!='LOP') or (FNAttendanceCode!='LOP' and ANAttendanceCode='LOP')) THEN 0.5 
									ELSE 0 
							END), 
			'Total_HoursWorkInMins' =  sum(CASE WHEN isnull(HoursWorkInMins,0)!=0 THEN HoursWorkInMins else 0 END),
			isnull(SUM(TPD.Total_Spec_NormOT1),0),
			isnull(SUM(TPD.Total_Spec_NormOT2),0),
			isnull(SUM(TPD.Total_Spec_OffOT1),0),
			isnull(SUM(TPD.Total_Spec_OffOT2),0),
			isnull(SUM(TPD.Total_Spec_HOT1),0),
			isnull(SUM(TPD.Total_Spec_HOT2),0),
			isnull(SUM(TPD.PermissionHours),0),
			isnull(sum(TPD.PermissionDays),0),
			isnull(sum(TPD.LOPCount),0),
			TPD.PayMonth,
			TPD.PayYear,
			TPD.PayMonthName
			from #TempProcessedData  TPD
			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
			--Inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=TPD.Employee_Code_Id			
			group by TPD.Employee_Code_ID,TPD.PayMonth,TPD.PayYear,TPD.PayMonthName
	
	update #TempDetailedAttendance set Present = TEAD.Present,
	Absent = TEAD.Absent,  
	[Total Late Days]	= TEAD.TotalLateDays,
	[Total Late Hours]	= TEAD.TotalLateHours,  
	[Total OT Days]		= TEAD.TotalOTDays,
	[Total OT Hours]	= TEAD.TotalOTHours,  
	[Norm OT Hrs]		= TEAD.NormalOTHrs,
	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
	[Total Early Exit Hours]=TEAD.EarlyOutInMins,
	[Total Early Exit Days]= TEAD.TotalEarlyOutDays,
	EmployeeCategory	=TEAD.EmployeeCategory,
	EmpCategory			=TEAD.EmpCategory,
	EmployeeType		=TEAD.EmployeeType,
	Total_HoursWorkInMins=TEAD.Total_HoursWorkInMins,
	Total_Spec_NormOT1	=isnull(TEAD.Total_Spec_NormOT1,0),
	Total_Spec_NormOT2	=isnull(TEAD.Total_Spec_NormOT2,0),
	Total_Spec_OffOT1	=isnull(TEAD.Total_Spec_OffOT1,0),
	Total_Spec_OffOT2	=isnull(TEAD.Total_Spec_OffOT2,0),
	Total_Spec_HOT1		=isnull(TEAD.Total_Spec_HOT1,0),
	Total_Spec_HOT2		=isnull(TEAD.Total_Spec_HOT2,0),
	PermissionHours=TEAD.PermissionHours,
	PermissionDays=TEAD.PermissionDays,
	LOPCount = TEAD.LOPCount,
	WeeklyOff=TEAD.WeeklyOff,
	Holiday=TEAD.Holiday,
	PayMonthName=#TempDetailedAttendance.PayMonthName
	from #EmpAttendanceDetails TEAD 
	inner join #TempDetailedAttendance on (TEAD.EmployeeID=#TempDetailedAttendance.SwipeCardNo and TEAD.PayMonth=#TempDetailedAttendance.PayMonth and TEAD.PayYear=#TempDetailedAttendance.PayYear)
	
	
	---Sum of PermissionHours, PermissionDays,LOPCount ---
    update  a set PermissionHours = (b.PermissionHours),PermissionDays = (b.PermissionDays)
	from #TempDetailedAttendance a 
	inner join
	( 
		select EmployeeID,sum(PermissionHours) PermissionHours,sum(PermissionDays)PermissionDays,PayMonth,PayYear 
		from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	update  a set LOPCount = (b.LOPCount)
	from #TempDetailedAttendance a 
	inner join 
	(
		select EmployeeID,sum(LOPCount) LOPCount,PayMonth,PayYear from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	--Inserts the Others details in the temporary table  
	declare @SqlOthers NVARCHAR(4000)  
	create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
	Insert into #Others 
	select Employee_Code_Id ,	
	sum
	(
		CASE	WHEN (FNAttendanceCode='RH' or FNAttendanceCode='LOP' or FNAttendanceCode='ESI') THEN 0.5
				ELSE 0 
		END
	)+ 
	sum
	( 
		CASE WHEN (ANAttendanceCode='RH' or ANAttendanceCode='LOP' or ANAttendanceCode='ESI') THEN 0.5
			 ELSE 0 
		END
	)
	from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance)
	group by Employee_Code_ID
	
	Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
	INSERT INTO #tempLeaveTypeforOthers 
	SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
	LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
	WHERE TLT.Leavetype is null
	declare @LTOthersCount int  
	declare @totLeaveType int
	set @LTOthersCount=1  
	select @totLeaveType=count(*) from #tempLeaveTypeforOthers
	while(@LTOthersCount<=@totLeaveType)  
		BEGIN  
			declare @LeaveTypeForOthers NVARCHAR(10)  
			select @LeaveTypeForOthers =LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount
			declare @SqlUpdateOthers NVARCHAR(3000)
			set @SqlUpdateOthers=''
			set @SqlUpdateOthers = @SqlUpdateOthers + ' Update #Others set Others = Others + A.TotalDays from '   
			set @SqlUpdateOthers =@SqlUpdateOthers  + ' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END)'  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' + sum( CASE PD.ANAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else PD.TotalDays END else 0 END)) as TotalDays'
			set @SqlUpdateOthers = @SqlUpdateOthers + ' from #TempProcessedData PD '  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' group by PD.Employee_Code_Id) A'  
			set @SqlUpdateOthers = @SqlUpdateOthers + ' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id'  
			set @LTOthersCount=@LTOthersCount+1  
			exec(@SqlUpdateOthers)  
		END
	--Updates the Others column in the temporary table  
	update #TempDetailedAttendance set Others=#Others.Others from #Others 
	inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo
	
	--Adding the Leave type column in the #TempDetailedAttendance table.  
	declare @LeaveTypeCount int  
	set @LeaveTypeCount=1  
	declare @Column NVARCHAR(max)
	set @Column=''
	declare @Column_Sum NVARCHAR(max)
	set @Column_Sum=''
	while(@LeaveTypeCount<=10)  
		BEGIN  
			declare @LeaveType nvarchar(50)  
			set @LeaveType=''
			select @LeaveType=Leavetype from #tempLeavetype where slno=@LeaveTypeCount
			if @LeaveType is not null and @LeaveType!=''
			BEGIN
				DECLARE @AlterQuery NVARCHAR(100)  
				set @AlterQuery='Alter table #TempDetailedAttendance add [' + @LeaveType + '] numeric(18,1)'  
				if(@Column='')
				begin
					set @Column=quotename(@LeaveType)
					set @Column_Sum=quotename(@LeaveType)
				end
				else
				begin
					set @Column=@Column+','+quotename(@LeaveType)
					set @Column_Sum=@Column_Sum+'+'+quotename(@LeaveType)
				end
				exec(@AlterQuery)  
				set @AlterQuery=''
				declare @UpdateQuery NVARCHAR(4000)  
				set @UpdateQuery=''
				set @UpdateQuery = @UpdateQuery + 'update #TempDetailedAttendance  set ['+ @LeaveType +']'  
				set @UpdateQuery = @UpdateQuery + '=A.TotalDays from'  
				set @UpdateQuery = @UpdateQuery +' (select Employee_Code_ID,TDA.PayMonth,TDA.PayYear,(sum(CASE WHEN PD.FNAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END) '  
				set @UpdateQuery = @UpdateQuery + ' + sum(CASE WHEN PD.ANAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END)) as TotalDays '  
				set @UpdateQuery = @UpdateQuery + ' from #TempProcessedData PD'  
				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TDA on (TDA.SwipeCardNo=PD.Employee_code_ID and TDA.PayMonth=PD.PayMonth and TDA.PayYear=PD.PayYear)'
				set @UpdateQuery = @UpdateQuery + ' group by PD.Employee_Code_ID,TDA.PayMonth,TDA.PayYear) A'  
				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID AND TempAttendance.PayMonth=A.PayMonth AND TempAttendance.PayYear=A.PayYear'  
				exec(@UpdateQuery)  
				--PRINT(@UpdateQuery)  
				set @UpdateQuery=''
			end
			set @LeaveTypeCount=@LeaveTypeCount+1  
	END  
	
		
	--SELECT * FROM #TempDetailedAttendance 
	declare @SqlPresent NVARCHAR(max)
	set @SqlPresent=''
	set @SqlPresent=@SqlPresent+' select 	
		[Employee Id],
		[Employee Name],
		SwipeCardNo,				
		Gender,	
		Present,
		Absent,
		WeeklyOff,
		Holiday,				
		[Total Late Days],		
		[Total Early Exit Days],		
		[Total OT Days],		
		[Norm OT Hrs]=dbo.ConvertMinsToHours([Norm OT Hrs]),
		[WeekOff OT Hrs]=dbo.ConvertMinsToHours([WeekOff OT Hrs]),
		[Holiday OT Hrs]=dbo.ConvertMinsToHours([Holiday OT Hrs]),
		Others,
		Total_HoursWorkInMins=dbo.ConvertMinsToHours(Total_HoursWorkInMins),		
		[WD Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
		[WD Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_NormOT2),
		[WO Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_OffOT1),
		[WO Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_OffOT2),
		[H Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_HOT1),
		[H Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_HOT2),
		PermissionHours=dbo.ConvertMinsToHours(PermissionHours) 
		,PermissionDays 
		,LOPCount
		,[Total Late Hours]=dbo.ConvertMinsToHours([Total Late Hours]),
		[Total Early Exit Hours]=dbo.ConvertMinsToHours([Total Early Exit Hours]),
		[Total OT Hours]=dbo.ConvertMinsToHours([Total OT Hours]),
		 Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,
		Level4Name,Level4Details,Level5Name,Level5Details,
		PayDays=Present+WeeklyOff+Holiday+'+(@Column_Sum)+'
		,TotalDays=DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)),0))),
		[Month]=PaymonthName,
		'+(@Column)+'
		
		--,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)
		from #TempDetailedAttendance 
 		inner Join #Emptest ELL on ELL.EmployeeId =#TempDetailedAttendance.[Employee Id]
		 where 1=1 order by PayMonth,paymonthName,[Employee Id] '	
	--print (@SqlPresent) 
	exec (@SqlPresent)
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpAttendanceDetails  
	drop table #Others  
	drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #Emptest
END



--ALTER PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]   
--(  
--	@fromDat datetime,  
--	@ToDat datetime,  
--	@empId NVARCHAR(max),   
--	@EmployeeName NVARCHAR(max),
--	@LevelID NVARCHAR(max),  
--	@UserGroupName NVARCHAR(250),  
--	@GradeLevel NVARCHAR(20)  ,  
--	@EmpSwipeCard NVARCHAR(20),  
--	@ParentId int,  
--	@DesignationID int,  
--	@Gender NVARCHAR(10),
--	@EmployeeCategory int,
--	@EmployeeType int,
--	@EmpAutoID int
--)  
--AS  
--BEGIN  
--	SET NOCOUNT ON

	


--	print @fromDat
--	CREATE TABLE #TempDetailedAttendance  
--	(     
--		[Employee Name] nvarchar(200),
--		[Employee Id] NVARCHAR(50),
--		[Department]NVARCHAR(250),
--		Present numeric(8,1),
--		Absent numeric(8,1),
--		WeeklyOff numeric(8,1),
--		Holiday numeric(8,1),
--		Leave Numeric(8,1),
--		LOP numeric(8,1),
--		LOPCount float,
--		[Total Late Days] numeric(8,1),
--		[Total Late Hours] numeric(8,1),
--		[Total Early Exit Days] numeric(18,1),
--		[Total Early Exit Hours] numeric(8,1) default(0),
--		[Total OT Days] numeric(8,1),
--		[Total OT Hours] numeric(8,1),
--		[Norm OT Hrs] numeric(8,1),
--		[WeekOff OT Hrs] numeric(8,1),  
--		[Holiday OT Hrs] numeric(8,1),
--		Others numeric(8,1),
--		EmployeeCategory int,
--		EmpCategory nvarchar(200),
--		EmployeeType int,		
--		Total_HoursWorkInMins int,
--		Total_Spec_NormOT1 int,
--		Total_Spec_NormOT2 int,
--		Total_Spec_OffOT1 int,
--		Total_Spec_OffOT2 int,
--		Total_Spec_HOT1 int,
--		Total_Spec_HOT2 int,
--		PermissionHours int,
--		PermissionDays int,		
--		SwipeCardNo NVARCHAR(50),
--		Gender NVARCHAR(20),
--		PayMonth int,
--		PayYear int,
--		PayMonthName varchar(15)
--	)
--	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
--	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
--	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
--	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
--	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
--	DECLARE @isReportingto AS INT
--	CREATE TABLE #EmployeeIds(EmpAutoId int)
--    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
--    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
--	CREATE TABLE #EmpAttendanceDetails
--	(
--		EmployeeID  NVARCHAR(50),
--		Present numeric(8,1),
--		Absent numeric(8,1),
--		TotalLateDays numeric(8,1),
--		TotalLateHours numeric(8,1),
--		TotalOTDays numeric(8,1),
--		TotalOTHours numeric(8,1),
--		NormalOTHrs numeric(8,1),
--		WeekOffOTHrs numeric(8,1),
--		HolidayOTHours numeric(8,1),
--		EarlyOutInMins float,
--		TotalEarlyOutDays numeric(8,1),
--		EmployeeCategory int,
--		EmpCategory nvarchar(200),
--		EmployeeType int,
--		WeeklyOff numeric(8,1),
--		Holiday numeric(8,1),
--		Leave Numeric(8,1),
--		LOP numeric(8,1),
--		Total_HoursWorkInMins numeric(8,1),
--		Total_Spec_NormOT1 int,
--		Total_Spec_NormOT2 int,
--		Total_Spec_OffOT1 int,
--		Total_Spec_OffOT2 int,
--		Total_Spec_HOT1 int,
--		Total_Spec_HOT2 int,
--		PermissionHours int,
--		PermissionDays int,
--		LOPCount float,
--		PayMonth int,
--		PayYear int,
--		PayMonthName varchar(15)
--	)
--	CREATE TABLE #LevelRights(LevelId int)
--	CREATE TABLE #TempProcessedData
--	(
--		EmpAutoId bigint,
--		Date datetime,
--		Employee_Code_Id NVARCHAR(20),
--		InTime nvarchar(25),
--		OutTime nvarchar(25),
--		Attendance nvarchar(20),
--		fnattendanceCode nvarchar(20),
--		anattendanceCode nvarchar(20),
--		Shift_Id int,
--		TotalDays numeric(18,1),
--		LateInMins float,
--		OtMins float,
--		NormOT nvarchar(10),
--		OffOT nvarchar(10),
--		HolOT nvarchar(10),
--		EarlyOutMins float,
--		HoursWorkInMins decimal(18,1),
--		Total_Spec_NormOT1 int,
--		Total_Spec_NormOT2 int,
--		Total_Spec_OffOT1 int,
--		Total_Spec_OffOT2 int,
--		Total_Spec_HOT1 int,
--		Total_Spec_HOT2 int,
--		PermissionHours float,
--		PermissionDays int,
--		LOPCount float,
--		EmpSwipeCardNo NVARCHAR(20),
--		EmployeeName nvarchar(200) ,
--		Gender NVARCHAR(20),
--		Department nvarchar(250),
--		PayMonth int,
--		PayYear int,
--		PayMonthName varchar(15)
--	)
--	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--	INSERT INTO #tempLeavetype SELECT Top 10 LeaveType  FROM ta_tbl_leavetype where LeaveType!='WFH'
--	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
--	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
--	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
--	--To split up the comma separated values
--	create table #EmployeeID(EmployeeID NVARCHAR(25))
--	create table #EmployeeName(EmployeeID NVARCHAR(25))
--	if(@empId is not null and @empId <> '')
--		begin			
--			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
--		end
--	if(@EmployeeName is not null and @EmployeeName <> '')
--		begin			
--			insert into #EmployeeName
--			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
--		end
	
--	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
--	(
--		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
--		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
--		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
--		left outer join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
--		left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
--		where emp.Isdeleted=0 
--		and(1=1 or emp.Employee_Code_Id in(select * from #EmployeeID))
--		and(isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in(select * from #EmployeeName))
--		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
--	) ELevel
--	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
--	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
--	AND EL.EffectiveDate <= @ToDat and EL.LevelId is not null
		
--	insert into #TempProcessedData 
--	select	E.Employee_Id,
--			PD.Date,
--			PD.Employee_Code_Id,
--			PD.InTime,
--			PD.OutTime,
--			PD.Attendance,
--			PD.fnattendanceCode,
--			PD.anattendanceCode,
--			PD.Shift_Id,
--			PD.TotalDays,
--			PD.LateInMins,
--			PD.OtMins,
--			PD.NormOT,
--			PD.OffOT,
--			PD.HolOT,
--			PD.EarlyOutMins,
--			isnull(PD.HoursWorkInMins,0),
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) else isnull(PD.SPEC_NormOTMins1,0) end,
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins2,PD.SPEC_NormOTMins2) else isnull(PD.SPEC_NormOTMins2,0) end,
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins1,PD.SPEC_OffOTMins1) else isnull(PD.SPEC_OffOTMins1,0) end,
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_OffOTMins2,PD.SPEC_OffOTMins2) else isnull(PD.SPEC_OffOTMins2,0) end,
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins1,PD.SPEC_HOLOTMins1) else isnull(PD.SPEC_HOLOTMins1,0) end,
--			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_HolOTMins2,PD.SPEC_HOLOTMins2)else isnull(PD.SPEC_HOLOTMins2,0) end,
--			Pd.PermissionHrsInMins,
--			case when Pd.PermissionHrsInMins > 0 then 1 else 0 end,
--			case WHEN (PD.FNAttendanceCode='LOP' and PD.ANAttendanceCode='LOP') THEN 1 WHEN (PD.FNAttendanceCode='LOP' or PD.ANAttendanceCode='LOP') THEN 0.5  ELSE 0 END,
--			E.SwipeCardNo,
--			E.Employee_FirstName,
--			E.Gender,
--			ld.name,
--			Paymonth=MONTH(pd.Date),
--			Payyear=year(pd.Date),
--			DATENAME(MONTH,pd.Date)
--	FROM TA_Tbl_ProcessedData PD
--	INNER JOIN TA_Tbl_Employee  e on E.SwipeCardNo=PD.Employee_Code_Id
--	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
--	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
--	Inner join #EMPCATEGORY cat on cat.employeeid=e.Employee_Id 
--	Inner join #EMPTYPE type on type.employeeid=e.Employee_Id 
--	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
--	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
--	inner join ta_tbl_leveldetails ld on ld.id=#EmpLevel.LevelId	
--	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
--	where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 
--	and (@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level >=@GradeLevel)
--	and (isnull(@Gender,'Both')='Both' or  e.Gender =@Gender)
--	and (isnull(@isReportingto,0)=0 or (e.Employee_ID IN (select * from #EmployeeIds)))
--	and (PD.date >= CONVERT(DATETIME,@fromDat, 111)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 111)) and    
--	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
--	INSERT INTO #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender,Department,PayMonth,PayYear,PayMonthName) 
--	SELECT DISTINCT Employee_Code_Id,Employee_Code_Id,EmployeeName,Gender,Department,PayMonth,PayYear,PayMonthName FROM #TempProcessedData	
	
--	INSERT INTO #EmpAttendanceDetails 
--	SELECT TPD.Employee_code_Id,  
--			Present= 
--			sum
--			(
--				CASE	WHEN FNAttendanceCode='Present'	 AND ANAttendanceCode='Present'		THEN 1.0
--						WHEN ((FNAttendanceCode='Present'  AND ANAttendanceCode!='Present')or(FNAttendanceCode!='Present' AND ANAttendanceCode='Present')) THEN 0.5
--						WHEN FNAttendanceCode='Comp Off' AND ANAttendanceCode='Comp Off'	THEN 1.0
--						WHEN FNAttendanceCode='BL' AND  ANAttendanceCode='BL'				THEN 1.0						
--						ELSE 0.0
--				END
--			),
--			Absent=
--			sum
--			(
--				CASE	WHEN FNAttendanceCode='Absent'	 AND  ANAttendanceCode='Absent'	THEN 1.0 
--						WHEN ((FNAttendanceCode='Absent' AND  ANAttendanceCode!='Absent') or (FNAttendanceCode!='Absent' AND  ANAttendanceCode='Absent')) THEN 0.5
--						WHEN ((FNAttendanceCode IS NULL    AND  ANAttendanceCode IS NULL) or (FNAttendanceCode='' AND ANAttendanceCode=''))	THEN 1
--						ELSE 0.0
--				END
--			), 
--			[Total Late Days]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0 THEN  1 else 0 END),
--			[Total Late Hours]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0	THEN  lateinmins END),
--			[Total OT Days]		=SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN 1 else 0 END),  
--			[Total Ot Hours]	=
--			isnull(SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN  otmins END),0)+
--			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT1,0)!=0 THEN  TPD.Total_Spec_NormOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT2,0)!=0 THEN  TPD.Total_Spec_NormOT2 END),0)+
--			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT1,0)!=0 THEN  TPD.Total_Spec_OffOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT2,0)!=0 THEN  TPD.Total_Spec_OffOT2 END),0)+
--			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT1,0)!=0 THEN  TPD.Total_Spec_HOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT2,0)!=0 THEN  TPD.Total_Spec_HOT2 END),0),  
--			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,'00:00')='00:00'	THEN 0 ELSE OtMins END),
--			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,'00:00')='00:00'	THEN 0 ELSE OtMins END),
--			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,'00:00')='00:00'	THEN 0 ELSE OtMins END), 
--			[Total EarlyOut Hours]=SUM(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),  
--			[Total EarlyOut Days]=COUNT(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),
--			0,
--			0,
--			0,
--			'WeeklyOff'	=sum(CASE WHEN FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' THEN 1 ELSE 0 END),
--			'Holiday'	=sum(CASE	WHEN FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' THEN 1 
--								WHEN ((FNAttendanceCode='Holiday' and ANAttendanceCode!='Holiday') or (FNAttendanceCode!='Holiday' and ANAttendanceCode='Holiday'))THEN 0.5 
--								ELSE 0 
--							END), 
--			'Leave'		=SUM(CASE WHEN FNAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END) + 
--						 SUM(CASE WHEN ANAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END), 
--			'LOP'		=SUM(CASE	WHEN FNAttendanceCode='LOP' and ANAttendanceCode='LOP' THEN 1 
--									WHEN ((FNAttendanceCode='LOP' and ANAttendanceCode!='LOP') or (FNAttendanceCode!='LOP' and ANAttendanceCode='LOP')) THEN 0.5 
--									ELSE 0 
--							END), 
--			'Total_HoursWorkInMins' =  sum(CASE WHEN isnull(HoursWorkInMins,0)!=0 THEN HoursWorkInMins else 0 END),
--			isnull(SUM(TPD.Total_Spec_NormOT1),0),
--			isnull(SUM(TPD.Total_Spec_NormOT2),0),
--			isnull(SUM(TPD.Total_Spec_OffOT1),0),
--			isnull(SUM(TPD.Total_Spec_OffOT2),0),
--			isnull(SUM(TPD.Total_Spec_HOT1),0),
--			isnull(SUM(TPD.Total_Spec_HOT2),0),
--			isnull(SUM(TPD.PermissionHours),0),
--			isnull(sum(TPD.PermissionDays),0),
--			isnull(sum(TPD.LOPCount),0),
--			TPD.PayMonth,
--			TPD.PayYear,
--			TPD.PayMonthName
--			from #TempProcessedData  TPD
--			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
--			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
--			--Inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=TPD.Employee_Code_Id			
--			group by TPD.Employee_Code_ID,TPD.PayMonth,TPD.PayYear,TPD.PayMonthName
	
--	update #TempDetailedAttendance set Present = TEAD.Present,
--	Absent = TEAD.Absent,  
--	[Total Late Days]	= TEAD.TotalLateDays,
--	[Total Late Hours]	= TEAD.TotalLateHours,  
--	[Total OT Days]		= TEAD.TotalOTDays,
--	[Total OT Hours]	= TEAD.TotalOTHours,  
--	[Norm OT Hrs]		= TEAD.NormalOTHrs,
--	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
--	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
--	[Total Early Exit Hours]=TEAD.EarlyOutInMins,
--	[Total Early Exit Days]= TEAD.TotalEarlyOutDays,
--	EmployeeCategory	=TEAD.EmployeeCategory,
--	EmpCategory			=TEAD.EmpCategory,
--	EmployeeType		=TEAD.EmployeeType,
--	Total_HoursWorkInMins=TEAD.Total_HoursWorkInMins,
--	Total_Spec_NormOT1	=isnull(TEAD.Total_Spec_NormOT1,0),
--	Total_Spec_NormOT2	=isnull(TEAD.Total_Spec_NormOT2,0),
--	Total_Spec_OffOT1	=isnull(TEAD.Total_Spec_OffOT1,0),
--	Total_Spec_OffOT2	=isnull(TEAD.Total_Spec_OffOT2,0),
--	Total_Spec_HOT1		=isnull(TEAD.Total_Spec_HOT1,0),
--	Total_Spec_HOT2		=isnull(TEAD.Total_Spec_HOT2,0),
--	PermissionHours=TEAD.PermissionHours,
--	PermissionDays=TEAD.PermissionDays,
--	LOPCount = TEAD.LOPCount,
--	WeeklyOff=TEAD.WeeklyOff,
--	Holiday=TEAD.Holiday,
--	PayMonthName=#TempDetailedAttendance.PayMonthName
--	from #EmpAttendanceDetails TEAD 
--	inner join #TempDetailedAttendance on (TEAD.EmployeeID=#TempDetailedAttendance.SwipeCardNo and TEAD.PayMonth=#TempDetailedAttendance.PayMonth and TEAD.PayYear=#TempDetailedAttendance.PayYear)
	
	
--	---Sum of PermissionHours, PermissionDays,LOPCount ---
--    update  a set PermissionHours = (b.PermissionHours),PermissionDays = (b.PermissionDays)
--	from #TempDetailedAttendance a 
--	inner join
--	( 
--		select EmployeeID,sum(PermissionHours) PermissionHours,sum(PermissionDays)PermissionDays,PayMonth,PayYear 
--		from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
--	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
--	update  a set LOPCount = (b.LOPCount)
--	from #TempDetailedAttendance a 
--	inner join 
--	(
--		select EmployeeID,sum(LOPCount) LOPCount,PayMonth,PayYear from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
--	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
--	--Inserts the Others details in the temporary table  
--	declare @SqlOthers NVARCHAR(4000)  
--	create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
--	Insert into #Others 
--	select Employee_Code_Id ,	
--	sum
--	(
--		CASE	WHEN (FNAttendanceCode='RH' or FNAttendanceCode='LOP' or FNAttendanceCode='ESI') THEN 0.5
--				ELSE 0 
--		END
--	)+ 
--	sum
--	( 
--		CASE WHEN (ANAttendanceCode='RH' or ANAttendanceCode='LOP' or ANAttendanceCode='ESI') THEN 0.5
--			 ELSE 0 
--		END
--	)
--	from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance)
--	group by Employee_Code_ID
	
--	Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
--	INSERT INTO #tempLeaveTypeforOthers 
--	SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
--	LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
--	WHERE TLT.Leavetype is null
--	declare @LTOthersCount int  
--	declare @totLeaveType int
--	set @LTOthersCount=1  
--	select @totLeaveType=count(*) from #tempLeaveTypeforOthers
--	while(@LTOthersCount<=@totLeaveType)  
--		BEGIN  
--			declare @LeaveTypeForOthers NVARCHAR(10)  
--			select @LeaveTypeForOthers =LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount
--			declare @SqlUpdateOthers NVARCHAR(3000)
--			set @SqlUpdateOthers=''
--			set @SqlUpdateOthers = @SqlUpdateOthers + ' Update #Others set Others = Others + A.TotalDays from '   
--			set @SqlUpdateOthers =@SqlUpdateOthers  + ' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays When ''1.0'' Then ''0.5'' when null then 0 Else PD.TotalDays END else 0 END)'  
--			set @SqlUpdateOthers = @SqlUpdateOthers + ' + sum( CASE PD.ANAttendanceCode WHEN '''+ @LeaveTypeForOthers + ''' THEN CASE PD.TotalDays when null then 0 When ''1.0'' Then ''0.5'' When ''0.5'' Then ''0.5'' Else PD.TotalDays END else 0 END)) as TotalDays'
--			set @SqlUpdateOthers = @SqlUpdateOthers + ' from #TempProcessedData PD '  
--			set @SqlUpdateOthers = @SqlUpdateOthers + ' group by PD.Employee_Code_Id) A'  
--			set @SqlUpdateOthers = @SqlUpdateOthers + ' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id'  
--			set @LTOthersCount=@LTOthersCount+1  
--			exec(@SqlUpdateOthers)  
--		END
--	--Updates the Others column in the temporary table  
--	update #TempDetailedAttendance set Others=#Others.Others from #Others 
--	inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo
	
--	--Adding the Leave type column in the #TempDetailedAttendance table.  
--	declare @LeaveTypeCount int  
--	set @LeaveTypeCount=1  
--	declare @Column NVARCHAR(max)
--	set @Column=''
--	declare @Column_Sum NVARCHAR(max)
--	set @Column_Sum=''
--	while(@LeaveTypeCount<=10)  
--		BEGIN  
--			declare @LeaveType nvarchar(50)  
--			set @LeaveType=''
--			select @LeaveType=Leavetype from #tempLeavetype where slno=@LeaveTypeCount
--			if @LeaveType is not null and @LeaveType!=''
--			BEGIN
--				DECLARE @AlterQuery NVARCHAR(100)  
--				set @AlterQuery='Alter table #TempDetailedAttendance add [' + @LeaveType + '] numeric(18,1)'  
--				if(@Column='')
--				begin
--					set @Column=quotename(@LeaveType)
--					set @Column_Sum=quotename(@LeaveType)
--				end
--				else
--				begin
--					set @Column=@Column+','+quotename(@LeaveType)
--					set @Column_Sum=@Column_Sum+'+'+quotename(@LeaveType)
--				end
--				exec(@AlterQuery)  
--				set @AlterQuery=''
--				declare @UpdateQuery NVARCHAR(4000)  
--				set @UpdateQuery=''
--				set @UpdateQuery = @UpdateQuery + 'update #TempDetailedAttendance  set ['+ @LeaveType +']'  
--				set @UpdateQuery = @UpdateQuery + '=A.TotalDays from'  
--				set @UpdateQuery = @UpdateQuery +' (select Employee_Code_ID,TDA.PayMonth,TDA.PayYear,(sum(CASE WHEN PD.FNAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END) '  
--				set @UpdateQuery = @UpdateQuery + ' + sum(CASE WHEN PD.ANAttendanceCode=''' + @LeaveType + ''' THEN 0.5 else 0 END)) as TotalDays '  
--				set @UpdateQuery = @UpdateQuery + ' from #TempProcessedData PD'  
--				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TDA on (TDA.SwipeCardNo=PD.Employee_code_ID and TDA.PayMonth=PD.PayMonth and TDA.PayYear=PD.PayYear)'
--				set @UpdateQuery = @UpdateQuery + ' group by PD.Employee_Code_ID,TDA.PayMonth,TDA.PayYear) A'  
--				set @UpdateQuery = @UpdateQuery + ' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID AND TempAttendance.PayMonth=A.PayMonth AND TempAttendance.PayYear=A.PayYear'  
--				exec(@UpdateQuery)  
--				--PRINT(@UpdateQuery)  
--				set @UpdateQuery=''
--			end
--			set @LeaveTypeCount=@LeaveTypeCount+1  
--	END  
	
		
--	--SELECT * FROM #TempDetailedAttendance 
--	declare @SqlPresent NVARCHAR(max)
--	set @SqlPresent=''
--	set @SqlPresent=@SqlPresent+' select 	
--		[Employee Id],
--		[Employee Name],
--		SwipeCardNo,				
--		Gender,	
--		Present,
--		Absent,
--		WeeklyOff,
--		Holiday,				
--		[Total Late Days],		
--		[Total Early Exit Days],		
--		[Total OT Days],		
--		[Norm OT Hrs]=dbo.ConvertMinsToHours([Norm OT Hrs]),
--		[WeekOff OT Hrs]=dbo.ConvertMinsToHours([WeekOff OT Hrs]),
--		[Holiday OT Hrs]=dbo.ConvertMinsToHours([Holiday OT Hrs]),
--		Others,
--		Total_HoursWorkInMins=dbo.ConvertMinsToHours(Total_HoursWorkInMins),		
--		[WD Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
--		[WD Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_NormOT2),
--		[WO Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_OffOT1),
--		[WO Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_OffOT2),
--		[H Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_HOT1),
--		[H Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_HOT2),
--		PermissionHours=dbo.ConvertMinsToHours(PermissionHours) 
--		,PermissionDays 
--		,LOPCount
--		,[Total Late Hours]=dbo.ConvertMinsToHours([Total Late Hours]),
--		[Total Early Exit Hours]=dbo.ConvertMinsToHours([Total Early Exit Hours]),
--		[Total OT Hours]=dbo.ConvertMinsToHours([Total OT Hours]),
--		PayDays=Present+WeeklyOff+Holiday+'+(@Column_Sum)+'
--		,TotalDays=DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)),0))),
--		[Month]=PaymonthName,
--		'+(@Column)+'
		
--		--,convert(varchar(20),payyear)+right(''00''+convert(varchar(20),PayMonth),2)+right(''00''+convert(varchar(20),1),2)
--	 from #TempDetailedAttendance where 1=1 order by PayMonth,paymonthName,[Employee Id] '	
--	--print (@SqlPresent) 
--	exec (@SqlPresent)
--	drop table #tempLeavetype  
--	drop table #EmpLevel  
--	drop table #EmpDesignation  
--	drop table #EmpAttendanceDetails  
--	drop table #Others  
--	drop table #tempLeaveTypeforOthers  
--	drop table #TempDetailedAttendance  
--	drop table #LevelRights  
--	drop table #TempProcessedData  
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailedAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthilkumar
-- ALTER  date: 17Aug2007
-- Description:	Employee Attendance Summary
-- Proc_TA_RptDetailedAttendance '01/01/2008','08/30/2008','','','','Admin',3
-- =============================================
CREATE       PROCEDURE [dbo].[Proc_TA_RptDetailedAttendance]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(1000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 
)
AS
BEGIN
	declare @sqlQuery as varchar(8000)
	declare @sqlQuery1 as varchar(8000)
	set @sqlQuery=''
	set @sqlQuery1=''	
					 set @sqlQuery = @sqlQuery + 'SELECT b.Employee_Code_Id, isnull(b.Employee_FirstName,'''') + SPACE(1) + isnull(b.Employee_LastName,'''') AS empName, SUM(a.Present) AS Present, '
					 set @sqlQuery = @sqlQuery + ' SUM(a.cl) AS CL,  SUM(a.el) AS EL, SUM(a.sl) AS SL, SUM(a.others) AS Others,'
                     set @sqlQuery = @sqlQuery + ' SUM(a.Absent) AS Absent, SUM(a.lateDays) AS ''TotlateDays'', SUM(a.otDays) AS TotOtDays, SUM(a.Leaves) AS Leaves, TA_Tbl_EmployeeDesignation.DesignationId, '
					 --set @sqlQuery = @sqlQuery + ' CAST(floor(cast(sum(a.totLate)as int) / 60) AS varchar(15)) + '':'' + cast((cast(sum(a.totLate)as int) % 60) as varchar(10))  as TotalLateHrs ,'	
					set @sqlQuery = @sqlQuery + ' sum(a.totLate) as TotalLateHrs ,'
					 --set @sqlQuery = @sqlQuery + ' CAST(floor(cast(sum(a.ot)as int) / 60) AS varchar(15)) + '':'' + cast((cast(sum(a.ot)as int) % 60) as varchar(10))  as OtHrs ,'	
					set @sqlQuery = @sqlQuery + ' sum(a.ot) as OtHrs ,'	
                     set @sqlQuery = @sqlQuery + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name'
--Number of days present					 
					 set @sqlQuery = @sqlQuery + ' FROM         (SELECT  '''' AS ot,'''' AS totLate,    Employee_Code_Id, SUM(TotalDays) AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery = @sqlQuery + ' FROM          ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE     (Attendance IN (''Present'', ''Weekly Off'', ''Holiday'', ''Comp Off'') OR LeaveCode=''Comp Off'')'
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery = @sqlQuery + ' UNION'
--number of days absent
                     set @sqlQuery = @sqlQuery + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', SUM(TotalDays) AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery = @sqlQuery + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE    (Attendance = ''Absent'' OR Attendance = ''LA'' OR Attendance = ''AL'') '
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery = @sqlQuery + ' UNION'
--Late coming days count					 
                     set @sqlQuery = @sqlQuery + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', COUNT(LateInMins) AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery = @sqlQuery + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE     LateInMins <>0'
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery = @sqlQuery + ' UNION'						
--late exit days count
                     set @sqlQuery = @sqlQuery + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', COUNT(ExtraMins) AS ''otDays'', '''' AS ''Leaves'''
                     set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
					 set @sqlQuery = @sqlQuery + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE     ExtraMins<>0 And ExtraMins IS NOT NULL And ExtraMins<>'''' '
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'						
					 set @sqlQuery = @sqlQuery + ' UNION'
-- sum lateIn  mins                     
                     set @sqlQuery = @sqlQuery + ' SELECT  '''' AS ot, sum(LateInMins) AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery = @sqlQuery + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE     lateInMins<>0'
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'
					 set @sqlQuery = @sqlQuery + ' UNION'
--sum late exit mins                     
                     set @sqlQuery = @sqlQuery + ' SELECT  sum(ExtraMins) AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery = @sqlQuery + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery = @sqlQuery + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery = @sqlQuery + ' WHERE     ExtraMins<>0 And ExtraMins IS NOT NULL And ExtraMins<>'''' '
					 set @sqlQuery = @sqlQuery + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery = @sqlQuery + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery = @sqlQuery + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery = @sqlQuery + ' UNION'			
--Count CL
					set @sqlQuery1 = @sqlQuery1 + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery1 = @sqlQuery1 + ' , SUM(TotalDays) AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery1 = @sqlQuery1 + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery1 = @sqlQuery1 + ' WHERE     LeaveCode=''CL'' '
					 set @sqlQuery1 = @sqlQuery1 + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery1 = @sqlQuery1 + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery1 = @sqlQuery1 + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery1 = @sqlQuery1 + ' UNION'
--count EL                     
                     set @sqlQuery1 = @sqlQuery1 + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery1 = @sqlQuery1 + ' , 0.0 AS ''cl'' ,SUM(TotalDays) AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery1 = @sqlQuery1 + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery1 = @sqlQuery1 + ' WHERE     LeaveCode=''EL'' '
					 set @sqlQuery1 = @sqlQuery1 + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery1 = @sqlQuery1 + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery1 = @sqlQuery1 + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery1 = @sqlQuery1 + ' UNION'
--count SL                     
                     set @sqlQuery1 = @sqlQuery1 + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery1 = @sqlQuery1 + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',SUM(TotalDays) AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery1 = @sqlQuery1 + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery1 = @sqlQuery1 + ' WHERE     LeaveCode=''SL'' '
					 set @sqlQuery1 = @sqlQuery1 + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery1 = @sqlQuery1 + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery1 = @sqlQuery1 + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery1 = @sqlQuery1 + ' UNION'
--count Others
                     set @sqlQuery1 = @sqlQuery1 + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', '''' AS ''Leaves'''
					 set @sqlQuery1 = @sqlQuery1 + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',SUM(TotalDays) AS ''others'' '
                     set @sqlQuery1 = @sqlQuery1 + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery1 = @sqlQuery1 + ' WHERE     attendance not in (''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')  AND LeaveCode not in (''Comp Off'', ''CL'' ,''EL'' ,''SL'' ) '
					 set @sqlQuery1 = @sqlQuery1 + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery1 = @sqlQuery1 + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
					 set @sqlQuery1 = @sqlQuery1 + ' GROUP BY Employee_Code_Id'
                     set @sqlQuery1 = @sqlQuery1 + ' UNION'
--number of leave days
                     set @sqlQuery1 = @sqlQuery1 + ' SELECT  '''' AS ot, '''' AS totLate,   Employee_Code_Id, 0.0 AS ''Present'', 0.0 AS ''Absent'', '''' AS ''lateDays'', '''' AS ''otDays'', COUNT(Attendance) AS ''Leaves'''
					 set @sqlQuery1 = @sqlQuery1 + ' , 0.0 AS ''cl'' ,0.0 AS ''el'',0.0 AS ''sl'',0.0 AS ''others'' '
                     set @sqlQuery1 = @sqlQuery1 + ' FROM         ta_tbl_processeddata'
                     set @sqlQuery1 = @sqlQuery1 + ' WHERE     Attendance NOT IN (''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') '
					 set @sqlQuery1 = @sqlQuery1 + ' And     (date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '
					 set @sqlQuery1 = @sqlQuery1 + ' AND (date <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
                     set @sqlQuery1 = @sqlQuery1 + ' GROUP BY Employee_Code_Id) a INNER JOIN'
                    set @sqlQuery1 = @sqlQuery1 + ' dbo.TA_Tbl_Employee b ON a.Employee_Code_Id = b.SwipeCardNo INNER JOIN'
					set @sqlQuery1 = @sqlQuery1 + ' TA_Tbl_EmployeeLevel on b.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN'
					set @sqlQuery1 = @sqlQuery1 + ' Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id INNER JOIN'
					set @sqlQuery1 = @sqlQuery1 + ' dbo.TA_Tbl_EmployeeDesignation ON b.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId INNER JOIN'
					set @sqlQuery1 = @sqlQuery1 + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId INNER JOIN'
					set @sqlQuery1 = @sqlQuery1 + ' TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
					set @sqlQuery1 = @sqlQuery1 + ' WHERE b.Isdeleted=0 and b.report_exclude=0 and b.employee_status=1'
					set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = b.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
					set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = b.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
					if(@UserGroupName<>'SuperAdmin')
					begin
						set @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
					end
					if not(@EmployeeName='' or @EmployeeName='0')
					begin
						set @sqlQuery1 = @sqlQuery1 + ' and (b.Employee_FirstName + '''' + isnull(b.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
					end
					if not (@empId='' or @empId='0')
					begin
						set @sqlQuery1 = @sqlQuery1 + ' and b.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
					end
					if not(@LevelID='' or @LevelID='0')
					begin
						set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeLevel.LevelId IN ( ' + @LevelId + ') ' 
					end	
					set   @sqlQuery1 = @sqlQuery1 + ' GROUP BY b.Employee_Code_Id, b.Employee_FirstName, b.Employee_LastName, TA_Tbl_EmployeeDesignation.DesignationId, dbo.TA_Tbl_Title.TitleName, '
                    set   @sqlQuery1 = @sqlQuery1 + ' dbo.Ta_Tbl_levelDetails.name'
					set   @sqlQuery1 = @sqlQuery1 + ' ORDER BY b.Employee_Code_Id'
					exec(@sqlQuery + ' ' +  @sqlQuery1)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--EXEC [Proc_TA_RptDetails] '2012-05-01','Emp1'
CREATE PROCEDURE [dbo].[Proc_TA_RptDetails]
 @fromDate datetime,
 @Id VARCHAR(100)
AS  
BEGIN  
	SELECT 
		'InTime[' + PD.InTime + '], OutTime[' + PD.OutTime + '], BreakOut[' + PD.BreakOut	+ '], BreakIn[' + PD.BreakIn + ']' FROM TA_Tbl_ProcessedData PD
	WHERE PD.[Date] = CONVERT(DATETIME, CAST(@fromDate AS NVARCHAR(50)), 102) AND PD.Employee_Code_Id = @Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDeviationReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_RptDeviationReport '20211101','20211122','','','Superadmin',0,0,0,0,'Both',0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptDeviationReport]
(
	@FromDate varchar(20),
	@ToDate varchar(20),
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),
	@UserGroupName varchar(250),
	@DesignationID int,
	@employeeCategory int,
	@employeeType int,
	@ParentID int,
	@Gender varchar(10),
	@ProcessType char(2),
	@EmpAutoID int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel int
	SET @Isdel=0
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmployeeName(EmployeeID varchar(25))
	create table #EmployeeID(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '')
	begin		
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@EmployeeId)
	end	
	if(@EmployeeName is not null and @EmployeeName <> '')
	begin
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
	end	
	--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Type insert in Temporary table
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		Left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id 
		where emp.Isdeleted=0 group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery='select	RD.CLK_CARDID as ''Employee_Code_Id'',
							Emp.Employee_FirstName + '' '' + isnull(Emp.Employee_LastName,'''') as EmployeeName,
							(isnull(Ter.Terminal_Name,'''') + '' ('' + RD.CLK_DEVICEID + '')'') as ''Terminal_Name'', 
							case	when '+cast(@dateFormat as varchar(100))+'=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') else CONVERT(VARCHAR, RD.CLK_DATE, '+cast(@dateFormat as varchar(100))+') 
									end AS ShiftDate,
							case	when '+cast(@dateFormat as varchar(100))+'=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') else CONVERT(VARCHAR, RD.CLK_DATE, '+cast(@dateFormat as varchar(100))+') end AS PunchDate,
							RD.CLK_TIME as PunchTime,(isnull(PY.PunchType,'''') + '' ('' + RD.CLK_TYPE + '')'') as ''PunchType'',RD.*,ld.Name as LevelName,CONVERT(datetime,''01-01-1900 '' + RD.CLK_Time,103) as OrderTime, case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''Processing...'' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''Processed'' else case when ReasonId=''0'' then ''Processed'' else case when ReasonId=''1'' then ''Remedy 1'' else case when ReasonId=''2'' then ''Remedy 2'' else case when ReasonId=''3'' then ''Remedy 3'' else ''Remedy 4'' end end end end end 
									end  as Resolution,
							case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''Processing...'' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''Processed'' else ''Non Processed'' end end as Process
							, 
							BlockingType=case when Daily=1 then ''Daily 13 Hrs Exceed; '' else '''' end+
							case when DayWise=1 then ''7 Days Present; '' else '''' end+
							case when WeekWise=1 then ''Weekly 60 Hrs Exceed; '' else '''' end+
							case when QuarterWise=1 then ''Quarer Wise 75 hours Exceed; '' else '''' end+
							case when ContinuousDaywise=1 then ''7 Days Absent; '' else '''' end
	from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.SwipeCardNo=RD.CLK_CARDID  '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_BlockedEmployeesHistory BEH on EMP.Employee_code_id=BEh.EmployeeCard'
	set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID '
	set @sqlQuery = @sqlQuery + ' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value '
	if(@ParentID=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
		set @sqlQuery = @sqlQuery + ' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
	end
	if(@employeeType=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
	end
	if(@DesignationID=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
	end
	if(@employeeCategory=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
	end
	If Not (@EmployeeId = '')  
	Begin  
	SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.Employee_Code_Id '
	End
	If Not (@EmployeeName = '')  
	Begin  
		SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.Employee_Code_Id '
	End
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id 
	where RD.CLK_DATE >='''+ @FromDate +''' and RD.CLK_DATE <=''' + @ToDate +''''
	if(@ProcessType <> 0)
	begin
	if(@ProcessType =1)
	begin
		set @sqlQuery = @sqlQuery + ' and CLK_FLAG=1 and CLK_PROCESS=1 '
	end
	else if(@ProcessType =2)
	begin
		set @sqlQuery = @sqlQuery + ' and CLK_FLAG=1 and CLK_PROCESS=0 '
	end
	end	
	if(@Gender<>'Both')
	begin
		set @sqlQuery = @sqlQuery + ' and Emp.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
	end
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + ' and (Emp.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	--6402
	set @sqlQuery = @sqlQuery + ' and CLK_Type=6402'
	set @sqlQuery = @sqlQuery +' Order by RD.CLK_DATE,OrderTime desc'
	exec(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_RptDiscrepancy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- proc_ta_RptDiscrepancy '2016/01/01','2016/12/31','','0','','',0,0,'SuperAdmin','0','',0,0,'Both',0,1
CREATE PROCEDURE [dbo].[proc_ta_RptDiscrepancy]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,[Clk_CompId] varchar(10),
		[Clk_EmpId] nvarchar(50),[Clk_InDeviceId] nvarchar(20),
		[Clk_InDate] datetime,[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25),[Clk_OutDeviceId] nvarchar(20),
		[Clk_OutDate] datetime,[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25),[Clk_Process] nvarchar(1),
		[Clk_Remarks] nvarchar(500),[Clk_User] nvarchar(20),
		[Clk_Date] datetime,[Clk_Status] char(1),[IsVoid] bit
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))	
	create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(20))	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @todat,@empId
	--To split up the comma separated values
	if(@empId is not null and @empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails where ta_tbl_clockdetails.IsVoid=0 
	and (ta_tbl_clockdetails.clk_inTime is null or ta_tbl_clockdetails.clk_outTime is null)
	and ta_tbl_clockdetails.clk_Date >= @fromDat
	and ta_tbl_clockdetails.clk_Date <= @toDat
	
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo='insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
	If Not (@empId = '')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'
	Execute(@sqlCommonSwipeCardNo)	
	Declare @sqlTempProcessedData2 varchar(8000)	
	set @sqlTempProcessedData2=	'insert into  #TempProcessedData 
	select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
	from #TempEmployee INNER JOIN TA_Tbl_ProcessedData ON #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id and 
	Date between CONVERT(DATETIME,'''+cast(@fromDat as nvarchar(50))+''', 102) and CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102)'
	if(@shift<>0)  
		begin  
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + ' And TA_Tbl_ProcessedData.shift_id= '+  cast (@shift as nvarchar(50))  
		end
	Execute(@sqlTempProcessedData2)
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'select #TempClockDetails.clk_id,dbo.TA_Tbl_Employee.Employee_Code_Id as clk_EmpId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''') as empName ,right(#TempClockDetails.clk_InTime,8) as clk_InTime,'
	set @sqlQuery = @sqlQuery + 'case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_InDate, '+CONVERT(varchar,@dateFormat)+') end as inDate,
										case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end  as outDate , right(#TempClockDetails.clk_OutTime,8) as clk_OutTime,case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_Date, '+CONVERT(varchar,@dateFormat)+') end  as ClockDate,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],TA_Tbl_Title.Titlename as Designation,ta_tbl_Employee.Gender,#TempClockDetails.clk_Date as format  from #TempClockDetails'
	set @sqlQuery = @sqlQuery + ' inner join ta_tbl_Employee on #TempClockDetails.clk_EmpId = ta_tbl_employee.SwipeCardNo'
    set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=#EmpDesignation.DesignationId'
	SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData on #TempProcessedData.EmpAutoId = TA_Tbl_Employee.Employee_Id and #TempProcessedData.Date = #TempClockDetails.CLK_Date'  
	set @sqlQuery = @sqlQuery + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ((ta_tbl_employee.employee_status=1)
	or (ta_tbl_employee.employee_status=0 and convert( nvarchar(11),ta_tbl_employee.InActiveDate,102)>=CONVERT(nvarchar(11),#TempProcessedData.Date,102))
	))'
	if(@Gender<>'Both')
		begin
		   set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end	
	set @sqlQuery = @sqlQuery + '  order by  lower(#TempClockDetails.clk_EmpId),#TempClockDetails.clk_Date,#TempClockDetails.clk_InDate ,#TempClockDetails.clk_InTime, #TempClockDetails.clk_OutDate, #TempClockDetails.clk_outTime,ta_tbl_Employee.Employee_FirstName '
	if(@ExportType=1)
		begin	
			exec(@sqlQuery)	
		end
	else
		begin
		Create table #TempEarlyEntry(clk_id int, clk_EmpId nVarchar(30), empName nvarchar(100),clk_InTime nvarchar(30),indate nvarchar(20),outDate nvarchar(20),clk_OutTime nvarchar(30),ClockDate nvarchar(20),[Level Name] nvarchar(100),Designation nvarchar(100),Gender nvarchar(10),format datetime)
		insert into #TempEarlyEntry exec (@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempEarlyEntry
		insert into #TempDate 
		select distinct CAST(format as datetime),ClockDate from #TempEarlyEntry order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + '@'
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempEarlyEntry where [Level Name]=@Levelstr and ClockDate=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + '#'
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
		end
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptDocumentExpiry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Senthil
-- ALTER  date: <01-Aug-2007>
-- Description:	<Report - Document Expiry>
-- Proc_Ta_RptDocumentExpiry '01/01/2009','01/01/2030','','','','',1,1,'SuperAdmin','0','',0,0,'Both'
-- =============================================
CREATE          PROCEDURE [dbo].[Proc_Ta_RptDocumentExpiry] 
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	 --Get Current date time format
      DECLARE @dateFormat as int
      DECLARE @date as nvarchar(25)             
      SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
      IF(@date='dd/MM/yyyy')
      BEGIN
            SET @dateFormat = 103
      END
      ELSE IF(@date='MM/dd/yyyy')
      BEGIN
            SET @dateFormat = 101
      END
      ELSE
      BEGIN
            SET @dateFormat = 106
      END   
      --End
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
if(@EmployeeId is not null and @EmployeeId <> '')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	if(@Gender<>'Both')  
		begin  
			set @sqlCommon = @sqlCommon + ' and Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + ' and (Employee_ID IN (select * from #EmployeeIds)) '  
            END
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 '
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
			End
	If Not (@EmployeeName = '')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.SwipeCardNo '
			End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @TODAT,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @TODAT,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @TODAT,@EMPLOYEEID,@EMPLOYEECATEGORY
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''
		set @sqlQuery = @sqlQuery + ' select Passport_No,case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, Passport_expiryDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, Passport_expiryDate, '+CONVERT(varchar,@dateFormat)+') end
										 as passport_expiryDate,
										Visa_no,case when '+CONVERT(varchar,@dateFormat) +'=106 then
										REPLACE(CONVERT(VARCHAR, Visa_expiryDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
										else CONVERT(VARCHAR, Visa_expiryDate, '+CONVERT(varchar,@dateFormat)+') end
										as visa_expiryDate,
										Ta_tbl_Employee.Employee_Code_Id as employee_id,
										isnull(Employee_FirstName,'''') +  space(1) + isnull(Employee_LastName,'''')  as empName,
										replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
										ta_tbl_employee.Gender 
										from ta_tbl_employee '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
		SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=#EmpDesignation.DesignationId'
		SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '		
		set @sqlQuery = @sqlQuery + ' where Ta_tbl_Employee.Isdeleted=0 and 
		((employee_Status=1 ))
		and report_exclude=0'
		set @sqlQuery = @sqlQuery + ' And((passport_expirydate >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and passport_expirydate <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102))'
		set @sqlQuery = @sqlQuery + ' or  (visa_expirydate>= CONVERT(DATETIME,''' +  cast(@fromDat as nvarchar(11)) + ''', 102) and visa_expirydate <= CONVERT(DATETIME,''' + cast(@toDat as nvarchar(11)) + ''', 102)))'
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		set @sqlQuery = @sqlQuery + ' order by ta_tbl_employee.Employee_Code_Id'		
		exec(@sqlQuery)
 drop table #EmpLevel
 drop table #EmpDesignation
 drop table #EmpType
 drop table #EmpCategory
 --drop table #EmpPay
 drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptEarlyEntry '','1','01/June/2018','30/June/2018','',0,0,0,'UxHOD Distribution','0','',0,0,'Both',1,'',94
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptEarlyEntry]
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@ExportType int,
	@MINExceptionHOURS AS VARCHAR(6),
	@EmpAutoID int
)  
AS
BEGIN		
	SET NOCOUNT ON;
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_empId varchar(100)
	Declare @local_shift int
	Declare @local_EmployeeName varchar(50)
	Declare @local_LevelID varchar(8000)
	Declare @local_EmployeeCategory int
	Declare @local_EmployeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_ExportType int
	Declare @local_MINExceptionHOURS AS VARCHAR(6)
	Declare @local_EmpAutoID int
	
	Set @local_fromDat=@FromDate
	Set @local_ToDat=@ToDate
	Set @local_empId=@EmployeeID
	Set @local_shift=@shift
	Set @local_EmployeeName=@EmployeeName
	Set @local_LevelID=@LevelID
	Set @local_EmployeeCategory=@EmployeeCategory
	Set @local_EmployeeType=@EmployeeType
	Set @local_UserGroupName=@UserGroupName
	Set @local_EmpSwipeCard=@EmpSwipeCard
	Set @local_ParentId=@ParentId
	Set @local_DesignationID=@DesignationID
	Set @local_Gender=@Gender
	Set @local_ExportType=@ExportType
	Set @local_MINExceptionHOURS=@MINExceptionHOURS
	Set @local_EmpAutoID=@EmpAutoID
	Set @local_GradeLevel=@GradeLevel
	
	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX(':',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX(':',@local_MINExceptionHOURS)+1,2)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		shift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		LateEntryReason nvarchar(260),
		Exactshift_StartTime nvarchar(25),
		EarlyInMins int,
		EarlyInHrs varchar(10)
	)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId] ASC  
	)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId] ASC  
	)ON [PRIMARY]	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_empId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_empId,@local_EmployeeType
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_empId,@local_EmployeeCategory
	--To split up the comma separated values
	if(@local_empId is not null and @local_empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@local_empId)
		end	
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel='insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDat as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@local_empId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData= 'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
	If Not (@local_empId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.report_exclude=0 '
		if(@local_Gender<>'Both')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + ' and TA_Tbl_Employee.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end	
		if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1= 'insert into #TempProcessedData
	select	#TempEmployee.EmpAutoId,
			pd.Date,
			pd.Employee_Code_Id,
			pd.InTime,
			pd.OutTime,
			pd.Shift_Id,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime),
			pd.Process_Rec_ID,
			pd.LateIn,
			pd.LateInMins,
			pd.LateEntryReason,
			cast(S.Shift_startTime as datetime),
			EarlyInMins,
			EarlyInHrs
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join ta_tbl_shift S on S.Shift_Id=PD.Shift_Id	
	where pd.InTime is not null AND pd.InTime <> ''0'' AND pd.InTime <> ''00:00'' and 
	(cast(s.Shift_StartTime as datetime) > cast(PD.InTime AS datetime)) and PD.EarlyEntry=1 AND
	(PD.FNAttendanceCode<>''CL'' or PD.ANAttendanceCode<>''CL'') and	
	(pd.Date>=CONVERT(DATETIME,'''+cast(@local_fromDat as nvarchar(50))+''', 102) and pd.Date <=CONVERT(DATETIME,'''+cast(@local_ToDat as nvarchar(50))+''', 102))'
	if(@local_shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' and PD.shift_id= '+  cast (@local_shift as nvarchar(50))
		end
	IF (@local_MINExceptionHOURS<>'')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND PD.EarlyInMins >= ' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode='CL' 
	Declare @SelectSQL As Varchar(8000)  
	Set @EmployeeName = @local_EmployeeName  
	Set @SelectSQL = ' '
	
	
	Set @SelectSQL = @SelectSQL + '	SELECT ED.Employee_Code_Id AS CardNo, '  
	Set @SelectSQL = @SelectSQL + '	ED.Employee_FirstName + '  
	Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '  
	Set @SelectSQL = @SelectSQL + '	replace(L.name,''&amp;'',''&'')  AS [Level Name],replace(T.TitleName,''&amp;'',''&'')  AS Designation,Gender as Gender, '  
	set @SelectSQL = @SelectSQL + '	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, pd.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
											else CONVERT(VARCHAR, pd.Date, '+CONVERT(varchar,@dateFormat)+') 
									end as Date,
									replace(sh.shift_shortName,''&amp;'',''&'') as shift_shortName,
									case when (select TimeFormat from TA_Tbl_DateandTimeFormat)=''hh:mm tt'' then PD.Shift_StartTime else CONVERT(varchar(5), DATEADD(minute,0,convert(datetime,PD.Shift_StartTime,0)), 114) end as Shift_StartTime, '
	Set @SelectSQL = @SelectSQL + '	CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,pd.intime,0)), 114)
											ELSE SUBSTRING(pd.intime,13,5)+'' '' + SUBSTRING(pd.intime,18,2) 
									END InTime,
									case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
											''0''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) 
										else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) 
									end
									+ '':'' + 
									case	when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''00''
											else	case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
															''0''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
														else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) 
													end
									end As EarlyBy,
									PD.LateEntryReason as Reason,
									((SUBSTRING(ISNULL(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''0''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '':'' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''00''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''0''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end,''00:00''),0,CHARINDEX('':'',case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''0''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '':'' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''00''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''0''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end))*60) + (SUBSTRING(ISNULL(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''0''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '':'' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''00''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''0''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end,''00:00''),(LEN(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''0''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '':'' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''00''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''0''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end)-1),2))) AS EarlyInMins,PD.Process_Rec_ID,pd.Date as format
									FROM TA_Tbl_Employee ED  '  
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId '  
	Set @SelectSQL = @SelectSQL + ' INNER JOIN ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID '	
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid=ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id '    
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= ED.Employee_Id '  
	Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId '  
	SET @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID'  
	set @SelectSQL = @SelectSQL + ' inner join #EmpCategory on ED.Employee_Id = #EmpCategory.EmployeeId'  	
	set @SelectSQL = @SelectSQL + ' inner join #EmpType on ED.Employee_Id = #EmpType.EmployeeId'  	
	Set @SelectSQL = @SelectSQL + ' INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id '  
	set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '   
	Set @SelectSQL = @SelectSQL + ' Where 1=1 and 
									( (ED.Employee_Status=1) or
									( ED.Employee_Status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102))
									) '
	Set @SelectSQL = @SelectSQL + ' and (cast(PD.Exactshift_StartTime as datetime) > cast(PD.InTime AS datetime)) AND PD.LateInMins=0  '  		
	set @SelectSQL = @SelectSQL + ' order by [CardNo],format , pd.Intime,PD.Shift_StartTime'  
	if(@local_ExportType=1)
		begin
			exec (@SelectSQL)  
		end
	else
		begin
			Create table #TempEarlyEntry
			(		
				CardNo nVarchar(30), 
				[Employee Name] nvarchar(100),
				[Level Name] nvarchar(100),
				designation nvarchar(100),
				Gender nvarchar(10),
				Date nvarchar(20),
				shift_shortName nvarchar(4),
				Shift_StartTime nvarchar(20),
				InTime nvarchar(10),
				EarlyBy nvarchar(10),
				Reason nvarchar(200),		
				EarlyInMins decimal(18,2),
				Peocess_Rec_ID int, 
				fromat datetime
			)
			insert into #TempEarlyEntry exec (@SelectSQL)
			create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
			create table #TempDate(ID int identity(1,1),Date nvarchar(20))
			insert into #TempLevelName 
			select distinct [Level Name] from #TempEarlyEntry
			insert into #TempDate 
			select distinct Date from #TempEarlyEntry
			declare @couLevel int
			set @couLevel=(select COUNT(*) from #TempLevelName)
			declare @couDate int
			set @couDate=(select COUNT(*) from #TempDate)
			declare @i int
			set @i=1
			declare @j int
			set @j=1
			declare @SQLString1 nvarchar(Max)
			set @SQLString1=''
			while @i<=@couLevel
			begin
				declare @Levelstr nvarchar(100)
				set @Levelstr =(select Name from #TempLevelName where ID=@i)
				set @SQLString1 = @SQLString1 + @Levelstr + '@'
				while @j<=@couDate
				begin
					declare @RowCount int
					set @RowCount=(select COUNT(*) from #TempEarlyEntry where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
					if(@RowCount!=0)
					begin
						set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
					end
					else
					begin
						set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
					end
					set @j=@j+1
				end
				SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
				set @SQLString1 = @SQLString1 + '#'
				set @j=1
				set @i=@i+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			select @SQLString1 as 'Value'
			drop table #TempDate
			drop table #TempEarlyEntry
			drop table #TempLevelName
		end
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  	
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyExit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- proc_TA_EarlyExit '01/Jan/2017','30/jun/2017','',0,'','0','0','0','SuperAdmin',0,'',0,0,'Both',1,''
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
create  PROCEDURE [dbo].[Proc_TA_RptEarlyExit]
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @empId varchar(100),  
	 @shift int,  
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000),
	 @EmployeeCategory int,	   
	 @EmployeeType int,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @ExportType int,
	 @MINExceptionHOURS AS VARCHAR(6),
	 @EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_empId varchar(100)
	Declare @local_shift int
	Declare @local_EmployeeName varchar(50)
	Declare @local_LevelID varchar(8000)
	Declare @local_EmployeeCategory int
	Declare @local_EmployeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_ExportType int
	Declare @local_MINExceptionHOURS AS VARCHAR(6)
	Declare @local_EmpAutoID int
	
	Set @local_fromDat=@fromDat
	Set @local_ToDat=@ToDat
	Set @local_empId=@empId
	Set @local_shift=@shift
	Set @local_EmployeeName=@EmployeeName
	Set @local_LevelID=@LevelID
	Set @local_EmployeeCategory=@EmployeeCategory
	Set @local_EmployeeType=@EmployeeType
	Set @local_UserGroupName=@UserGroupName
	Set @local_EmpSwipeCard=@EmpSwipeCard
	Set @local_ParentId=@ParentId
	Set @local_DesignationID=@DesignationID
	Set @local_Gender=@Gender
	Set @local_ExportType=@ExportType
	Set @local_MINExceptionHOURS=@MINExceptionHOURS
	Set @local_EmpAutoID=@EmpAutoID
	Set @local_GradeLevel=@GradeLevel
	 
	Declare @RowCountEmployeeID int
	Declare @RowCountEmployeeName int
	Declare @RowCountSwipeCardNo int
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX(':',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX(':',@local_MINExceptionHOURS)+1,2)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(30),
		OutTime nvarchar(30),
		Shift_Id int,
		EarlyOut nvarchar(20),
		EarlyOutReason nvarchar(Max),
		EarlyOutMins float,
		Process_Rec_ID bigint,
		Shift_EndTime nvarchar(20)
	)
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_empId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_empId,@local_EmployeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_empId,@local_EmployeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @local_ToDat,@local_empId
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	if(@local_empId is not null and @local_empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@local_empId)
		end	
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData= 'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@local_empId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and dbo.TA_Tbl_Employee.IsDeleted = ''0''  and dbo.TA_Tbl_Employee.report_exclude=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + ' and TA_Tbl_Employee.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(max)
	set @sqlTempProcessedData1= 'insert into #TempProcessedData
	select	#TempEmployee.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Shift_Id,
			PD.EarlyOut,
			PD.EarlyOutReason,
			PD.EarlyOutMins,
			PD.Process_Rec_ID,
			PD.Shift_EndTime
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id
    where (PD.Date >= CONVERT(DATETIME,'''+cast( @local_fromDat as nvarchar(50))+''', 102))  
	AND (PD.Date <= CONVERT(DATETIME,'''+cast(@local_ToDat as nvarchar(50))+''', 102)) 
	AND PD.EarlyOut <> ''0'' and PD.EarlyOut <> ''00:00:00'' and PD.EarlyOut <> ''00:00''
	and PD.EarlyOut is not null AND EarlyOutMins > 0 AND OutTime is not null AND OutTime <>'''' AND OutTime <> ''0'' AND OutTime <> ''00:00'' and processflag=1 '
	if(@local_shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' and PD.shift_id= '+  cast (@local_shift as nvarchar(50))
		end
	IF (@local_MINExceptionHOURS<>'')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND PD.EarlyOutMins >= ' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	declare @sqlQuery as varchar(max)  
	set @sqlQuery = ''   
	
	
	
	set @sqlQuery = @sqlQuery + ' select	dbo.TA_Tbl_Employee.Employee_Code_Id,
											(dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''')) as Employee_FirstName,
											replace(Ta_tbl_LevelDetails.Name,''&amp;'',''&'') as LevelName, 
											replace(Ta_tbl_Title.TitleName,''&amp;'',''&'') as TitleName,											
											
											case when '+cast(@dateFormat as varchar(100))+'=106 then
											REPLACE(CONVERT(VARCHAR, #TempProcessedData.Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
											else CONVERT(VARCHAR, #TempProcessedData.Date, '+cast(@dateFormat as varchar(100))+') end as date,
											ta_tbl_shift.shift_shortName,
											#TempProcessedData.Shift_EndTime as shiftOut ,
											CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OutTime,0)), 114) 
													ELSE OutTime
											END OutTime,
											#TempProcessedData.EarlyOut,											
											#TempProcessedData.EarlyOutReason as Reason,
											#TempProcessedData.Process_Rec_ID,
											#EmpLevel.LevelId,											 
											#TempProcessedData.shift_id,'  
	set @sqlQuery = @sqlQuery + '	TA_Tbl_Employee.Gender,
									EarlyOutMins,
									#TempProcessedData.Date as format FROM  #TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON #TempProcessedData.EmpAutoId = dbo.TA_Tbl_Employee.Employee_ID '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlQuery = @sqlQuery + ' INNER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	if(@RowCountEmployeeID >0)
		begin
			Set @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		end
	if(@RowCountSwipeCardNo >0)
		begin
			Set @sqlQuery = @sqlQuery + ' INNER JOIN #SwipeCardNo on #SwipeCardNo.SwipeCardNo=TA_Tbl_Employee.SwipeCardNo '
		end	
	set @sqlQuery = @sqlQuery + ' where 
	((dbo.TA_Tbl_Employee.employee_status=1)
	or
	(dbo.TA_Tbl_Employee.employee_status=0 and convert(nvarchar(11),dbo.TA_Tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))
	) '
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	set  @sqlQuery = @sqlQuery + '  order by #TempProcessedData.Employee_Code_Id,#TempProcessedData.Date'  
	 if(@local_ExportType=1)
		begin
			Exec(@sqlQuery)   
		end
	else
	begin
		Create table #TempEarlyExit
		(
			Employee_Code_Id nvarchar(30),
			[Employee_FirstName] nvarchar(100),
			LevelName nvarchar(100),
			designation nvarchar(100),
			Date nvarchar(20),
			shift_shortName nvarchar(4),
			shiftOut nvarchar(20),
			OutTime nvarchar(20),
			EarlyOut nvarchar(20),
			Reason nvarchar(max),
			Peocess_Rec_ID int,
			Levelid int,
			shift_id int,
			Gender nvarchar(10),
			EarlyOutMins decimal(18,2),
			format datetime
		)
		insert into #TempEarlyExit exec (@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct LevelName from #TempEarlyExit
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempEarlyExit order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + '@'
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempEarlyExit where LevelName=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + '#'
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
		drop table #TempDate
		drop table #TempLevelName
		drop table #TempEarlyExit
	end
  	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory    
    drop table #LevelRights
    drop table #TempProcessedData
    drop table #TempEmployee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- ALTER  date: 04August08   
-- Modified By	:	Sashma	
-- Modified On	:	12-May-2011
-- Proc_Ta_RptEmployee '','04/Feb/2023','',0,'','1','0','0','all','SuperAdmin','0','','',1,0,'Both',1,15,0,0,0,0
-- Description:	Report Employee Details
-- Modified By		:	Gopinath.K
-- Modified Date	:	21-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployee]
(
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@SwipeOpt varchar(10),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int,
    @expiryNo int,
    @Filt_UsrGrp int=null,  
	@Leave_Policy int=null,  
    @Reporting_to int=null,  
    @Approval_Authority int=null
)
AS
BEGIN
	set nocount on
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	if(charIndex('-',@ToDat)>0)
		begin
			set @ToDat=(select convert(varchar(30),getdate(),102))
		end
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	--(
	--	[EffectiveDate],[LevelId],[EmployeeId] ASC
	--) ON [PRIMARY]
	--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	--(
	--	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	--)ON [PRIMARY]
	--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	--(
	--	[EffectiveDate],[TypeId],[EmployeeId] ASC
	--) ON [PRIMARY]
	--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	--(
	--	[EffectiveDate],[CategoryId],[EmployeeId]  ASC
	--)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @todat,@EmployeeId
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	
	SELECT	E.Employee_code_Id as employee_id,
			isnull(Employee_firstName,'') + Space(1) + isnull(Employee_LastName,'') as empname,
			dbo.Fn_ReplaceCharacter(TA_Tbl_Title.TitleName,'&') as TitleName,
			E.Gender,
			dbo.Fn_ReplaceCharacter(Ta_Tbl_levelDetails.name,'&') as name,
			Convert(nvarchar(20),E.DateOfJoining,101) as dateJoin,
			convert(nvarchar(20),E.DateofBirth,101) as dateOfBirth,
			E.Nationality, 
			E.Visa_No, 
			CASE	WHEN CAST(@DATEFORMAT AS NVARCHAR(10))=106 THEN REPLACE(CONVERT(VARCHAR, E.Visa_expirydate,@DATEFORMAT),'','-') 
					ELSE CONVERT(VARCHAR, E.Visa_expirydate,@DATEFORMAT)
			END AS Visa_expirydate, 
			E.Passport_No, 
			CASE	WHEN CAST(@DATEFORMAT AS NVARCHAR(10))=106 THEN REPLACE(CONVERT(VARCHAR, E.Passport_expirydate,@DATEFORMAT),'','-') 
					ELSE CONVERT(VARCHAR, E.Passport_expirydate,@DATEFORMAT) 
			END AS Passport_expirydate,
			E.CustomField1, 
			CASE	WHEN CAST(@DATEFORMAT AS NVARCHAR(10))=106 THEN REPLACE(CONVERT(VARCHAR, E.CustomField2,@DATEFORMAT),'','-') 
					ELSE CONVERT(VARCHAR, E.CustomField2,@DATEFORMAT) 
			END AS CustomField2,
			status = case employee_status  when '1'  then 'Active'  when '0' then 'Inactive' end, 
			isnull(dbo.Fn_ReplaceCharacter(dept.name,'&'),'-') as department ,
			E.Employee_Id as empAutoId,
			E.Report_Exclude  
	FROM TA_Tbl_Employee E 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId  
	LEFT OUTER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelID = Ta_Tbl_levelDetails.id  
	LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id  
	LEFT OUTER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid=E.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id  
	Left outer join #EmployeeName on #EmployeeName.EmployeeID=E.Employee_code_Id 
	WHERE E.Isdeleted = 0 AND (E.Employee_Code_Id <> '18000000')
	and(@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)	  
	and(@expiryNo=0 or ((Passport_expirydate is not null and Passport_expirydate<=DATEADD(d,15,getdate())) 
	or (Visa_expirydate is not null and Visa_expirydate<=DATEADD(d,15,getdate())))) 
	and(ISNULL(@Filt_UsrGrp,0)=0 or E.UserGroup_Id= @Filt_UsrGrp)
	and(ISNULL(@Reporting_to,0)=0 or E.Reporting_To=@Reporting_to)
	and(ISNULL(@Approval_Authority,0)=0 or E.Leave_Sanc_Authority=@Approval_Authority)
	and(@Gender='Both' or Gender=@Gender)
	and(@isReportingto=0 or (Employee_ID IN (select * from #EmployeeIds)))
	and (@EmployeeStatus='All' or E.Employee_Status=(case when @EmployeeStatus='Active' then 1 else 0 end))
	and (ISNULL(@fromDat,'')='' or E.DateOfJoining >= CONVERT(DATETIME, cast( @fromDat as nvarchar(50))))
	and (ISNULL(@ToDat,'')='' or E.DateOfJoining <= CONVERT(DATETIME, cast( @ToDat as nvarchar(50))))
	order by E.Employee_code_Id 
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #EmployeeName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeCompOffStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*   
Procedure Name	:	Proc_TA_EmployeeCompOffOTSanction
Tables Included :	TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
					TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
					TA_Tbl_Grade,ta_tbl_shift
Modified On		:   20-Jun-2016
Description		:	Report Issue
Modified By		:   Karthikeyan.R
Description		:	Remove The Date Convertion In Expaire Date Calculation
EXEC Proc_TA_RptEmployeeCompOffStatus @FromDate='2000-01-01 00:00:00',@ToDate='2023-10-03 00:00:00',@EmpId=N'',@ShiftId=0,@EmployeeName=N'',@LevelID=N'0',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'1',@Status=N'All',@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',@EmpAutoID=1
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeCompOffStatus]
(
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmpId VARCHAR(100),
	@ShiftId INT,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeCategory INT, 
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@Status VARCHAR(20)	,
	@EmpSwipeCard VARCHAR(20),
	@ParentId INT,
	@DesignationID INT,
    @Gender VARCHAR(10),
    @EmpAutoID int
)
AS
BEGIN
	set nocount on;
	DECLARE @SQLQuery VARCHAR(MAX)
	SET @SQLQuery = ''
	--Get the Current date time format
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	--End
--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	CREATE TABLE #LevelRights(LevelId INT)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	INSERT INTO #LevelRights 
		SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ,[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ,[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@empId,@employeeCategory
	--To split up the comma separated values
	if(@empId is not null and @empId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@empId)
		end
			if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
If Not (@empId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo '
		End
		If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
execute(@sqlEmpLevel)	
--AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''00:00''), 108) != ''00:00''
--AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''00:00''), 108) != ''00:00'' 
	SET @SQLQuery = 'SELECT Emp.SwipeCardNo, RTRIM(LTRIM(Emp.Employee_FirstName + SPACE(1) + ISNULL(Emp.Employee_LastName , ''''))) EmployeeName,'
	SET @SQLQuery = @SQLQuery + ' Emp.Gender,case	when ' + CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR(11), PD.[Date], '+ CONVERT(varchar,@dateFormat) +'),'' '',''-'') else CONVERT(VARCHAR(11), PD.[Date], '+ CONVERT(varchar,@dateFormat) +') end AS [Date], PD.HrsExtra,PD.ActHrsExtra, PD.OTSanctioned, PD.CompoffSanctioned, PD.OverTimeStatus, PD.CompOffSatus, ISNULL(S.Shift_ShortName, ''Off'') AS Shift_ShortName , PD.[NoOfDaysTaken], PD.ExtraMins,PD.ActExtraMins,ExpiryDate FROM'
	SET @SQLQuery = @SQLQuery + ' (SELECT OTS.Employee_Id, OTS.Process_RecID,  OTS.[Date] [Date], OTS.HrsExtra,isnull(OTS.ActHrsExtra,OTS.HrsExtra) [ActHrsExtra], (CASE WHEN OTS.OTEligible = 1 THEN OTS.HrsExtra ELSE ''00:00'' END) OTSanctioned,'
	SET @SQLQuery = @SQLQuery + ' (CASE WHEN OTS.CompOffEligible = 1 THEN OTS.HrsExtra ELSE ''00:00'' END) CompoffSanctioned, OTS.OverTimeStatus, (CASE WHEN OTS.OverTimeStatus = ''Approved'' AND OTS.CompOffEligible = 1 THEN ''Taken'' ELSE ''-'' END) [CompOffSatus], PD.Employee_Code_Id, PD.Shift_Id, (ISNULL(OTS.NoOfDays, 0.0) - ISNULL(OTS.RemainingDays, 0.0)) [NoOfDaysTaken], OTS.ExtraMins,ISNULL(OTS.ActExtraMins,OTS.ExtraMins) [ActExtraMins],
	ExpiryDate=case	when ' + CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR(11), DateToExpired, '+ CONVERT(varchar,@dateFormat) +'),'' '',''-'') else CONVERT(VARCHAR(11), DateToExpired, '+ CONVERT(varchar,@dateFormat) +') end
	FROM TA_Tbl_OverTimeStatus OTS'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OTS.Process_RecID'
	SET @SQLQuery = @SQLQuery + ' WHERE PD.OtMins != 0 AND OTS.NoOfDays > OTS.RemainingDays AND ISNULL(OTS.LeaveApplicationId, '''') != '''' AND PD.[Date] BETWEEN ''' + CONVERT(VARCHAR(11), @FromDate, 101) + ''' AND ''' + CONVERT(VARCHAR(11), @ToDate, 101) + ''' UNION ALL' 
	SET @SQLQuery = @SQLQuery + ' SELECT OTS.Employee_Id, OTS.Process_RecID, CONVERT(VARCHAR(11), OTS.[Date], 101) [Date], OTS.HrsExtra,isnull(OTS.ActHrsExtra,OTS.HrsExtra) [ActHrsExtra], (CASE WHEN OTS.OTEligible = 1 THEN OTS.HrsExtra ELSE ''00:00'' END) OTSanctioned,'
	SET @SQLQuery = @SQLQuery + ' (CASE WHEN OTS.CompOffEligible = 1 THEN OTS.HrsExtra ELSE ''00:00'' END) CompoffSanctioned, OTS.OverTimeStatus, (CASE WHEN ISNULL(OTS.DateToExpired, PD.[Date]) < GETDATE() AND OTS.CompOffEligible = 1 THEN ''Expired'' WHEN OTS.CompOffEligible = 0 THEN ''-'' ELSE ISNULL(OTS.CompOffSatus, OTS.OverTimeStatus) END) [CompOffSatus], PD.Employee_Code_Id, PD.Shift_Id, ISNULL(OTS.RemainingDays, 0.0) [NoOfDaysTaken], OTS.ExtraMins,ISNULL(OTS.ActExtraMins,OTS.ExtraMins) [ActExtraMins],
	ExpiryDate=case	when ' + CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR(11), DateToExpired, '+ CONVERT(varchar,@dateFormat) +'),'' '',''-'') else CONVERT(VARCHAR(11), DateToExpired, '+ CONVERT(varchar,@dateFormat) +') end
	FROM TA_Tbl_OverTimeStatus OTS'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OTS.Process_RecID'
	SET @SQLQuery = @SQLQuery + ' WHERE PD.OtMins != 0 AND (OTS.RemainingDays > 0.0 OR OTS.RemainingDays IS NULL) AND ISNULL(OTS.CompOffSatus, ''Not Taken'') != ''Taken'' AND PD.[Date] BETWEEN ''' + CONVERT(VARCHAR(11), @FromDate, 101) + ''' AND ''' + CONVERT(VARCHAR(11), @ToDate, 101) + ''' UNION ALL'
	SET @SQLQuery = @SQLQuery + ' SELECT EMP.Employee_Id, PD.Process_Rec_ID, CONVERT(VARCHAR(11), PD.[Date], 101) [Date],'
	SET @SQLQuery = @SQLQuery + ' (CASE WHEN PD.HrsOT != ''00:00'' THEN PD.HrsOT WHEN PD.NormOT != ''00:00'' THEN PD.NormOT WHEN PD.OffOT != ''00:00'' THEN PD.OffOT WHEN PD.HolOT != ''00:00'' THEN PD.HolOT END) [HrsExtra],'
SET @SQLQuery = @SQLQuery + ' (CASE WHEN isnull(PD.ActHrsOT,PD.HrsOT) != ''00:00'' THEN isnull(PD.ActHrsOT,PD.HrsOT) WHEN isnull(PD.ActNormOT,PD.NormOT) != ''00:00'' THEN isnull(PD.ActNormOT,PD.NormOT) WHEN isnull(PD.ActOffOT,PD.OffOT) != ''00:00'' THEN isnull(PD.ActOffOT,PD.OffOT) WHEN isnull(PD.ActHolOT,PD.HolOT) != ''00:00'' THEN isnull(PD.ActHolOT,PD.HolOT) END) [ActHrsExtra],'	
	SET @SQLQuery = @SQLQuery + ' ''00:00'' OTSanctioned, ''00:00'' CompoffSanctioned, ISNULL(PD.OverTimeStatus, ''Pending'') OverTimeStatus,'
	SET @SQLQuery = @SQLQuery + ' ISNULL(PD.OverTimeStatus, ''Pending'') [CompOffSatus],'
	SET @SQLQuery = @SQLQuery + ' PD.Employee_Code_Id,PD.Shift_Id, 0.0 [NoOfDaysTaken],PD.OtMins, isnull(PD.ActOtMins,PD.OtMins) [OtMins],ExpirtyDate=''''  FROM TA_Tbl_ProcessedData PD'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo'	
	SET @SQLQuery = @SQLQuery + ' WHERE Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1 AND PD.OtMins != 0 AND PD.Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus) AND PD.[Date] BETWEEN ''' + CONVERT(VARCHAR(11), @FromDate, 101) + ''' AND ''' + CONVERT(VARCHAR(11), @ToDate, 101) + ''') PD' 
	SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.EmployeeId = Emp.Employee_Id'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id = ELP.LeavePolicy_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId'
	SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel EL ON EL.EmployeeId = Emp.Employee_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation ED ON ED.EmployeeId = Emp.Employee_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType ET ON ET.EmployeeId = Emp.Employee_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory EC ON EC.EmployeeId = Emp.Employee_Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = EL.LevelId'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
	SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'	 
	SET @SQLQuery = @SQLQuery + ' WHERE Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1'
	SET @SQLQuery = @SQLQuery + ' AND Emp.IsDeleted = 0 AND Emp.Employee_Status = 1'
	SET @SQLQuery = @SQLQuery + ' AND YS.IsActive = 1 AND Emp.Report_Exclude = 0 AND' --LP.OtDayWise = 1 AND 
	SET @SQLQuery = @SQLQuery + ' ((Emp.Employee_Status=1) OR (Emp.Employee_Status = 0 AND CONVERT(NVARCHAR(11), Emp.InActiveDate, 102) >= CONVERT(NVARCHAR(11), PD.[Date], 102)))'	
	IF(@UserGroupName <> 'SuperAdmin')
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel  
	END
	IF(@ShiftId<>0) 
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND PD.[Shift_Id] = ' + CAST(@ShiftId AS NVARCHAR(50))  
	END
	--IF NOT(@EmployeeName = '')
	--BEGIN
	--Declare @Tempname nvarchar(200)
 --        set @Tempname= '(Emp.Employee_FirstName + '' '' + isnull(Emp.Employee_LastName,'''')'
	--     set @sqlQuery = @sqlQuery + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 
	--	--SET @SQLQuery = @SQLQuery + ' AND (Emp.Employee_FirstName + '' '' + ISNULL(Emp.Employee_LastName, '''') LIKE ''' + @EmployeeName + '%'')'
	--END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@EmployeeCategory AS VARCHAR(10))
	END
	IF(@EmployeeType<>0)
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@EmployeeType AS VARCHAR(10))
	END
	IF NOT(@EmpSwipeCard = '')  
    BEGIN
		SET @SQLQuery = @SQLQuery + ' AND Emp.SwipeCardNo = ''' + @EmpSwipeCard + ''''
	END
	--IF NOT(@EmpId='')
	--BEGIN
	--	SET @SQLQuery = @SQLQuery + ' AND Emp.Employee_Code_Id = ''' + CAST(@EmpId AS VARCHAR(50)) + ''''
	--END
	IF(@DesignationID<>0)
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND ED.DesignationId = ' + CAST(@DesignationID AS NVARCHAR(8))
	END
	IF(@Gender<>'Both')
	BEGIN
		SET @SQLQuery = @SQLQuery + ' AND Emp.Gender = ''' + CAST(@Gender AS NVARCHAR(8)) + ''''
	END
	if(@isReportingto > 0)
    BEGIN
       set @SQLQuery = @SQLQuery + ' and (Emp.Employee_ID IN (select * from #EmployeeIds)) '  
    END
	IF NOT(@Status = '' OR @Status = 'All')
	BEGIN
		IF(@Status = 'Pending')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (PD.OvertimeStatus IS NULL OR PD.OvertimeStatus = ''' + @Status + ''')'
		END
		ELSE
		BEGIN
		    SET @SQLQuery = @SQLQuery + ' AND PD.OvertimeStatus = ''' + @status + ''''
		END
    END
	SET @SQLQuery = @SQLQuery + ' ORDER BY PD.Employee_Code_Id, PD.[Date]'
	EXEC(@SQLQuery)
	print(@SQLQuery)
--Remove the temporary tables here
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistory '01/01/1970','08/20/2008','',0,'','',0,0,'Admin',3
-- Description:	Report Employee History Details
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistory]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(3000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery = @sqlQuery + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_EmployeeLevel.EffectiveDate as LevelEffectiveDate,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_EmployeeDesignation.EffectiveDate as DesigEffectiveDate,dbo.TA_Tbl_Category.CategoryName,TA_Tbl_EmployeeCategory.EffectiveDate as CatEffectiveDate,dbo.TA_Tbl_Type.TypeName,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate,dbo.TA_Tbl_EmployeePay.BasicPay,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate '		
		set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId'		
		set @sqlQuery = @sqlQuery + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		if not(@fromDat='')		
		begin
		set @sqlQuery = @sqlQuery + ' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '		
		End
		if not (@ToDat='')
		begin
		set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
		end
		if not(@EmployeeName='' or @EmployeeName='0')
		begin
			set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if not (@EmployeeId='' or @EmployeeId='0')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
		end
		if not (@EmployeeCategory=0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))
		end
		if not(@LevelID='' or @LevelID='0')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelId +')'
		end			
		set @sqlQuery = @sqlQuery + ' order by dbo.TA_Tbl_Employee.Employee_code_Id '
		exec(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistoryNew '','03/26/2009','',0,'','47',0,0,'SuperAdmin',7,'',323,0,'Both'
-- Description:	Report Employee History Details
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		declare @sqlQuery1 as varchar(8000)
		declare @sqlQuery2  as varchar(8000)
		declare @sqlQuery3  as varchar(8000)
		declare @sqlQuery4  as varchar(8000)
		declare @sqlQuery5  as varchar(8000)
		declare @sqlCommon  as varchar(8000)
		declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	set @sqlCommon=''
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlCommon = @sqlCommon + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		if not(@fromDat='')		
		begin
		set @sqlCommon = @sqlCommon + ' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '		End
		if not (@ToDat='')
		begin
		set @sqlCommon = @sqlCommon + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
		end
		If Not (@EmpSwipeCard = '')  
		Begin  
			  Set @sqlCommon = @sqlCommon + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
		if not (@EmployeeCategory=0)
		begin
			set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))
		end
		if(@DesignationID<>0)
		begin
			  set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
	    if(@Gender<>'Both')
		begin
			  set @sqlCommon = @sqlCommon + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
--Select employee level
set @sqlQuery1 = ''
		set @sqlQuery1 = @sqlQuery1 + 'SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery1 = @sqlQuery1 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery1 = @sqlQuery1 + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_EmployeeLevel.EffectiveDate as EffectiveDate, ''Employee Level '' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender '
		set @sqlQuery1 = @sqlQuery1 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery1 = @sqlQuery1 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery1 = @sqlQuery1 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery1 = @sqlQuery1 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		set @sqlQuery1 = @sqlQuery1 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery1=@sqlQuery1 + @sqlCommon
		set @sqlQuery2 = ' Union '
		set @sqlQuery2 = @sqlQuery2 + 'SELECT    distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery2 = @sqlQuery2 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery2 = @sqlQuery2 + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as name,TA_Tbl_EmployeeDesignation.EffectiveDate as EffectiveDate, ''Employee Designation '' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery2 = @sqlQuery2 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery2 = @sqlQuery2 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery2 = @sqlQuery2 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
			If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery2 = @sqlQuery2 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		set @sqlQuery2 = @sqlQuery2 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery2 = @sqlQuery2 + @sqlCommon
set @sqlQuery3 = ' Union '
		set @sqlQuery3 = @sqlQuery3 + 'SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery3 = @sqlQuery3 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery3 = @sqlQuery3 + ' dbo.TA_Tbl_Category.CategoryName AS name,TA_Tbl_EmployeeCategory.EffectiveDate as EffectiveDate, ''Employee Category '' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery3 = @sqlQuery3 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery3 = @sqlQuery3 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery3 = @sqlQuery3 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
			If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery3 = @sqlQuery3 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		set @sqlQuery3 = @sqlQuery3 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery3 = @sqlQuery3 + @sqlCommon
set @sqlQuery4 = ' Union '
		set @sqlQuery4 = @sqlQuery4 + 'SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery4 = @sqlQuery4 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery4 = @sqlQuery4 + ' dbo.TA_Tbl_Type.TypeName AS name,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate, ''Employee Type '' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery4 = @sqlQuery4 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery4 = @sqlQuery4 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery4 = @sqlQuery4 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
			If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery4 = @sqlQuery4 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		set @sqlQuery4 = @sqlQuery4 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery4 = @sqlQuery4 + @sqlCommon
set @sqlQuery5 =  ' Union '
		set @sqlQuery5 = @sqlQuery5 + 'SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery5 = @sqlQuery5 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery5 = @sqlQuery5 + ' cast(dbo.TA_Tbl_EmployeePay.BasicPay as nvarchar) AS name,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate, ''Employee Basic Pay '' as HistoryType ,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender '		
		set @sqlQuery5 = @sqlQuery5 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery5 = @sqlQuery5 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId'		
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery5 = @sqlQuery5 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
			If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery5 = @sqlQuery5 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
		set @sqlQuery5 = @sqlQuery5 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery5 = @sqlQuery5 + @sqlCommon
		exec(@sqlQuery1 + @sqlQuery2 + @sqlQuery3 + @sqlQuery4 + @sqlQuery5)
		drop table #LevelRights
--exec(@sqlQuery1)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistoryNew '','03/26/2009','',0,'','47',0,0,'SuperAdmin',7,'',323,0,'Both'
-- Description:	Report Employee History Details
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		declare @sqlQuery1 as nvarchar(4000)
		declare @sqlQuery2  as nvarchar(4000)
		declare @sqlQuery3  as nvarchar(4000)
		declare @sqlQuery4  as nvarchar(4000)
		declare @sqlQuery5  as nvarchar(4000)
		declare @sqlCommon  as varchar(8000)
		declare @EmployeeLevel1 as nvarchar(50)
        set @EmployeeLevel1= (select (N'????? ??????'))
        declare @EmployeeDesignation1 as nvarchar(50)
        set @EmployeeDesignation1= (select (N'???? ??????'))
        declare @EmployeeCategory1 as nvarchar(50)
        set @EmployeeCategory1= (select (N'??? ??????'))
        declare @EmployeeType1 as nvarchar(50)
        set @EmployeeType1= (select (N'??? ??????'))
        declare @Employeebasicpay1 as nvarchar(50)
        set @Employeebasicpay1= (select (N'???? ??????'))
        declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	set @sqlCommon=''
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlCommon = @sqlCommon + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		if not(@fromDat='')		
		begin
		set @sqlCommon = @sqlCommon + ' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '		End
		if not (@ToDat='')
		begin
		set @sqlCommon = @sqlCommon + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
		end
		if not(@EmployeeName='')
		begin
			Declare @Tempname nvarchar(200)
         set @Tempname= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
	     set @sqlCommon = @sqlCommon + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')' 
		--	set @sqlCommon = @sqlCommon + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' +  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if not (@EmployeeId='')
		begin
			set @sqlCommon = @sqlCommon + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
		end
		If Not (@EmpSwipeCard = '')  
		Begin  
			  Set @sqlCommon = @sqlCommon + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
		if not (@EmployeeCategory=0)
		begin
			set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))
		end
		if(@DesignationID<>0)
		begin
			  set @sqlCommon = @sqlCommon + ' and TA_Tbl_EmployeeDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
	    if(@Gender<>'Both')
		begin
			  set @sqlCommon = @sqlCommon + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
--Select employee level
set @sqlQuery1 = ''
		set @sqlQuery1 = @sqlQuery1 + 'SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery1 = @sqlQuery1 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery1 = @sqlQuery1 + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_EmployeeLevel.EffectiveDate as EffectiveDate,  N''' + @EmployeeLevel1 + ''' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender '
		set @sqlQuery1 = @sqlQuery1 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery1 = @sqlQuery1 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery1 = @sqlQuery1 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery1 = @sqlQuery1 + @sqlCommon
		set @sqlQuery2 = ' Union '
		set @sqlQuery2 = @sqlQuery2 + 'SELECT    distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery2 = @sqlQuery2 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery2 = @sqlQuery2 + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as name,TA_Tbl_EmployeeDesignation.EffectiveDate as EffectiveDate,  N''' + @EmployeeDesignation1 + ''' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery2 = @sqlQuery2 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery2 = @sqlQuery2 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery2 = @sqlQuery2 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery2 = @sqlQuery2 + @sqlCommon
set @sqlQuery3 = ' Union '
		set @sqlQuery3 = @sqlQuery3 + 'SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery3 = @sqlQuery3 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery3 = @sqlQuery3 + ' dbo.TA_Tbl_Category.CategoryName AS name,TA_Tbl_EmployeeCategory.EffectiveDate as EffectiveDate,  N''' + @EmployeeCategory1 + ''' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery3 = @sqlQuery3 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery3 = @sqlQuery3 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery3 = @sqlQuery3 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery3 = @sqlQuery3 + @sqlCommon
set @sqlQuery4 = ' Union '
		set @sqlQuery4 = @sqlQuery4 + 'SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery4 = @sqlQuery4 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery4 = @sqlQuery4 + ' dbo.TA_Tbl_Type.TypeName AS name,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate,  N''' + @EmployeeType1 + ''' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '
		set @sqlQuery4 = @sqlQuery4 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery4 = @sqlQuery4 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery4 = @sqlQuery4 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery4 = @sqlQuery4 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
		set @sqlQuery4 = @sqlQuery4 + @sqlCommon
set @sqlQuery5 =  ' Union '
		set @sqlQuery5 = @sqlQuery5 + 'SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery5 = @sqlQuery5 + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname, '
		set @sqlQuery5 = @sqlQuery5 + ' cast(dbo.TA_Tbl_EmployeePay.BasicPay as nvarchar) AS name,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate,  N''' + @Employeebasicpay1 + ''' as HistoryType,replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender  '		
		set @sqlQuery5 = @sqlQuery5 + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery5 = @sqlQuery5 + ' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId'		
		set @sqlQuery5 = @sqlQuery5 + ' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery5 = @sqlQuery5 + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')'		
	    set @sqlQuery5 = @sqlQuery5 + @sqlCommon
		exec(@sqlQuery1 + @sqlQuery2 + @sqlQuery3 + @sqlQuery4 + @sqlQuery5)
		drop table #LevelRights
--exec(@sqlQuery1)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOut]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptEmployeeInOut '','2009/04/01','2012/04/30','',0,0,0,'SuperAdmin','0','1',0,0,'Both'
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOut]      
(
	@EmployeeID VarChar(50), 
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)      
AS      
BEGIN   
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--select * from #LevelRights
	--Employee Level Indexes
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,
		[Clk_CompId] varchar(10),
		[Clk_EmpId] nvarchar(20),
		[Clk_InDeviceId] nvarchar(20),
		[Clk_InDate] datetime,
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25),
		[Clk_OutDeviceId] nvarchar(20),
		[Clk_OutDate] datetime,
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25),
		[Clk_Process] nvarchar(1),
		[Clk_Remarks] nvarchar(100),
		[Clk_User] nvarchar(20),
		[Clk_Date] datetime,
		[Clk_Status] char(1),
		[IsVoid] bit
	)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId]  ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
	If Not (@EmpSwipeCard = '')  
			Begin  
				Set @sqlCommon = @sqlCommon + ' And SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			End
		if not(@EmployeeId='' or @EmployeeId='0')  
			begin  
				set @sqlCommon = @sqlCommon + ' and (Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
			end 
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	Execute(@sqlEmpLevel + @sqlCommon)
	--Employee Designation insert in Temporary table
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(100)) + ''')'
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
	Execute(@sqlEmpCategory)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	/****** Object:  Index [IDX_EmpSwipeCardNo]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmpSwipeCardNo] ON [dbo].[#TempEmployee] 
	(
		[EmpSwipeCardNo] ASC
	)ON [PRIMARY]
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	--select * from #TempEmployee
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @sqlCommonEmpId nvarchar(1000)
	set @sqlCommonEmpId=''
	If Not (@EmpSwipeCard = '')  
			Begin  
				Set @sqlCommonEmpId = @sqlCommonEmpId + ' And Clk_EmpId = ''' + @EmpSwipeCard + ''' '  
			End
	set @sqlTempProcessedData=	
	'insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails
	where ta_tbl_clockdetails.IsVoid=0 
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,'''+cast(@FromDate as nvarchar(11))+''', 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(11))+''', 102)'
	--select * from #TempClockDetails
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20),Shift_ID int,Date datetime)
	/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	)ON [PRIMARY]
	Declare @sqlCommonEmployee_Code_Id nvarchar(1000)
	set @sqlCommonEmployee_Code_Id=''
	If Not (@EmpSwipeCard = '')  
			Begin  
				Set @sqlCommonEmployee_Code_Id = @sqlCommonEmployee_Code_Id + ' and (TA_Tbl_ProcessedData.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'    
			End
	set @sqlTempProcessedData1=	
	'insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date 
	from TA_Tbl_ProcessedData inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,'''+cast( @FromDate as nvarchar(50))+''', 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102))'
	Execute(@sqlTempProcessedData +@sqlCommonEmpId)	
		Execute(@sqlTempProcessedData1+@sqlCommonEmployee_Code_Id)	 
--select * from #TempProcessedData
		 -- SET NOCOUNT ON added to prevent extra result sets from      
		 -- interfering with SELECT statements.      
		 Declare @SelectSQL As Varchar(8000)      
		 Set @EmployeeName = isnull(@EmployeeName,'') + '%'      
		 Set @SelectSQL = ' '        
		Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id, '      
		Set @SelectSQL = @SelectSQL + 'ltrim(ED.Employee_FirstName) + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
		Set @SelectSQL = @SelectSQL + ' case isnull(CD.Clk_InTime,'''') when '''' then ''Missing In'' else right(convert(varchar(20),CD.Clk_InTime,100),7) end as InTime ,'      
		Set @SelectSQL = @SelectSQL + ' case isnull(CD.Clk_OutTime,'''') when '''' then ''Missing Out'' else right(convert(varchar(20),CD.Clk_OutTime,100),7) end as OutTime,CONVERT(VARCHAR,CD.Clk_Date,101) as ClockDate,ED.Gender FROM TA_Tbl_Employee ED '      
		set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
   		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
		Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and ED.employee_status=1 and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) else '' '' end + isnull(ED.Employee_LastName,'''') like ''' + @EmployeeName + ''' '  
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
		-- If (@EmployeeId <> '' and @EmployeeId is not null)      
		-- Begin      
		--  Set @SelectSQL = @SelectSQL + 'And ED.employee_code_id = ''' + @EmployeeId + ''' '      
		-- End      
		--If (@EmpSwipeCard <> '' and @EmpSwipeCard is not null)  
		-- Begin  
		--  Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		-- End
		if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		if(@shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@shift  as nvarchar(20))   
		end 
		 If (@FromDate <> '')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + 'And CD.Clk_Date >= ''' + @FromDate + ''' '      
		 End      
		 If (@ToDate <> '')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + 'And CD.Clk_Date <= ''' + @ToDate + ''' '      
		 End      
		--if(@employeeCategory<>0)
		--begin
		--	set @SelectSQL = @SelectSQL + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar) 
		--end
		--if(@employeeType<>0)
		--begin
		--	set @SelectSQL = @SelectSQL + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar) 
		--end   
		--if(@DesignationID<>0)
		--begin
		--	  set @SelectSQL = @SelectSQL + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		--end	
		if(@Gender<>'Both')
		begin
			  set @SelectSQL = @SelectSQL + ' and ED.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end  
		Set @SelectSQL = @SelectSQL + ' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc'      
 	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay  
	drop table #LevelRights  
	drop table #TempEmployee  
	drop table #TempClockDetails    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author      : Sashma
-- Create date : <Create Date,,>
-- Description : <Description,,>
--	Modified by	:	A.K.T.MOORTHI
--	Modified On	:	18-Feb-2014
--	Descriptions	:	Add OD Notation when OnDuty occur
/*
[Proc_TA_RptEmployeeInOutDetails] '','','0','0','0','SuperAdmin','0','',0,'20180701','20180731',0,'Both',0
exec Proc_TA_RptEmployeeInOutDetails @EmployeeId='',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',@UserGroupName='SuperAdmin',@GradeLevel='0',@EmpSwipeCard='',@ParentId=0,@FromDate1='01/Jan/2019',@ToDate1='30/jan/2019',@DesignationID=0,@Gender='Both',@EmpAutoID=0


exec Proc_TA_RptEmployeeInOutDetails @EmployeeId='',@EmployeeName='',@LevelID='37',@employeeCategory=N'0',@employeeType=N'0',
@UserGroupName='SuperAdmin',@GradeLevel='0',@EmpSwipeCard='',@ParentId=37,@FromDate1='2024-03-01',@ToDate1='2024-03-01',
@DesignationID=0,@Gender='Both',@EmpAutoID=1

*/

CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails]


	@EmployeeId varchar(max)='',
	@EmployeeName varchar(max)='',  
	@LevelID varchar(1000)='37', 	 
	@employeeCategory nvarchar(50)='0',
	@employeeType nvarchar(50)='0'	,
	@UserGroupName varchar(250)='SuperAdmin',
	@GradeLevel varchar(20)='0'	,
	@EmpSwipeCard varchar(20)='',
	@ParentId int=37,
    @FromDate1 varchar(50)='2024-03-01',
    @ToDate1 varchar(50)='2024-03-01',
	@DesignationID int=0,
	@Gender varchar(10)='Both',
	@EmpAutoID int=1

AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeId varchar(max)
	DECLARE @local_EmployeeName varchar(max)
	DECLARE @local_LevelID varchar(1000)
	DECLARE @local_employeeCategory nvarchar(50)
	DECLARE @local_employeeType nvarchar(50)
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
    DECLARE @local_FromDate1 varchar(50)
    DECLARE @local_ToDate1 varchar(50)
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoID int
	
	set @local_EmployeeId=@EmployeeId
	set @local_EmployeeName=@EmployeeName
	set @local_LevelID=@LevelID
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
    set @local_FromDate1=@FromDate1
    set @local_ToDate1=@ToDate1
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoID=@EmpAutoID
		
	Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	set @Fromdate2 = @local_FromDate1
	set @Diff = datediff(d,@local_FromDate1,@local_ToDate1) + 1
	set @Count=1
	
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))	
	create table #EmployeeIds(EmpAutoId int)	
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,
		LevelId int,date datetime,
		Otmins numeric(18,1),
		TotalDays numeric(18, 1),
		Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,
		Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,
		Designation nvarchar(250) ,
		empname nvarchar(150) ,
		Father_Name nvarchar(50),
		EmpAadhar Nvarchar(12),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		isManualTimeEntryFH bit default 0 not null,
		isManualTimeEntrySH bit default 0 not null
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(150),
		FatherName nvarchar(150) ,
		Designation nvarchar(250) ,
		Employee_Code_Id nvarchar(15),
		EmpAadhar Nvarchar(12),
		Present numeric(18,1),
		Absent numeric(18,1),
		Leave numeric(18,1),
		Holiday numeric(18,1)default(0.0),
		TotalOT numeric(18,1),
		CountDays  numeric(18,1) default(0.0),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		F_Day1 nvarchar(100) DEFAULT '',
		F_Day2 nvarchar(100) DEFAULT '',
		F_Day3 nvarchar(100) DEFAULT '',
		F_Day4 nvarchar(100) DEFAULT '',
		F_Day5 nvarchar(100) DEFAULT '',
		F_Day6 nvarchar(100) DEFAULT '',
		F_Day7 nvarchar(100) DEFAULT '',
		F_Day8 nvarchar(100) DEFAULT '',
		F_Day9 nvarchar(100) DEFAULT '',
		F_Day10 nvarchar(100) DEFAULT '',
		F_Day11 nvarchar(100) DEFAULT '',
		F_Day12 nvarchar(100) DEFAULT '',
		F_Day13 nvarchar(100) DEFAULT '',
		F_Day14 nvarchar(100) DEFAULT '',
		F_Day15 nvarchar(100) DEFAULT '',
		F_Day16 nvarchar(100) DEFAULT '',
		F_Day17 nvarchar(100) DEFAULT '',
		F_Day18 nvarchar(100) DEFAULT '',
		F_Day19 nvarchar(100) DEFAULT '',
		F_Day20 nvarchar(100) DEFAULT '',
		F_Day21 nvarchar(100) DEFAULT '',
		F_Day22 nvarchar(100) DEFAULT '',
		F_Day23 nvarchar(100) DEFAULT '',
		F_Day24 nvarchar(100) DEFAULT '',
		F_Day25 nvarchar(100) DEFAULT '',
		F_Day26 nvarchar(100) DEFAULT '',
		F_Day27 nvarchar(100) DEFAULT '',
		F_Day28 nvarchar(100) DEFAULT '',
		F_Day29 nvarchar(100) DEFAULT '',
		F_Day30 nvarchar(100) DEFAULT '',
		F_Day31 nvarchar(100) DEFAULT ''
	)
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		OtMins float,
		TotalDays numeric(18, 1),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		earlyoutmins varchar(20),
		LateInmins varchar(20),
		HrsWork varchar(20),
		ShiftId int,
		Shift_FirstHalf_EndTime nvarchar(20),
		Shift_SecondHalf_StartTime nvarchar(20),
		BreakOutTime varchar(10),
		BreakInTime varchar(10)
	)	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	insert into #TempHeader(id) values(1)
	if(@isReportingto > 0)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	end
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId	
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@local_GradeLevel
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate1,@local_EmployeeId,@local_DesignationID	
	
	if(@local_employeeType > 0)
	BEGIN
		INSERT INTO #EmpType exec [Proc_TA_EmpType] @local_ToDate1,@local_EmployeeId,@local_employeeType
	END
	if(@local_employeeCategory > 0)
	BEGIN
		INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate1,@local_EmployeeId,@local_employeeCategory
	END
	
	if(@local_EmployeeId is not null and @local_EmployeeId <> '')
	begin
		create table #EmployeeID(EmployeeID varchar(25))
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@local_EmployeeId)
	end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
	begin
		create table #EmployeeName(EmployeeID varchar(25))
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
	end	
	Declare @sqlEmpLevel nvarchar(4000)		
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId '
	If Not (@local_EmployeeId = '')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id '
	End
	If Not (@local_EmployeeName = '')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id '
	End
	SET @sqlEmpLevel = @sqlEmpLevel + ' where emp.Isdeleted=0 '
	IF(@local_Gender<>'Both')
	BEGIN
		SET @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
	END	
	set @sqlEmpLevel=@sqlEmpLevel+' group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	execute(@sqlEmpLevel)	
	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1='insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee e
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id'	
	SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' where SwipeCardNo is not null and e.Isdeleted=0'			
	EXECUTE(@sqlTempProcessedData1)	
	
	--print @sqlTempProcessedData1

	SELECT SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee e
	inner join #TempEmployee on #TempEmployee.EmpAutoId=e.Employee_Id
	where inactivedate is not null and Employee_Status=0
	
	DECLARE @sqlTempProcessedData varchar(8000)
	SET @sqlTempProcessedData=		
	'insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''',''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,'''+cast(@local_FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102)'
	Execute(@sqlTempProcessedData)
	
	--Print @sqlTempProcessedData

	set @sqlTempProcessedData1=		
	'insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,PD.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''',''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on Convert(nvarchar(50),#TempEmployee.EmpSwipeCardNo)=Convert(nvarchar(50),PD.Employee_Code_Id )
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,'''+cast(@local_FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102)
	and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)'
	Execute(@sqlTempProcessedData1)

	--Print @sqlTempProcessedData1

	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()




	--update #TempProcessedData set BreakOutTime=mp.Clk_InTime,BreakInTime=mp.Clk_OutTime 
	--from #TempProcessedData TPD
	--inner join
	--(
	--select clk_empid,row=ROW_NUMBER()over(partition by clk_empid,clk_indate,clk_outdate order by clk_empid),
	--Clk_InDate,
	--case when RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7)<>'00:00' then
	--case	when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(25),DATEADD(minute,0,convert(datetime,Clk_InTime,0))),13,5)
	--else case	when len(ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,CHARINDEX(':',RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7)))))=1 then '0'+ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,6))+' '+substring(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),6,2)
	--			else SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,6)+' '+substring(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),6,2)
	--	 end
	--end
	--else '' 
	--end	Clk_InTime,
	--Clk_OutDate,
	--case when RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7)<>'00:00' then
	--case	when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(25),DATEADD(minute,0,convert(datetime,Clk_OutTime,0))),13,5)
	--else case	when len(ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,CHARINDEX(':',RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7)))))=1 then '0'+ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,6))+' '+substring(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),6,2)
	--			else SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,6)+' '+substring(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),6,2)
	--	 end
	--end
	--else '' 
	--end	Clk_OutTime,Clk_InPunchType,Clk_OutPunchType,Clk_Date from ta_tbl_matchedpunches 
	--where (Clk_InPunchType='Break out' or Clk_OutPunchType='Break in')
	--and(Clk_Date>=CONVERT(DATETIME,cast(@local_FromDate1 as nvarchar(50)), 102) and Clk_Date<=CONVERT(DATETIME,cast(@local_ToDate1 as nvarchar(50)), 102))
	--)as mp on ((TPD.Employee_Code_Id=mp.Clk_EmpId) and (mp.Clk_Date=TPD.Date))
	--inner join #TempEmployee te on te.EmpSwipeCardNo=mp.Clk_EmpId
	--where mp.row=1	
	Set @local_EmployeeName = isnull(@EmployeeName,'') + '%'
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery2=''
	set @sqlQuery1 =''
	set @sqlQuery ='Insert into #EmpInOutDetails 
					select	TA_Tbl_Employee.Employee_code_id,
							#EmpLevel.LevelId,
							#TempProcessedData.date, 
							#TempProcessedData.OtMins,
							#TempProcessedData.TotalDays,
							Attendance1 = case #TempProcessedData.Attendance 
												when ''Present'' then case	when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) then '' '' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + ''#''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
																			when (#TempProcessedData.LateInmins <> ''0'')	then '' '' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +''#'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
																			when (#TempProcessedData.earlyoutmins <> ''0'' )then '' '' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + ''#'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
																			else '' '' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + ''#'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) 
																	  end
												when ''Absent'' then ''A''
												when ''Holiday'' then case	when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**H'' else ''H'' end
												when ''RH'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**RH'' else  ''RH'' end
												when ''Comp Off'' then ''C''
												when ''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end
												Else ''L''
										  end,
							Attendance2 =cast(isnull('' '' +#TempProcessedData.InTime,'''')as nvarchar)  +  cast(isnull(''#'' + #TempProcessedData.OutTime,'''') as nvarchar),
							Attendance	=case	when (#TempProcessedData.InTime <> ''00:00'' or #TempProcessedData.outtime <> ''00:00'' ) then cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) +''#'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
												when  fnattendancecode=''Absent''  then ''A''
												when fnattendanceCode=''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end
												when fnattendanceCode=''Holiday'' and anattendanceCode<>''Holiday'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**H'' else ''H''	 end
												when fnattendanceCode=''Holiday'' and anattendanceCode=''Holiday''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**H'' else ''H''	 end
												when fnattendanceCode=''RH'' and anattendanceCode<>''RH'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**RH'' else ''RH''	 end
												when fnattendanceCode=''RH'' and anattendanceCode=''RH''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**RH'' else  ''RH''	 end
												when fnattendanceCode=''Comp Off''  then ''C''
												when fnattendanceCode is null  then ''-''
												else ''L''
										end
										--+''##''+cast(isnull(#TempProcessedData.BreakOutTime,'''')as nvarchar)  + ''#''+ cast(isnull(#TempProcessedData.BreakInTime,'''') as nvarchar)
										+''##''+ case when #TempProcessedData.HrsWork<>''00:00'' then cast(isnull(#TempProcessedData.HrsWork,'''') as nvarchar) else '''' end,
							#TempProcessedData.employee_code_id, 
							Replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,
							TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''') as empname,
							TA_tbl_Employee.CustomField1 as EmpAadhar, 
							ta_tbl_employee.Father_Name,
							TA_Tbl_Title.TitleId,
							TA_Tbl_Grade.Grade_Level,
							0,
							0,
							0 
							FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId
							Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id
							INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId
							INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
	if(@local_employeeCategory>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #EmpCategory TEC on TA_Tbl_Employee.Employee_Id = TEC .EmployeeId
										INNER JOIN TA_Tbl_Category c on TEC.CategoryId = c.CategoryId'
	END
	if(@local_employeeType>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #EmpType TET on TA_Tbl_Employee.Employee_Id = TET.EmployeeId
										INNER JOIN TA_Tbl_Type T on TET.TypeId = TA_Tbl_Type.TypeId'	
	END
	set @sqlQuery1 = @sqlQuery1 + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '	
	--set @sqlQuery1 = @sqlQuery1 + ' left outer join TA_Tbl_ManualTimeEntry mdIn on (mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	--								and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''Approved'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''Y'' and mdIn.IsOnDuty=''0''
	--								left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	--								and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	--								and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''Approved'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''Y'' and mdOut.IsOnDuty=''0'')' 
	set @sqlQuery1 = @sqlQuery1 + ' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )'  
	if(@local_UserGroupName<>'SuperAdmin')
	begin	
		SET @sqlQuery2 = @sqlQuery2 + '	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)'
	end	
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery2 = @sqlQuery2 + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	set @sqlQuery2 = @sqlQuery2 + ' order by #TempProcessedData.Employee_code_id'  
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2)
	
	--select * from #EmpInOutDetails
	--update Emp set Emp.isManualTimeEntryFH=  
	--case	when (P.FNAttendanceCode='Present' OR FNAttendanceCode='*Present' OR FNAttendanceCode='Holiday' OR FNAttendanceCode='*Holiday' OR FNAttendanceCode='Weekly Off' OR FNAttendanceCode='*Weekly Off') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
	--		else 0 
	--end,	
	--Emp.isManualTimeEntrySH= 
	--case	when (P.FNAttendanceCode='Present' OR FNAttendanceCode='*Present' OR FNAttendanceCode='Holiday' OR FNAttendanceCode='*Holiday' OR FNAttendanceCode='Weekly Off' OR FNAttendanceCode='*Weekly Off') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
	--		else 0 
	--end	from #EmpInOutDetails Emp	inner join Ta_Tbl_ManualTimeEntry M on M.ManualTimeEntry_Employee_Id=Emp.employee_code_id
	--inner join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	--and Emp.date=P.Date
	--and (cast(P.Date+CONVERT(datetime,P.InTime) as datetime)=cast(M.ManualTimeEntry_InDate+CONVERT(datetime,M.ManualTimeEntry_InTime) as datetime)
	--or cast( P.Date+convert(datetime,P.OutTime) as datetime)=cast(M.ManualTimeEntry_OutDate+CONVERT(datetime,M.ManualTimeEntry_OutTime) as datetime)))
	--where M.ManualTimeEntry_Status='Approved' and M.Isdeleted=0 
	--and isnull(M.IsOnDuty,0)=0
	
	UPDATE #EmpInOutDetails SET 
	Attendance1 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id, 'FN', PD.Shift_Id, Attendance1),
	Attendance2 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, Attendance2)
	FROM #EmpInOutDetails IOD INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	
	UPDATE #EmpInOutDetails SET Attendance = 
	(CASE WHEN Attendance1 = 'OD' AND Attendance2 = 'OD' THEN 'OD'
	WHEN Attendance1 = 'OD' THEN (CASE WHEN Attendance LIKE '%/%' THEN ('OD ' + SUBSTRING(Attendance, CHARINDEX('/', Attendance, 0), 10000)) WHEN Attendance LIKE '% %' THEN ('OD ' + SUBSTRING(Attendance, CHARINDEX(' ', Attendance, 0), 10000))  ELSE Attendance END)
	WHEN Attendance2 = 'OD' THEN (CASE WHEN Attendance LIKE '%/%' THEN (SUBSTRING(Attendance, 0, CHARINDEX('/', Attendance, 0)) + '/ OD ') WHEN Attendance LIKE '% %' THEN ((SUBSTRING(Attendance, 0, CHARINDEX(' ', Attendance, 0))) + ' OD')  ELSE Attendance END) ELSE Attendance END)
	FROM #EmpInOutDetails WHERE Attendance1 LIKE '%OD%' OR Attendance2 LIKE '%OD%'
	
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,EmpAadhar,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,EmpAadhar,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails	
	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@local_FromDate1
	while(@Count <=31)
	BEGIN
		SET @SQLTemp = @SQLTemp + ' update #TempHeader set Day'+cast(@Count as varchar(10)) + '=' + cast(datepart(d,@FromDate3)as varchar(10)) + 'where id=1'
		exec(@SQLTemp)
		set @SQLTemp=''
		if(@Count <=@Diff)
		BEGIN
			SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(20)) + ' = #EmpInOutDetails.Attendance '
			SET @SQLFN1 = @SQLFN1 + ' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	'
			SET @SQLFN1 = @SQLFN1 + ' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, ''' + @FromDate3 + ''' , 102) '
			EXEC(@SQLFN1)
			SET @SQLFN1=''									
			IF NOT EXISTS(SELECT DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
			BEGIN							
				SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
				EXEC(@SQLFN1)																			
			END
		END
		ELSE
		BEGIN
			SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
			EXEC(@SQLFN1)
		END
		SET @FromDate3=dateadd(d,1,@FromDate3)
		SET @Count=@Count +1
	END	 
	
	--Present
	--update #AllEmpInOutDetails set Present=a.total from #AllEmpInOutDetails
	--inner join
	--(
	--	select 	Employee_code_Id,sum(case when FNAttendanceCode='Present' then 0.5 else 0 end)+
	--							 sum(case when ANAttendanceCode='Present' then 0.5 else 0 end) as total 
	--	from #TempProcessedData group by Employee_code_Id
	--)as a on a.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----Absent
	--update #AllEmpInOutDetails set Absent=sum(case when FNAttendanceCode='Absent' then 0.5 else 0 end)+
	--									   sum(case when ANAttendanceCode='Absent' then 0.5 else 0 end)  from #TempProcessedData 
	--inner join #AllEmpInOutDetails 
	--on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----Ot Mins
	----update #AllEmpInOutDetails set TotalOT=sum(OtMins)from #TempProcessedData 
	----inner join #AllEmpInOutDetails on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----NFHolidays
	--update #AllEmpInOutDetails set Absent=sum(case when FNAttendanceCode='Holiday' then 0.5 else 0 end)+
	--									   sum(case when ANAttendanceCode='Holiday' then 0.5 else 0 end)  from #TempProcessedData 
	--inner join #AllEmpInOutDetails 
	--on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	--TotalWorkingDays
	--insert into #TotalWorkedDays select E.Employee_code_Id,
	--sum(case 
	--when FNAttendanceCode='Present' and ANAttendanceCode='Present' then 1   
	--when FNAttendanceCode='Present' and ANAttendanceCode='Absent' then 0.5 
	--when FNAttendanceCode='Absent' and ANAttendanceCode='Present' then 0.5                 
	--when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then 1
	--when FNAttendanceCode='RH' and ANAttendanceCode='RH' then 1
	--when FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' and (InTime<>'00:00' or OutTime<>'00:00') then  1                  
	--when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and  (OutTime is null or OutTime='') then 0.5
	--when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
	--when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
	--when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and (InTime is null or InTime='') then 0.5
	--when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
	--when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
	--when fnattendanceCode='Present' and anattendanceCode not in('Holiday','Absent','Present','Restricted Holiday','Weekly Off') then 0.5
	--when anattendanceCode='Present' and fnattendanceCode not in('Holiday','Absent','Present','Restricted Holiday','Weekly Off') then 0.5
	--else 0
	--end)
	--from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	--Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	--where (Date between @local_FromDate1 and @local_ToDate1) and ((InTime<>'00:00' or InTime is not null )
	--or (OutTime<>'00:00' or OutTime is not null) or fnattendanceCode in ('Tour','Training') or anattendanceCode in ('Tour','Training'))
	--group by E.Employee_code_Id
	--update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	
	--update #AllEmpInOutDetails set TotalOT='0' 
	
	select
	ROW_NUMBER()over(order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name) SlNo,
	Employee_Code_Id,
	Name,
	EmpAadhar,
	Designation, 
	F_Day1,
	F_Day2,
	F_Day3,
	F_Day4,
	F_Day5,
	F_Day6,
	F_Day7,
	F_Day8,
	F_Day9 ,
	F_Day10 ,
	F_Day11 ,
	F_Day12 ,
	F_Day13 ,
	F_Day14 ,
	F_Day15 ,
	F_Day16 ,
	F_Day17 ,
	F_Day18 ,
	F_Day19 ,
	F_Day20 ,
	F_Day21 ,
	F_Day22 ,
	F_Day23 ,
	F_Day24 ,
	F_Day25 ,
	F_Day26 ,
	F_Day27 ,
	F_Day28 ,
	F_Day29 ,
	F_Day30 ,
	F_Day31,	
	EF_Day1=Replace(F_Day1,'#',Space(2)),
	EF_Day2=Replace(F_Day2,'#',Space(2)),
	EF_Day3=Replace(F_Day3,'#',Space(2)),
	EF_Day4=Replace(F_Day4,'#',Space(2)),
	EF_Day5=Replace(F_Day5,'#',Space(2)),
	EF_Day6=Replace(F_Day6,'#',Space(2)),
	EF_Day7=Replace(F_Day7,'#',Space(2)),
	EF_Day8=Replace(F_Day8,'#',Space(2)),
	EF_Day9=Replace(F_Day9,'#',Space(2)),
	EF_Day10=Replace(F_Day10,'#',Space(2)),
	EF_Day11=Replace(F_Day11 ,'#',Space(2)),
	EF_Day12=Replace(F_Day12 ,'#',Space(2)),
	EF_Day13=Replace(F_Day13 ,'#',Space(2)),
	EF_Day14=Replace(F_Day14 ,'#',Space(2)),
	EF_Day15=Replace(F_Day15 ,'#',Space(2)),
	EF_Day16=Replace(F_Day16 ,'#',Space(2)),
	EF_Day17=Replace(F_Day17 ,'#',Space(2)),
	EF_Day18=Replace(F_Day18 ,'#',Space(2)),
	EF_Day19=Replace(F_Day19 ,'#',Space(2)),
	EF_Day20=Replace(F_Day20 ,'#',Space(2)),
	EF_Day21=Replace(F_Day21 ,'#',Space(2)),
	EF_Day22=Replace(F_Day22 ,'#',Space(2)),
	EF_Day23=Replace(F_Day23 ,'#',Space(2)),
	EF_Day24=Replace(F_Day24 ,'#',Space(2)),
	EF_Day25=Replace(F_Day25 ,'#',Space(2)),
	EF_Day2=Replace(F_Day26 ,'#',Space(2)),
	EF_Day27=Replace(F_Day27 ,'#',Space(2)),
	EF_Day28=Replace(F_Day28 ,'#',Space(2)),
	EF_Day29=Replace(F_Day29 ,'#',Space(2)),
	EF_Day30=Replace(F_Day30 ,'#',Space(2)),
	EF_Day31=Replace(F_Day31 ,'#',Space(2))	
	from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	select * from #TempHeader	
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee	
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author      : Sashma
-- Create date : <Create Date,,>
-- Description : <Description,,>
--	Modified by	:	A.K.T.MOORTHI
--	Modified On	:	18-Feb-2014
--	Descriptions	:	Add OD Notation when OnDuty occur
/*
Proc_TA_RptEmployeeInOutDetails '787','','0','0','0','SuperAdmin','0','',0,'2015-04-01','2015-04-30',0,'Both'
exec Proc_TA_RptEmployeeInOutDetails @EmployeeId='Emp1',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',@UserGroupName='SuperAdmin',@GradeLevel='0',@EmpSwipeCard='',@ParentId=0,@FromDate1='01/Jun/2013',@ToDate1='30/Jun/2013',@DesignationID=0,@Gender='Both'
*/
create PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix] 
	--@SelectedMonth nvarchar(20),  
	--@SelectedYear nvarchar(20),  
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),  
	@LevelID varchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
    @FromDate1 varchar(50),
    @ToDate1 varchar(50),
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
    Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	set @Fromdate2 = @Fromdate1
	set @Diff = datediff(d,@Fromdate1,@Todate1) + 1
	set @Count=1
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	insert into #TempHeader(id) values(1)
	SET NOCOUNT ON;
	--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,LevelId int,date datetime,
		Otmins numeric(18,1),TotalDays numeric(18, 1),Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,Designation nvarchar(250) ,
		empname nvarchar(50) ,Father_Name nvarchar(50),DesignationID int,Grade_Level int,OrderBy int
		,isManualTimeEntryFH bit default 0 not null,
	isManualTimeEntrySH bit default 0 not null
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50) ,FatherName nvarchar(50) ,Designation nvarchar(250) , Employee_Code_Id nvarchar(15) ,Present numeric(18,1),Absent numeric(18,1),Leave numeric(18,1),Holiday numeric(18,1)default(0.0),TotalOT numeric(18,1),CountDays  numeric(18,1) default(0.0),DesignationID int,Grade_Level int,OrderBy int,
		F_Day1 nvarchar(100) DEFAULT '',F_Day2 nvarchar(100) DEFAULT '',F_Day3 nvarchar(100) DEFAULT '',F_Day4 nvarchar(100) DEFAULT '',F_Day5 nvarchar(100) DEFAULT '',F_Day6 nvarchar(100) DEFAULT '',F_Day7 nvarchar(100) DEFAULT '',F_Day8 nvarchar(100) DEFAULT '',F_Day9 nvarchar(100) DEFAULT '',F_Day10 nvarchar(100) DEFAULT '',F_Day11 nvarchar(100) DEFAULT '',F_Day12 nvarchar(100) DEFAULT '',F_Day13 nvarchar(100) DEFAULT '',F_Day14 nvarchar(100) DEFAULT '',F_Day15 nvarchar(100) DEFAULT '',F_Day16 nvarchar(100) DEFAULT '',F_Day17 nvarchar(100) DEFAULT '',F_Day18 nvarchar(100) DEFAULT '',F_Day19 nvarchar(100) DEFAULT '',F_Day20 nvarchar(100) DEFAULT '',F_Day21 nvarchar(100) DEFAULT '',F_Day22 nvarchar(100) DEFAULT '',F_Day23 nvarchar(100) DEFAULT '',F_Day24 nvarchar(100) DEFAULT '',F_Day25 nvarchar(100) DEFAULT '',F_Day26 nvarchar(100) DEFAULT '',F_Day27 nvarchar(100) DEFAULT '',F_Day28 nvarchar(100) DEFAULT '',F_Day29 nvarchar(100) DEFAULT '',F_Day30 nvarchar(100) DEFAULT '',F_Day31 nvarchar(100) DEFAULT ''
	)
	create table #LeaveCount(Employee_code_Id nvarchar(15) ,LeaveCount numeric(18,1))
	create table #OTMins(Employee_code_Id nvarchar(15) ,OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15) ,NFHolidays numeric(18,1))
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15) ,Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15) ,FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15) ,FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15) ,FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(
	EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),OtMins float,TotalDays numeric(18, 1),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20)
		,earlyoutmins varchar(20),LateInmins varchar(20),HrsWork varchar(20),ShiftId int,Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20)
		 ) 
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
	(
	[Grade_Id] ASC
	) ON [PRIMARY]
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
--Employee Level insert in Temporary table
insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate1,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate1,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate1,@EmployeeId,@employeeCategory	
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
Declare @sqlEmpLevel nvarchar(4000)		
set @sqlEmpLevel=
'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate1 as nvarchar(50))+''', 102) and EL.LevelId is not null'	
If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
execute(@sqlEmpLevel)	
Declare @sqlTempProcess varchar(8000)
Declare @sqlTempProcess1 varchar(8000)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=	
	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id'
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End	
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'		
	execute(@sqlTempProcessedData1)	
   select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0
Declare @sqlTempProcessedData varchar(8000)
set @sqlTempProcessedData=		
	'insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,'''+cast(@FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@ToDate1 as nvarchar(50))+''', 102)'
Execute(@sqlTempProcessedData)	
set @sqlTempProcessedData1=		
	'insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,PD.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime 
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,'''+cast(@FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@ToDate1 as nvarchar(50))+''', 102)
		and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)'
	Execute(@sqlTempProcessedData1)
	Set @EmployeeName = isnull(@EmployeeName,'') + '%'
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
    set @sqlQuery=''
	set @sqlQuery2=''
	set @sqlQuery1 =''
	set @sqlQuery ='Insert into #EmpInOutDetails select TA_Tbl_Employee.Employee_code_id,#EmpLevel.LevelId,'  	
	set @sqlQuery = @sqlQuery + ' #TempProcessedData.date, #TempProcessedData.OtMins, #TempProcessedData.TotalDays,'
	set @sqlQuery = @sqlQuery + ' Attendance1 = case #TempProcessedData.Attendance '
	set @sqlQuery = @sqlQuery + ' when ''Present'' then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*~''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''0'') then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' O~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  else 
	  '' i~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) end'
	set @sqlQuery = @sqlQuery + ' when ''Absent'' then ''A'' '	
	set @sqlQuery = @sqlQuery + ' when ''Holiday'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**H'' else ''H'' end'
	set @sqlQuery = @sqlQuery + ' when ''RH'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**RH'' else  ''RH'' end'
	set @sqlQuery = @sqlQuery + ' when ''Comp Off'' then ''C'' '
	set @sqlQuery = @sqlQuery + ' when ''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end '
	set @sqlQuery = @sqlQuery + ' Else ''L'' '
	set @sqlQuery = @sqlQuery + ' end '
	set @sqlQuery = @sqlQuery + ' ,Attendance2 = cast(isnull('' i~'' +#TempProcessedData.InTime,'''')as nvarchar)  +  cast(isnull('' o~'' + #TempProcessedData.OutTime,'''') as nvarchar)'
	set @sqlQuery = @sqlQuery + ' ,Attendance = case  when fnattendanceCode=''Present'' then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' o*~''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
    					  when (#TempProcessedData.LateInmins <> ''0'') then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' o~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
						  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' o*~''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
						  else '' i~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' o~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) end'
	set @sqlQuery = @sqlQuery + ' when  fnattendancecode=''Absent''  then ''A'' '	
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end'		
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Holiday'' and anattendanceCode<>''Holiday'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**H'' else ''H''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Holiday'' and anattendanceCode=''Holiday''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**H'' else ''H''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''RH'' and anattendanceCode<>''RH'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**RH'' else ''RH''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''RH'' and anattendanceCode=''RH''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**RH'' else  ''RH''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Comp Off''  then ''C'' '
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode is null  then ''-''	'
	set @sqlQuery = @sqlQuery + ' else ''L'' '
	set @sqlQuery = @sqlQuery + ' end + '''' + isnull( '
	set @sqlQuery = @sqlQuery + 'case  '
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=anattendanceCode then null'
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' )then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''0'') then '' i*~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' O~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i~'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*~'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  else  '' /'' +   cast(isnull('' i~'' +#TempProcessedData.InTime,'''')as nvarchar)  +  cast(isnull('' O~'' + #TempProcessedData.OutTime,'''') as nvarchar)end'
	set @sqlQuery = @sqlQuery + ' when  anattendancecode=''Absent''  then ''/A'' '
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Weekly Off''  then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'')then ''**Off'' else ''/Off'' end'
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Holiday'' then  case when (OutTime is not null and OutTime<>''00:00'' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''**H'' else ''/H''	 end'	  	
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''RH'' then  case when (OutTime is not null and OutTime<>''00:00'' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''**RH'' else ''/RH''	 end'	  	
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Comp Off''  then ''/C'' '
	set @sqlQuery = @sqlQuery + ' when anattendanceCode is null  then ''-'' '
	set @sqlQuery = @sqlQuery + ' else ''/L''	'
	set @sqlQuery = @sqlQuery + ' end ,'''')'
	set @sqlQuery = @sqlQuery + '  ,#TempProcessedData.employee_code_id, Replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''') as empname, ta_tbl_employee.Father_Name '   
	set @sqlQuery = @sqlQuery + ' ,TA_Tbl_Title.TitleId,TA_Tbl_Grade.Grade_Level,0,0,0 FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId '  			
	set @sqlQuery1 = @sqlQuery1 + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	Set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id '    
	Set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id '
	Set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId ' 
	SET @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'  
	set @sqlQuery1 = @sqlQuery1 + ' inner join #EmpCategory on TA_Tbl_Employee.Employee_Id = #EmpCategory.EmployeeId'  	
	set @sqlQuery1 = @sqlQuery1 + ' inner join #EmpType on TA_Tbl_Employee.Employee_Id = #EmpType.EmployeeId'  	
	set @sqlQuery1 = @sqlQuery1 + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '	
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId'
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId'	
	 set @sqlQuery1 = @sqlQuery1 + ' left outer join TA_Tbl_ManualTimeEntry mdIn on mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date
	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''Approved'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''Y'' and mdIn.IsOnDuty=''0''
	left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''Approved'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''Y'' and mdOut.IsOnDuty=''0'' ' 
	set @sqlQuery1 = @sqlQuery1 + ' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )'  
	if(@UserGroupName<>'SuperAdmin')
		begin	
			SET @sqlQuery2 = @sqlQuery2 + '	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)'
		end
	if(@Gender<>'Both')
		begin
			set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery2 = @sqlQuery2 + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	set @sqlQuery2 = @sqlQuery2 + ' order by #TempProcessedData.Employee_code_id'  
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2)
	update Emp set Emp.isManualTimeEntryFH=  
	case when (P.FNAttendanceCode='Present' OR FNAttendanceCode='*Present' OR FNAttendanceCode='Holiday' OR FNAttendanceCode='*Holiday' OR FNAttendanceCode='Weekly Off' OR FNAttendanceCode='*Weekly Off') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
		 else 0 
	end ,	
	Emp.isManualTimeEntrySH= 
	case when (P.FNAttendanceCode='Present' OR FNAttendanceCode='*Present' OR FNAttendanceCode='Holiday' OR FNAttendanceCode='*Holiday' OR FNAttendanceCode='Weekly Off' OR FNAttendanceCode='*Weekly Off') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
		 else 0 end
	from #EmpInOutDetails Emp	
	inner join Ta_Tbl_ManualTimeEntry M on M.ManualTimeEntry_Employee_Id=Emp.employee_code_id
	inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	and Emp.date=P.Date
	and (cast(P.Date+CONVERT(datetime,P.InTime) as datetime)=cast(M.ManualTimeEntry_InDate+CONVERT(datetime,M.ManualTimeEntry_InTime) as datetime)
	or cast( P.Date+convert(datetime,P.OutTime) as datetime)=cast(M.ManualTimeEntry_OutDate+CONVERT(datetime,M.ManualTimeEntry_OutTime) as datetime))
	where M.ManualTimeEntry_Status='Approved' and M.Isdeleted=0 
	and isnull(M.IsOnDuty,0)=0
	--Update OnDuty Entry As 'OD' <-- Start By A.K.T.MOORTHI (18-Feb-2014)
	UPDATE #EmpInOutDetails SET 
		Attendance1 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id, 'FN', PD.Shift_Id, Attendance1),
		Attendance2 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, Attendance2)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	UPDATE #EmpInOutDetails SET Attendance = 
		(CASE WHEN Attendance1 = 'OD' AND Attendance2 = 'OD' THEN 'OD'
				WHEN Attendance1 = 'OD' THEN (CASE WHEN Attendance LIKE '%/%' THEN ('OD ' + SUBSTRING(Attendance, CHARINDEX('/', Attendance, 0), 10000)) WHEN Attendance LIKE '% %' THEN ('OD ' + SUBSTRING(Attendance, CHARINDEX(' ', Attendance, 0), 10000))  ELSE Attendance END)
		WHEN Attendance2 = 'OD' THEN (CASE WHEN Attendance LIKE '%/%' THEN (SUBSTRING(Attendance, 0, CHARINDEX('/', Attendance, 0)) + '/ OD ') WHEN Attendance LIKE '% %' THEN ((SUBSTRING(Attendance, 0, CHARINDEX(' ', Attendance, 0))) + ' OD')  ELSE Attendance END) ELSE Attendance END)
	FROM #EmpInOutDetails WHERE Attendance1 LIKE '%OD%' OR Attendance2 LIKE '%OD%'
	--End BY A.K.T.MOORTHI(18-Feb-2014)-->
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
		set @SQLTemp = @SQLTemp + ' update #TempHeader set Day'+cast(@Count as varchar(10)) + '=' + cast(datepart(d,@FromDate3)as varchar(10)) + 'where id=1'
		exec(@SQLTemp)
		set @SQLTemp=''
			if(@Count <=@Diff)
				begin
					set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(20)) + ' = #EmpInOutDetails.Attendance '
					set @SQLFN1 = @SQLFN1 + ' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	'
					set @SQLFN1 = @SQLFN1 + ' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, ''' + @FromDate3 + ''' , 102) '
					exec(@SQLFN1)
					set @SQLFN1=''									
					if not exists(select DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
						begin							
							set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
							exec(@SQLFN1)																			
						end
				end
			else
				begin
					set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
					exec(@SQLFN1)
				end
			set @FromDate3=dateadd(d,1,@FromDate3)
			set @Count=@Count +1
		end	 
	 --Leave Count
    DECLARE @LeaveCount AS NUMERIC(8,1)
	insert into #LeaveCount select e.employee_code_id,ISNULL(sum(NumberOfDays),0) as LeaveCount from ta_tbl_leaveapplication la 
	inner join ta_tbl_employee e on e.Employee_Id = la.Employee_Id
	where ((la.Leave_FromDate between @FromDate1 and @Todate1) and (la.Leave_ToDate between @FromDate1 and @Todate1))
	and la.Status = 'Approved' 
	group by e.employee_code_id
	--Present
	insert into #Present (Employee_code_Id,FNPresent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='Present' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Present set ANPresent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='Present' and (Date between @FromDate1 and @Todate1)
	and  #Present.Employee_code_Id=E.Employee_code_Id)
	update #Present set Present=FNPresent+ANPresent
	update #AllEmpInOutDetails set Present= case #Present.Present when null then '0.0' else #Present.Present end from #Present 
	inner join #AllEmpInOutDetails 
	on #Present.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Absent
	insert into #Absent (Employee_code_Id,FNAbsent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='Absent' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Absent set ANAbsent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='Absent' and 
	(Date >= @FromDate1 and date >= @Todate1)
	and  #Absent.Employee_code_Id=E.Employee_code_Id)
	update #Absent set Absent=FNAbsent+ANAbsent
	update #AllEmpInOutDetails set Absent=#Absent.Absent from #Absent 
	inner join #AllEmpInOutDetails 
	on #Absent.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id 
	--BonusLeave
	insert into #BonusLeave (Employee_code_Id,FNBL)select E.Employee_code_Id,count(*)/2.0 
	from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='BL' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #BonusLeave set ANBL=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='BL' and
	(Date between @FromDate1 and @Todate1)
	and  #BonusLeave.Employee_code_Id=E.Employee_code_Id)
	update #BonusLeave set BL=FNBL+ANBL
	--Leave
	update #AllEmpInOutDetails set Leave=(#LeaveCount.LeaveCount+#BonusLeave.BL) from #LeaveCount
	inner join #BonusLeave on #BonusLeave.Employee_code_Id=#LeaveCount.Employee_Code_Id
	inner join #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Ot Mins
	insert into #OTMins select E.Employee_code_Id,sum(OtMins) as OTMins from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_id
	update #AllEmpInOutDetails set TotalOT = #OTMins.OtMins from #OTMins inner join #AllEmpInOutDetails on #OTMins.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
   --NFHolidays
	insert into #Holiday select E.Employee_code_Id,count(*) from #TempProcessedData C 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	where (fnattendanceCode in ('Holiday') and anattendanceCode in('Holiday')) and (Date between @FromDate1 and @Todate1) 
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set Holiday = #Holiday.NFHolidays from #Holiday 
	inner join #AllEmpInOutDetails on #Holiday.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	--TotalWorkingDays
	insert into #TotalWorkedDays select E.Employee_code_Id,
	sum(case 
				  when FNAttendanceCode='Present' and ANAttendanceCode='Present' then 1   
				  when FNAttendanceCode='Present' and ANAttendanceCode='Absent' then 0.5 
				  when FNAttendanceCode='Absent' and ANAttendanceCode='Present' then 0.5                 
                  when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then 1
                  when FNAttendanceCode='RH' and ANAttendanceCode='RH' then 1
                  when FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' and (InTime<>'00:00' or OutTime<>'00:00') then  1                  
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and  (OutTime is null or OutTime='') then 0.5
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
                   when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and (InTime is null or InTime='') then 0.5
                  when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
                  when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
                  when fnattendanceCode='Present' and anattendanceCode not in('Holiday','Absent','Present','Restricted Holiday','Weekly Off') then 0.5
                  when anattendanceCode='Present' and fnattendanceCode not in('Holiday','Absent','Present','Restricted Holiday','Weekly Off') then 0.5
          end)
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	where (Date between @FromDate1 and @Todate1) and ((InTime<>'00:00' or InTime is not null )
	or (OutTime<>'00:00' or OutTime is not null) or fnattendanceCode in ('Tour','Training') or anattendanceCode in ('Tour','Training'))
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	update #AllEmpInOutDetails set TotalOT='0' 
	select * from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	select * from #TempHeader	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_processeddata where employee_code_id='222' and date between '05-01-2012' and '06-30-2012' and (fnattendancecode='CL' 
--or ANAttendanceCode='CL')
-- =============================================
-- Author:		Sashma
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modifyied By :	Manjula.P
-- Date			:	09-JUL-2013
-- Description	:	for adding # for indicating manual time entry
-- Modified By	:	Manjula.P
-- Date			:	23-Nov-2013
-- Descriptions	:	Changing CO into C notation for compoff  "C" for Splitting IN and OUT with "O" symbol in formula field. Then also "C" only in Muster roll summary report but not in  Muster roll details 
-- =============================================
--select * from ta_tbl_leavetype
--	Proc_TA_RptEmployeeInOutDetails_Detailed '','','3','0','0','SuperAdmin','0','',3,'','Both','2013/01/01','2013/01/30'
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed] 
	 @EmployeeId varchar(50),
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000), 	 
	 @employeeCategory nvarchar(50),
	 @employeeType nvarchar(50)	,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20)	,
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @FromDate1 varchar(50),
	 @ToDate1 varchar(50)	
AS
BEGIN
	Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	Declare @SQLDays nvarchar(2000)
	Declare @SQLFN nvarchar(2000)
	Declare @SQLAN nvarchar(2000)
	Declare @SQL3 varchar(2000)
	Declare @SQL1 varchar(2000)
	set @Fromdate2 = @Fromdate1
	set @Diff = datediff(d,@Fromdate1,@Todate1) + 1
	set @Count=1
	set @SQLDays=''	
	set @SQLAN=''
	set @SQLFN =''
	set @SQLFN = 'F_Day' + cast(@Count as varchar(10)) + ' nvarchar(100) DEFAULT '''''
	set @SQLDays= @SQLDays + 'Day' + cast(@Count as varchar(10)) + ' int'
	set @Count=@Count +1
	set @SQL3=''
	create table #TempHeader(id int)
	while(@Count <=31)
		begin
			set @SQLFN  = @SQLFN + ',F_Day'+ cast(@Count as nvarchar(10)) + ' nvarchar(100) DEFAULT '''''
			set @SQLDays = @SQLDays + ',Day' + cast(@Count as varchar(10)) + ' int'
			set @Fromdate2=dateadd(d,1,@Fromdate2)
			set @Count=@Count +1
		end	
	set @SQL3 = @SQL3 + 'alter table #TempHeader add '
	set @SQL3 = @SQL3 + @SQLDays 
	exec(@SQL3)
	Create table #tempClockData(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData1(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData2(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData3(Employee_Code_id varchar(50),Date datetime)
	insert into #tempClockData 	select Clk_EmpId,min(Clk_Date) from TA_Tbl_ClockDetails c Right Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=c.Clk_EmpId 
	where (c.Clk_InTime is not null or c.Clk_OutTime is not null) group by Clk_EmpId 
	insert into #tempClockData1	select Employee_Code_Id,MIN(date) from TA_Tbl_ProcessedData 
	where (ANAttendanceCode not in('Absent','Holiday','RH','Weekly Off') or FNAttendanceCode not in('Absent','Holiday','RH','Weekly Off')) 
	or(InTime is not null or OutTime is not null) group by Employee_Code_Id 	 		
	insert into #tempClockData2 	
	select T1.Employee_Code_id,case when T1.Date<T.Date then T1.Date else T.Date end from #tempClockData T inner join #tempClockData1 T1 
	on T.Employee_Code_id=T1.Employee_Code_id group by T1.Employee_Code_id,T1.Date,T.Date
	insert into #tempClockData2
	select Employee_Code_id,DATE from #tempClockData1 where Employee_Code_id not in(select Employee_Code_id from #tempClockData)	
	insert into #tempClockData3	select SwipeCardNo,'' from ta_tbl_employee E 
	where SwipeCardNo not in(select distinct Employee_Code_Id from #tempClockData2)	
	insert into #TempHeader(id) values(1)
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,LevelId int,date datetime,
		Otmins numeric(18,1),TotalDays numeric(18, 1),Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,Designation nvarchar(250) ,
		empname nvarchar(50) ,Father_Name nvarchar(50),DesignationID int,Grade_Level int
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50) ,FatherName nvarchar(50) ,Designation nvarchar(250) , 
		Employee_Code_Id nvarchar(15) ,Present numeric(18,1),Absent numeric(18,1),
		Leave numeric(18,1),
		Holiday numeric(18,1)default(0.0),
		TotalOT numeric(18,1),
		CountDays  numeric(18,1) default(0.0),DesignationID int,Grade_Level int
	)
	set @SQL1=''
	set @SQL1 = @SQL1 + 'alter table #AllEmpInOutDetails add '
	set @SQL1 = @SQL1 + @SQLFN 	
	exec(@SQL1)
	--select * from #AllEmpInOutDetails
	create table #LeaveCount(Employee_code_Id nvarchar(15) ,LeaveCount numeric(18,1))
	create table #OTMins(Employee_code_Id nvarchar(15) ,OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15) ,NFHolidays numeric(18,1))
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15) ,Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15) ,FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15) ,FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15) ,FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),OtMins float,TotalDays numeric(18, 1),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20)
	,earlyoutmins varchar(20),LateInmins varchar(20),HrsWork varchar(20),ShiftId int,Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20) ) 
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
	(
	[Grade_Id] ASC
	) ON [PRIMARY]
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102) and EL.LevelId is not null
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(cast(9+1 as nvarchar(20)) + '/' + '01/' + cast(2009 as nvarchar(20)) as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime 
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,cast(@FromDate1 as nvarchar(50)), 102) and Date <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)
	update #TempProcessedData set anattendanceCode='',fnattendanceCode='' from #TempProcessedData TP
	inner join #tempClockData2 TC on TP.Employee_Code_Id=TC.Employee_Code_id where TP.Date<TC.Date	
	update #TempProcessedData set anattendanceCode='',fnattendanceCode='' from #TempProcessedData TP
	where Employee_Code_Id in(select Employee_Code_Id from #tempClockData3 TC)
	Set @EmployeeName = isnull(@EmployeeName,'') + '%'
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery2=''
	set @sqlQuery ='Insert into #EmpInOutDetails select TA_Tbl_Employee.Employee_code_id,#EmpLevel.LevelId,'  	
	set @sqlQuery = @sqlQuery + ' #TempProcessedData.date, #TempProcessedData.OtMins, #TempProcessedData.TotalDays,'
	set @sqlQuery = @sqlQuery + ' Attendance1 = case #TempProcessedData.Attendance '
	set @sqlQuery = @sqlQuery + ' when ''Present'' then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) end'
	set @sqlQuery = @sqlQuery + ' when ''Absent'' then ''A'' '	
	set @sqlQuery = @sqlQuery + ' when ''Holiday'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**H'' else ''H'' end'
	set @sqlQuery = @sqlQuery + ' when ''RH'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**RH'' else  ''RH'' end'	
	set @sqlQuery = @sqlQuery + ' when ''Comp Off'' then ''C'' '
	set @sqlQuery = @sqlQuery + ' when ''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end '
	set @sqlQuery = @sqlQuery + ' when ''CL'' then ''<b>L</b>'' '
	set @sqlQuery = @sqlQuery + ' end '
	set @sqlQuery = @sqlQuery + ' ,Attendance2 = cast(isnull('' i:'' +#TempProcessedData.InTime,'''')as nvarchar)  +  cast(isnull('' O:'' + #TempProcessedData.OutTime,'''') as nvarchar)'
	set @sqlQuery = @sqlQuery + ' ,Attendance = case  when fnattendanceCode=''Present'' and isnull(mdIn.ManualTimeEntry_Id,0)=0 then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
    					  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
						  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
						  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) end'
--for adding manual time entry intime and outtime for fore noon by manjula.P on 27-Jun-2013
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Present'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''')<>''''  and isnull(#TempProcessedData.InTime,'''')!='''' and  
	isnull(#TempProcessedData.OutTime,'''')<>''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' #'' + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #'' 
		 end '
   set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Present'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')<>'''' and  
	isnull(#TempProcessedData.OutTime,'''')=''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' #'' + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
		 end '
  set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Present'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')='''' and  
	isnull(#TempProcessedData.OutTime,'''')<>''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #'' 
		 end '
   set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Present'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')='''' and  
	isnull(#TempProcessedData.OutTime,'''')=''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) 
		 end '
	-------------------------------------------------------------------------------------------			
	set @sqlQuery = @sqlQuery + ' when  fnattendancecode=''Absent''  then ''A'' '	
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Weekly Off'' then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'') then ''**Off'' else ''Off'' end'		
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Holiday'' and anattendanceCode<>''Holiday'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**H'' else ''H''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Holiday'' and anattendanceCode=''Holiday''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**H'' else ''H''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''RH'' and anattendanceCode<>''RH'' then  case when (InTime is not null and InTime<> ''00:00'' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''**RH'' else ''RH''	 end'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''RH'' and anattendanceCode=''RH''  then  case when (InTime<> ''00:00'' Or Outtime<>''00:00'') then ''**RH'' else  ''RH''	 end'	
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''Comp Off''  then ''C'' '	
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode is null  then ''''	'
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=''CL'' then ''<b>L</b>'' '
	set @sqlQuery = @sqlQuery + ' end + '''' + isnull( '
	set @sqlQuery = @sqlQuery + 'case  '
	set @sqlQuery = @sqlQuery + ' when fnattendanceCode=anattendanceCode then null'
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' and isnull(mdOut.ManualTimeEntry_Id,0)=0  then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' )then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)  + '' O*:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
	  else  '' /'' +   cast(isnull('' i:'' +#TempProcessedData.InTime,'''')as nvarchar)  +  cast(isnull('' O:'' + #TempProcessedData.OutTime,'''') as nvarchar)end'
	  --for adding manual time entry intime and outtime for fore noon by manjula.P on 27-Jun-2013
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')!='''' and  
	isnull(#TempProcessedData.OutTime,'''')<>''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' #'' + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #'' 
		 end '
   set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')<>'''' and  
	isnull(#TempProcessedData.OutTime,'''')=''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  +'' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' #''  + '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' #'' + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
		 end '
  set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')='''' and  
	isnull(#TempProcessedData.OutTime,'''')<>''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #''
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)+ '' #'' 
		 end '
   set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Present'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''')<>'''' and isnull(#TempProcessedData.InTime,'''')='''' and  
	isnull(#TempProcessedData.OutTime,'''')=''''
	then case when (#TempProcessedData.earlyoutmins <> ''0'' and #TempProcessedData.LateInmins <> ''0'' ) 
					then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''0'') then '' i*:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''0'' ) then '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar)+ '' O*:''+ cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar)
			  else '' i:'' +cast(isnull(#TempProcessedData.InTime,'''')as nvarchar) + '' O:'' + cast(isnull(#TempProcessedData.OutTime,'''') as nvarchar) 
		 end '
	--------------------------------------------------------------------------------------------
	set @sqlQuery = @sqlQuery + ' when  anattendancecode=''Absent''  then ''/A'' '
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Weekly Off''  then case when (InTime is not null and InTime<> ''00:00'') or (OutTime is not null and OutTime<>''00:00'')then ''**Off'' else ''/Off'' end'
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Holiday'' then  case when (OutTime is not null and OutTime<>''00:00'' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''**H'' else ''/H''	 end'	  	
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''RH'' then  case when (OutTime is not null and OutTime<>''00:00'' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''**RH'' else ''/RH''	 end'
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''Comp Off''  then ''/C'' '
	set @sqlQuery = @sqlQuery + ' when anattendanceCode is null  then '''' '
	set @sqlQuery = @sqlQuery + ' when anattendanceCode=''CL'' then ''/<b>L</b>'''
	set @sqlQuery = @sqlQuery + ' end ,'''')'
	set @sqlQuery = @sqlQuery + '  ,#TempProcessedData.employee_code_id, Replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''') as empname, ta_tbl_employee.Father_Name '   
	set @sqlQuery = @sqlQuery + ' ,TA_Tbl_Title.TitleId,TA_Tbl_Grade.Grade_Level FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId '  	
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sqlQuery  = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'	
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	--*********By Manjula.P on 09-Jul-2013 for joining Manual time entry notation.
    set @sqlQuery = @sqlQuery + ' left outer join TA_Tbl_ManualTimeEntry mdIn on mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date
	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''Approved'' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''Y'' and mdIn.IsOnDuty=''0''
	left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''Approved'' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''Y''  and mdOut.IsOnDuty=''0''  ' 
	--****************************************************************************.
	set @sqlQuery = @sqlQuery + ' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )'  	
	if(@UserGroupName<>'SuperAdmin')
		begin	
			SET @sqlQuery2 = @sqlQuery2 + '	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)'
		end
	if (@EmployeeName<>'')  
		begin  	
			set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_Employee.Employee_FirstName + case when TA_Tbl_Employee.Employee_MiddleName is not null then '' '' + cast(TA_Tbl_Employee.Employee_MiddleName as varchar(50)) else '' '' end + isnull(TA_Tbl_Employee.Employee_LastName,'''') like ''' + @EmployeeName + ''' '
		end  
	If (@EmpSwipeCard <> '')  
		Begin  
			Set @sqlQuery2 = @sqlQuery2 + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
	if (@EmployeeId<>'')  
		begin  
			set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '  
		end
	if(@employeeCategory<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
		end	
	if(@DesignationID<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))	
		end	
	if(@Gender<>'Both')
		begin
			set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	set @sqlQuery2 = @sqlQuery2 + ' order by #TempProcessedData.Employee_code_id'  
	Exec(@sqlQuery+@sqlQuery2) 
	--select * from #EmpInOutDetails 
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level from #EmpInOutDetails	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
			if(@Count <=@Diff)
				begin
					set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(20)) + ' = #EmpInOutDetails.Attendance '
					set @SQLFN1 = @SQLFN1 + ' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	'
					set @SQLFN1 = @SQLFN1 + ' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, ''' + @FromDate3 + ''' , 102) '
					exec(@SQLFN1)
					set @SQLFN1=''									
					if not exists(select DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
						begin							
							set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
							exec(@SQLFN1)																			
						end
				end
			else
				begin
					set @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
					exec(@SQLFN1)
				end
			set @FromDate3=dateadd(d,1,@FromDate3)
			set @Count=@Count +1
		end	 
	set @Count=1
	set @FromDate3=@Fromdate1
	while(@Count <=31)
	begin
		set @SQLTemp = @SQLTemp + ' update #TempHeader set Day'+cast(@Count as varchar(10)) + '=' + cast(datepart(d,@FromDate3)as varchar(10)) + 'where id=1'
		exec(@SQLTemp)
		set @SQLTemp=''	
		set @FromDate3=dateadd(d,1,@FromDate3)
		set @Count=@Count +1
	end
	 --Leave Count
    DECLARE @LeaveCount AS NUMERIC(8,1)
	insert into #LeaveCount 
	select e.employee_code_id,ISNULL(sum(NumberOfDays),0) as LeaveCount from ta_tbl_leaveapplication la 
	inner join ta_tbl_employee e on e.Employee_Id = la.Employee_Id
	where ((la.Leave_FromDate between @FromDate1 and @Todate1) and (la.Leave_ToDate between @FromDate1 and @Todate1))	
	and la.Status = 'Approved' 	
	group by e.employee_code_id
	--Present
	insert into #Present (Employee_code_Id,FNPresent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='Present' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Present set ANPresent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='Present' and (Date between @FromDate1 and @Todate1)	
	and  #Present.Employee_code_Id=E.Employee_code_Id)
	update #Present set Present=FNPresent+ANPresent
	update #AllEmpInOutDetails set Present= case #Present.Present when null then '0.0' else #Present.Present end from #Present 
	inner join #AllEmpInOutDetails 
	on #Present.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Absent
	insert into #Absent (Employee_code_Id,FNAbsent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='Absent' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Absent set ANAbsent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='Absent' and 
	(Date >= @FromDate1 and date >= @Todate1)
	and  #Absent.Employee_code_Id=E.Employee_code_Id)
	update #Absent set Absent=FNAbsent+ANAbsent
	--select * from #Absent
	update #AllEmpInOutDetails set Absent=#Absent.Absent from #Absent 
	inner join #AllEmpInOutDetails 
	on #Absent.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id 
	--BonusLeave
	insert into #BonusLeave (Employee_code_Id,FNBL)select E.Employee_code_Id,count(*)/2.0 
	from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode='BL' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #BonusLeave set ANBL=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode='BL' and
	(Date between @FromDate1 and @Todate1)
	and  #BonusLeave.Employee_code_Id=E.Employee_code_Id)
	update #BonusLeave set BL=FNBL+ANBL
	--select * from #BonusLeave
	--Leave
	update #AllEmpInOutDetails set Leave=(isnull(#LeaveCount.LeaveCount,0)) from #LeaveCount	
	inner join #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	update #AllEmpInOutDetails set Leave=(isnull(#AllEmpInOutDetails.Leave,0)+isnull(#BonusLeave.BL,0)) from #AllEmpInOutDetails
	inner join #BonusLeave on #BonusLeave.Employee_code_Id=#AllEmpInOutDetails.Employee_Code_Id	
	--Ot Mins
	insert into #OTMins select E.Employee_code_Id,sum(OtMins) as OTMins from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_id
	update #AllEmpInOutDetails set TotalOT = #OTMins.OtMins from #OTMins inner join #AllEmpInOutDetails on #OTMins.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	insert into #Holiday select E.Employee_code_Id,COUNT(*)	                  
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	--TotalWorkingDays
	insert into #TotalWorkedDays select E.Employee_code_Id,
	sum(case 
				  when FNAttendanceCode='Present' and ANAttendanceCode='Present' then 1   
				  when FNAttendanceCode='Present' and ANAttendanceCode='Absent' then 0.5 
				  when FNAttendanceCode='Absent' and ANAttendanceCode='Present' then 0.5                 
                  when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then 1
                  when FNAttendanceCode='RH' and ANAttendanceCode='RH' then 1
                  when FNAttendanceCode='Weekly Off' and ANAttendanceCode='Weekly Off' and (InTime<>'00:00' or OutTime<>'00:00') then  1                  
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and  (OutTime is null or OutTime='') then 0.5
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
                  when (FNAttendanceCode='Present') and(anattendanceCode='Holiday') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
                   when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and (InTime is null or InTime='') then 0.5
                  when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
                  when (anattendanceCode='Present') and(FNAttendanceCode='Holiday') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
                  when fnattendanceCode='Present' and anattendanceCode not in('Holiday','Absent','Present','RH','Weekly Off') then 0.5
                  when anattendanceCode='Present' and fnattendanceCode not in('Holiday','Absent','Present','RH','Weekly Off') then 0.5
          end)
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	where (Date between @FromDate1 and @Todate1) and ((InTime<>'00:00' or InTime is not null )
	or (OutTime<>'00:00' or OutTime is not null))
	--or fnattendanceCode in ('Tour','Training') or anattendanceCode in ('Tour','Training'))
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	update #AllEmpInOutDetails set TotalOT='0' 
	select * from #AllEmpInOutDetails A order by A.Grade_Level,Name
	select * from #TempHeader	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_RptEmployeeInOutSelectEmployee] '4','2009','','','0,1,2,3,5,9,10,11,12,13,14,15,16','0','0'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]
	 @SelectedMonth nvarchar(20),  
	 @SelectedYear nvarchar(20),  
	 @EmployeeId varchar(50),
	 @EmployeeName varchar(50),  
	 @LevelID varchar(1000), 	 
	 @employeeCategory nvarchar(50),
	 @employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
@EmpSwipeCard varchar(20)
AS
BEGIN
	declare @FromDate as nvarchar(15)
	declare @ToDate as nvarchar(15)
	set @FromDate = cast(@SelectedMonth as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
--	set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
if (@SelectedMonth=12)
	Begin
		set @ToDate =  '01/' + '01/' + cast(@SelectedYear+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
	End
declare @fromDat as datetime
declare @todat as datetime
set @fromdat=@FromDate
set @ToDat = @ToDate
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpGrade(Grade_Id int)
--Employee Grade Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
(
	[Grade_Id] ASC
) ON [PRIMARY]
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		--select  distinct employee_code_id from ta_tbl_processedData order by employee_code_id
	declare @sqlQuery as varchar(8000)
	set @sqlQuery ='select distinct TA_Tbl_ProcessedData.employee_code_id'  
	set @sqlQuery = @sqlQuery + ' FROM  dbo.TA_Tbl_ProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.SwipeCardNo=dbo.TA_Tbl_ProcessedData.Employee_Code_Id '  	
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
    set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
   	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
   	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery = @sqlQuery + ' where 1=1 And (TA_Tbl_Employee.Employee_Status=1 and ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )'  
	set @sqlQuery = @sqlQuery + ' AND (month(TA_Tbl_ProcessedData.Date) = ''' + cast(@SelectedMonth as nvarchar(50))  + ''') '   
	set @sqlQuery = @sqlQuery + ' AND (year(TA_Tbl_ProcessedData.Date) = ''' + cast(@SelectedYear as nvarchar(50))  + ''') '   
	if(@UserGroupName<>'SuperAdmin')
	begin
		--SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		SET @sqlQuery = @sqlQuery + '	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)'
	end
	if not(@EmployeeName='' or @EmployeeName='0')  
	begin  
		--set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''  
		set @sqlQuery = @sqlQuery + 'and (TA_Tbl_Employee.Employee_FirstName + isnull(TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end  
	If Not (@EmpSwipeCard = '')  
    Begin  
		  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End 
	if not (@EmployeeId='' or @EmployeeId='0')  
	begin  
		set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '  
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
	end	
	if not(@LevelID='' or @LevelID='0')  
	begin  
		set @sqlQuery = @sqlQuery + ' And (#EmpLevel.levelId IN (' + @LevelID  + '))'
	end  
	set @sqlQuery = @sqlQuery + ' order by TA_Tbl_ProcessedData.Employee_code_id'  
	Exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*	
Proc_TA_RptEmployeeInOutSummary @EmployeeId='',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',
@UserGroupName='superadmin',@GradeLevel='1',@EmpSwipeCard='',@ParentId=0,@Fromdate1='2022/11/01',@Todate1='2022/11/30',@DesignationID=0,@Gender='Both',@EmpAutoID=1


exec Proc_TA_RptEmployeeInOutSummary @DesignationID=N'0',@ToDate1=N'2024/02/05 00:00:00',@Gender=N'Both',
@EmployeeId=N'BB002',@EmpAutoId=N'0',@ParentId=N'37',@FromDate1=N'2024/02/05 00:00:00',@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@LevelID=N'37',@employeeType=N'0',@employeeCategory=N'0',@EmployeeName=N''

exec Proc_TA_RptEmployeeInOutSummary @EmployeeId=N'UTV1001,',@EmployeeName=N'',@LevelID=N'53',
@employeeCategory=N'0',@employeeType=N'0',@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',
@ParentId=53,@Fromdate1=N'01/Feb/2024',@Todate1=N'04/Feb/2024',@DesignationID=0,@Gender=N'Both',@EmpAutoID=1

*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary] 
	@EmployeeId NVARCHAR(50),
	@EmployeeName NVARCHAR(50),  
	@LevelID NVARCHAR(1000), 	 
	@employeeCategory NVARCHAR(50),
	@employeeType NVARCHAR(50)	,
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20)	,
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50),
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@EmpAutoID INT
AS
BEGIN
	SET NOCOUNT ON;
	--DECLARE @InputDate NVARCHAR(50) = @Fromdate1
	--DECLARE @InputDates NVARCHAR(50) = @Todate1
	--DECLARE @DateInDateTime DATETIME
	--DECLARE @DateInDateTimes DATETIME

 --Convert the input string to datetime
	--SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
	--SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
 --Convert the datetime to the desired format
	--Set @Fromdate1= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
	--Set @Todate1= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)

	print @Fromdate1
	Print @Todate1

	--Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(50),FatherName NVARCHAR(50),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),Present NUMERIC(18,1),
		Absent NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
		F_Day1 NVARCHAR(100) DEFAULT '-',F_Day2 NVARCHAR(100) DEFAULT '-',F_Day3 NVARCHAR(100) DEFAULT '-',F_Day4 NVARCHAR(100) DEFAULT '-',F_Day5 NVARCHAR(100) DEFAULT '-',F_Day6 NVARCHAR(100) DEFAULT '-',F_Day7 NVARCHAR(100) DEFAULT '-',F_Day8 NVARCHAR(100) DEFAULT '-',F_Day9 NVARCHAR(100) DEFAULT '-',F_Day10 NVARCHAR(100) DEFAULT '-',F_Day11 NVARCHAR(100) DEFAULT '-',F_Day12 NVARCHAR(100) DEFAULT '-',F_Day13 NVARCHAR(100) DEFAULT '-',F_Day14 NVARCHAR(100) DEFAULT '-',F_Day15 NVARCHAR(100) DEFAULT '-',F_Day16 NVARCHAR(100) DEFAULT '-',F_Day17 NVARCHAR(100) DEFAULT '-',F_Day18 NVARCHAR(100) DEFAULT '-',F_Day19 NVARCHAR(100) DEFAULT '-',F_Day20 NVARCHAR(100) DEFAULT '-',F_Day21 NVARCHAR(100) DEFAULT '-',F_Day22 NVARCHAR(100) DEFAULT '-',F_Day23 NVARCHAR(100) DEFAULT '-',F_Day24 NVARCHAR(100) DEFAULT '-',F_Day25 NVARCHAR(100) DEFAULT '-',F_Day26 NVARCHAR(100) DEFAULT '-',F_Day27 NVARCHAR(100) DEFAULT '-',F_Day28 NVARCHAR(100) DEFAULT '-',F_Day29 NVARCHAR(100) DEFAULT '-',F_Day30 NVARCHAR(100) DEFAULT '-',F_Day31 NVARCHAR(100) DEFAULT '-',
	    A_Day1 NVARCHAR(100) DEFAULT '-',A_Day2 NVARCHAR(100) DEFAULT '-',A_Day3 NVARCHAR(100) DEFAULT '-',A_Day4 NVARCHAR(100) DEFAULT '-',A_Day5 NVARCHAR(100) DEFAULT '-',A_Day6 NVARCHAR(100) DEFAULT '-',A_Day7 NVARCHAR(100) DEFAULT '-',A_Day8 NVARCHAR(100) DEFAULT '-',A_Day9 NVARCHAR(100) DEFAULT '-',A_Day10 NVARCHAR(100) DEFAULT '-',A_Day11 NVARCHAR(100) DEFAULT '-',A_Day12 NVARCHAR(100) DEFAULT '-',A_Day13 NVARCHAR(100) DEFAULT '-',A_Day14 NVARCHAR(100) DEFAULT '-',A_Day15 NVARCHAR(100) DEFAULT '-',A_Day16 NVARCHAR(100) DEFAULT '-',A_Day17 NVARCHAR(100) DEFAULT '-',A_Day18 NVARCHAR(100) DEFAULT '-',A_Day19 NVARCHAR(100) DEFAULT '-',A_Day20 NVARCHAR(100) DEFAULT '-',A_Day21 NVARCHAR(100) DEFAULT '-',A_Day22 NVARCHAR(100) DEFAULT '-',A_Day23 NVARCHAR(100) DEFAULT '-',A_Day24 NVARCHAR(100) DEFAULT '-',A_Day25 NVARCHAR(100) DEFAULT '-',A_Day26 NVARCHAR(100) DEFAULT '-',A_Day27 NVARCHAR(100) DEFAULT '-',A_Day28 NVARCHAR(100) DEFAULT '-',A_Day29 NVARCHAR(100) DEFAULT '-',A_Day30 NVARCHAR(100) DEFAULT '-',A_Day31 NVARCHAR(100) DEFAULT '-',	
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)  
	)
	--Assign Variable into some values
	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=CONVERT(Datetime, @Fromdate1,105),@loca_Todate1=CONVERT(Datetime, @Todate1,105),@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
    IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN
		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	
	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
    INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
    --For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel     SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0
    
	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)
	
	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	INSERT INTO #EmpInOutDetails 
	SELECT	E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))
	
	---Updating OD Notation 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    
    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN 
											  END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	INSERT INTO #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar)
	SELECT DISTINCT Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar FROM #EmpInOutDetails 
	
	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance
	UPDATE #AllEmpInOutDetails set PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1, PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	
	SET @Count=1
	DECLARE @SQLUS NVARCHAR(max)
	DECLARE @SQLHeader NVARCHAR(max)
	WHILE(@Count <=31)
	BEGIN
		--Creating Table Header
		SET @SQLHeader=''
		SET @SQLUS=''
		SET @SQLHeader = @SQLHeader + ' UPDATE #TempHeader SET Day'+CAST(@Count as NVARCHAR(10)) + '=' + CAST (datepart(d,@loca_Fromdate1)as NVARCHAR(10)) + 'WHERE id=1'	
		EXEC(@SQLHeader)
		--Updating data of particular date.
		IF(@Count <=@Diff)
		BEGIN			
			SET @SQLUS = @SQLUS + ' UPDATE AD SET F_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceFN,A_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceAN'
			SET @SQLUS = @SQLUS + ' FROM  #EmpInOutDetails ED INNER JOIN #AllEmpInOutDetails AD on AD.Employee_code_id=	ED.Employee_code_id AND ED.date =   CONVERT(DATETIME, ''' + @loca_Fromdate1 + ''' , 102)'
			EXEC(@SQLUS)
		END		
		SET @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
		SET @Count=@Count +1
	END
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	
	
	SELECT	Employee_Code_Id,
			Name,
			Designation,			
			CLAvailed,
			F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,
			F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
			FatherName,
			Present,
			Absent,
			Leave,
			Holiday,
			TotalOT,			
			DesignationID,
			Grade_Level,
			OrderBy,
			PD,
			AD,
			WOD,
			HD,
			LD,
			LOPD,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			TOTD,
			Aadhar,
			A_Day1,A_Day2,A_Day3,A_Day4,A_Day5,A_Day6,A_Day7,A_Day8,A_Day9,A_Day10,A_Day11,A_Day12,A_Day13,A_Day14,A_Day15,
			A_Day16,A_Day17,A_Day18,A_Day19,A_Day20,A_Day21,A_Day22,A_Day23,A_Day24,A_Day25,A_Day26,A_Day27,A_Day28,A_Day29,A_Day30,A_Day31,			
			AFDay1=REPLACE(F_Day1,'#','')+' / '+REPLACE(A_Day1,'#',''),
			AFDay2=REPLACE(F_Day2,'#','')+' / '+REPLACE(A_Day2,'#',''),
			AFDay3=REPLACE(F_Day3,'#','')+' / '+REPLACE(A_Day3,'#',''),
			AFDay4=REPLACE(F_Day4,'#','')+' / '+REPLACE(A_Day4,'#',''),
			AFDay5=REPLACE(F_Day5,'#','')+' / '+REPLACE(A_Day5,'#',''),
			AFDay6=REPLACE(F_Day6,'#','')+' / '+REPLACE(A_Day6,'#',''),
			AFDay7=REPLACE(F_Day7,'#','')+' / '+REPLACE(A_Day7,'#',''),
			AFDay8=REPLACE(F_Day8,'#','')+' / '+REPLACE(A_Day8,'#',''),
			AFDay9=REPLACE(F_Day9,'#','')+' / '+REPLACE(A_Day9,'#',''),
			AFDay10=REPLACE(F_Day10,'#','')+' / '+REPLACE(A_Day10,'#',''),
			AFDay11=REPLACE(F_Day11,'#','')+' / '+REPLACE(A_Day11,'#',''),
			AFDay12=REPLACE(F_Day12,'#','')+' / '+REPLACE(A_Day12,'#',''),
			AFDay13=REPLACE(F_Day13,'#','')+' / '+REPLACE(A_Day13,'#',''),
			AFDay14=REPLACE(F_Day14,'#','')+' / '+REPLACE(A_Day14,'#',''),
			AFDay15=REPLACE(F_Day15,'#','')+' / '+REPLACE(A_Day15,'#',''),
			AFDay16=REPLACE(F_Day16,'#','')+' / '+REPLACE(A_Day16,'#',''),
			AFDay17=REPLACE(F_Day17,'#','')+' / '+REPLACE(A_Day17,'#',''),
			AFDay18=REPLACE(F_Day18,'#','')+' / '+REPLACE(A_Day18,'#',''),
			AFDay19=REPLACE(F_Day19,'#','')+' / '+REPLACE(A_Day19,'#',''),
			AFDay20=REPLACE(F_Day20,'#','')+' / '+REPLACE(A_Day20,'#',''),
			AFDay21=REPLACE(F_Day21,'#','')+' / '+REPLACE(A_Day21,'#',''),
			AFDay22=REPLACE(F_Day22,'#','')+' / '+REPLACE(A_Day22,'#',''),
			AFDay23=REPLACE(F_Day23,'#','')+' / '+REPLACE(A_Day23,'#',''),
			AFDay24=REPLACE(F_Day24,'#','')+' / '+REPLACE(A_Day24,'#',''),
			AFDay25=REPLACE(F_Day25,'#','')+' / '+REPLACE(A_Day25,'#',''),
			AFDay26=REPLACE(F_Day26,'#','')+' / '+REPLACE(A_Day26,'#',''),
			AFDay27=REPLACE(F_Day27,'#','')+' / '+REPLACE(A_Day27,'#',''),
			AFDay28=REPLACE(F_Day28,'#','')+' / '+REPLACE(A_Day28,'#',''),
			AFDay29=REPLACE(F_Day29,'#','')+' / '+REPLACE(A_Day29,'#',''),
			AFDay30=REPLACE(F_Day30,'#','')+' / '+REPLACE(A_Day30,'#',''),
			AFDay31=REPLACE(F_Day31,'#','')+' / '+REPLACE(A_Day31,'#','')			
	FROM #AllEmpInOutDetails A ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),Name
	
	SELECT * FROM #TempHeader
	
	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*		
-- Proc_TA_RptEmployeeInOutSummary_saradhambika '','',0,0,0,'SuperAdmin','0','',1,'2018-10-01','2018-10-01',0,'Both',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika] 
	@EmployeeId nvarchar(50),
	@EmployeeName nvarchar(50),  
	@LevelID nvarchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName nvarchar(250),
	@GradeLevel nvarchar(20)	,
	@EmpSwipeCard nvarchar(20),
	@ParentId int,
	@Fromdate1 nvarchar(50),
    @Todate1 nvarchar(50),
	@DesignationID int,
	@Gender nvarchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	if(@EmployeeId is not null and @EmployeeId <> '')
            BEGIN
                  CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
                  INSERT INTO #EmployeeID
                  SELECT * from SplitupEmployeeCode(@EmployeeId)
            end
      if(@EmployeeName is not null and @EmployeeName <> '')
            BEGIN
                  CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
                  INSERT INTO #EmployeeName
                  SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
            end
            --select * from #EmployeeID
	Declare @Fromdate2 datetime
	set @Fromdate2 = @Fromdate1
	Declare @Count int
	declare @Diff int
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	Declare @SQL2 nvarchar(max)
	set @SQL2=''
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	create table #TempHeader(id int,Day1 varchar(20),Day2 varchar(20),Day3 varchar(20),Day4 varchar(20),Day5 varchar(20),Day6 varchar(20),Day7 varchar(20),Day8 varchar(20),Day9 varchar(20),Day10 varchar(20),Day11 varchar(20),Day12 varchar(20),Day13 varchar(20),Day14 varchar(20),Day15 varchar(20),Day16 varchar(20),Day17 varchar(20),Day18 varchar(20),Day19 varchar(20),Day20 varchar(20),Day21 varchar(20),Day22 varchar(20),Day23 varchar(20),Day24 varchar(20),Day25 varchar(20),Day26 varchar(20),Day27 varchar(20),Day28 varchar(20),Day29 varchar(20),Day30 varchar(20),Day31 varchar(20))
	--create table #TempTotal(id int,Day1 varchar(10),Day2 varchar(10),Day3 varchar(10),Day4 varchar(10),Day5 varchar(10),Day6 varchar(10),Day7 varchar(10),Day8 varchar(10),Day9 varchar(10),Day10 varchar(10),Day11 varchar(10),Day12 varchar(10),Day13 varchar(10),Day14 varchar(10),Day15 varchar(10),Day16 varchar(10),Day17 varchar(10),Day18 varchar(10),Day19 varchar(10),Day20 varchar(10),Day21 varchar(10),Day22 varchar(10),Day23 varchar(10),Day24 varchar(10),Day25 varchar(10),Day26 varchar(10),Day27 varchar(10),Day28 varchar(10),Day29 varchar(10),Day30 varchar(10),Day31 varchar(10))
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50),FatherName nvarchar(50),Designation nvarchar(250),Employee_Code_Id nvarchar(15),Present numeric(18,1),
		Absent numeric(18,1),Leave numeric(18,1) default(0),Holiday numeric(18,1),TotalOT numeric(18,1),DesignationID int,Grade_Level int,OrderBy int,CLAvailed decimal(18,2),
		F_Day1 nvarchar(100) DEFAULT '-',F_Day2 nvarchar(100) DEFAULT '-',F_Day3 nvarchar(100) DEFAULT '-',F_Day4 nvarchar(100) DEFAULT '-',F_Day5 nvarchar(100) DEFAULT '-',F_Day6 nvarchar(100) DEFAULT '-',F_Day7 nvarchar(100) DEFAULT '-',F_Day8 nvarchar(100) DEFAULT '-',F_Day9 nvarchar(100) DEFAULT '-',F_Day10 nvarchar(100) DEFAULT '-',F_Day11 nvarchar(100) DEFAULT '-',F_Day12 nvarchar(100) DEFAULT '-',F_Day13 nvarchar(100) DEFAULT '-',F_Day14 nvarchar(100) DEFAULT '-',F_Day15 nvarchar(100) DEFAULT '-',F_Day16 nvarchar(100) DEFAULT '-',F_Day17 nvarchar(100) DEFAULT '-',F_Day18 nvarchar(100) DEFAULT '-',F_Day19 nvarchar(100) DEFAULT '-',F_Day20 nvarchar(100) DEFAULT '-',F_Day21 nvarchar(100) DEFAULT '-',F_Day22 nvarchar(100) DEFAULT '-',F_Day23 nvarchar(100) DEFAULT '-',F_Day24 nvarchar(100) DEFAULT '-',F_Day25 nvarchar(100) DEFAULT '-',F_Day26 nvarchar(100) DEFAULT '-',F_Day27 nvarchar(100) DEFAULT '-',F_Day28 nvarchar(100) DEFAULT '-',F_Day29 nvarchar(100) DEFAULT '-',F_Day30 nvarchar(100) DEFAULT '-',F_Day31 nvarchar(100) DEFAULT '-',
		OffDays numeric(18,1),TotalDays as Present+Absent+Leave+Holiday+OffDays		
	)
	create table #EmpInOutDetails(Employee_code_id nvarchar(15),LevelId int,date datetime,Otmins numeric(18,1),TotalDays numeric(18, 1),
	AttendanceFN nvarchar(25),AttendanceAN nvarchar(25),employee_code_id1 nvarchar(15),Designation nvarchar(250),empname nvarchar(150),
	Father_Name nvarchar(50),DesignationId int,Grade_Level int,OrderBy int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20)
	,NightOrMorn int,InNotation char(1),OutNotation char(1),DayPresent decimal(18,1) default(0),DayAbsent decimal(18,1) default(0),DayLeave decimal(18,1) default(0))	
	create table #LeaveCount(Employee_code_Id nvarchar(15),LeaveCount numeric(18,1),LeaveCountFraction nvarchar(10))
	create table #OTMins(Employee_code_Id nvarchar(15),OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15),NFHolidays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15),Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15),FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15),FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15),FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id nvarchar(20),InTime nvarchar(25),OutTime nvarchar(25),Attendance nvarchar(20),fnattendanceCode nvarchar(20),
	anattendanceCode nvarchar(20),Shift_Id int,LevelId bigint,OtMins float,TotalDays numeric(18,1),earlyoutmins float,LateInmins float,HrsWork nvarchar(10),ShiftId int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20),NightOrMorn int,InNotation char(1),OutNotation char(1))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo nvarchar(20))
	set @Diff = datediff(d,@Fromdate1,@Todate1) +1
	set @Count=1
	insert into #TempHeader(id) values(1)
	--insert into #TempTotal(id) values(1)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@Todate1 as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End	
	Execute(@sqlEmpLevel)
		--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @ToDate1,@EmpSwipeCard,@DesignationID  
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @ToDate1,@EmpSwipeCard,@employeeType 
    INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @ToDate1,@EmpSwipeCard,@employeeCategory
	Declare @sqlTempProcess nvarchar(max)
	Declare @sqlTempProcess1 nvarchar(max)
	Declare @sqlCommonSwipeCard nvarchar(max)
	set @sqlCommonSwipeCard=''
	select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0
	Declare @sqlTempProcessedData nvarchar(max)
	Declare @sqlTempProcessedData1 nvarchar(max)
	Declare @sqlCommonEmpId nvarchar(max)
	Declare @sqlCommon1 nvarchar(max)
      set @sqlCommon1=''
	set @sqlTempProcessedData=		
	'insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins
		,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		inner join #InActiveDatas IA on (#EmpLevel.SwipeCard=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id '
	set @sqlTempProcessedData=@sqlTempProcessedData+@sqlCommon1
	set @sqlTempProcessedData=@sqlTempProcessedData+' where pd.processflag=1 and PD.Date >=''' + @Fromdate1 + ''' and PD.Date <= ''' + @Todate1 + ''' '
		Execute(@sqlTempProcessedData)
		set @sqlTempProcessedData1=		
	' insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,
	InNotation,OutNotation
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  '
	set @sqlTempProcessedData1=@sqlTempProcessedData1+@sqlCommon1
	set @sqlTempProcessedData1=@sqlTempProcessedData1+' where pd.processflag=1 and PD.Date >=''' + @Fromdate1 + ''' and PD.Date <= ''' + @Todate1 + ''' and #EmpLevel.SwipeCard not in(select distinct swipecardno from #InActiveDatas)'
	--print(@sqlTempProcessedData1)
	Execute(@sqlTempProcessedData1)
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)='PM' and SUBSTRING(S.Shift_Endtime,7,8)='AM' then 1 
													--when SUBSTRING(S.Shift_StartTime,7,8)='AM' and SUBSTRING(S.Shift_Endtime,7,8)='PM' and PD.OutTime>'00:00 AM' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	Insert into #EmpInOutDetails 
	select E.Employee_code_id,'',date,OtMins,TotalDays,
	AttendanceFN=
	case	when FNAttendanceCode='Present' and (LateInmins <> '0') then '*P'
			when FNAttendanceCode='Present' and (LateInmins = '0')  then 'P'
			when FNAttendanceCode='Absent'  then 'A'
			when FNAttendanceCode='Holiday' and (Intime<> '00:00') then '*H'
			when FNAttendanceCode='Holiday' and (Intime= '00:00' or intime is null)  then 'H'
			when FNAttendanceCode='RH' and (Intime<> '00:00') then '*RH'
			when FNAttendanceCode='RH' and (Intime= '00:00' or intime is null) then 'RH'
			when FNAttendanceCode='Weekly Off' and (Intime<>'00:00') then '*WH' 
			when FNAttendanceCode='Weekly Off' and (Intime='00:00' or intime is null) then 'WH' 
			when FNAttendanceCode='Comp Off' then 'C'
			Else Upper(FNAttendanceCode)
	end+ case when InNotation='M' then '#' else '' end,
	AttendanceAN= 
	case	when ANAttendanceCode='Present' and (earlyoutmins <> '0') then 'P' 
			when ANAttendanceCode='Present' and (earlyoutmins = '0')  then 'P' 
			when ANAttendanceCode='Absent' then 'A'
			when ANAttendanceCode='Holiday' and (OutTime<>'00:00') then '*H' 
			when ANAttendanceCode='Holiday' and (OutTime='00:00' or outtime is null) then 'H' 
			when ANAttendanceCode='RH' and (OutTime<>'00:00') then '*RH' 
			when ANAttendanceCode='RH' and (OutTime='00:00' or outtime is null) then 'RH'
			when ANAttendanceCode='Weekly Off' and Outtime<> '00:00' then '*WH' 
			when ANAttendanceCode='Weekly Off' and (Outtime='00:00' or outtime is null) then 'WH'
			when ANAttendanceCode='Comp Off' then 'C'
			Else upper(ANAttendanceCode)
	end+ case when OutNotation='M' then '#' else '' end,
	TPD.employee_code_id, 
	Replace(T.TitleName,'&amp;','&') as Designation,
	E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'') as empname, 
	Father_Name,
	TitleId,G.Grade_Level,0,TPD.Shift_FirstHalf_StartTime,TPD.Shift_FirstHalf_EndTime,TPD.Shift_SecondHalf_StartTime,
	TPD.Shift_SecondHalf_EndTime,TPD.NightOrMorn,InNotation,OutNotation,
	case when fnattendanceCode='Present' and anattendanceCode='Present'	then 1
		 when fnattendanceCode='Present' and anattendanceCode!='Present'then 0.5
		 when fnattendanceCode!='Present'and anattendanceCode='Present' then 0.5
	End,
	case when fnattendanceCode='Absent'  and anattendanceCode='Absent'	then 1
		 when fnattendanceCode='Absent'  and anattendanceCode!='Absent' then 0.5
		 when fnattendanceCode!='Absent' and anattendanceCode='Absent'	then 0.5
	End,
	case when fnattendanceCode not in('Present','Absent','Weekly Off','Holiday','RH') and anattendanceCode not in('Present','Absent','Weekly Off','Holiday','RH') then 1
		 when fnattendanceCode in('Present','Absent','Weekly Off','Holiday','RH') and anattendanceCode not in('Present','Absent','Weekly Off','Holiday','RH') then 0.5
		 when fnattendanceCode not in('Present','Absent','Weekly Off','Holiday','RH') and anattendanceCode in('Present','Absent','Weekly Off','Holiday','RH') then 0.5
	End
	FROM  #TempProcessedData TPD INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id    
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID
	inner join #EmpCategory on E.Employee_Id = #EmpCategory.EmployeeId
	inner join #EmpType on E.Employee_Id = #EmpType.EmployeeId
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId
	inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId
	inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId
	where 1=1 And (E.Isdeleted=0 and E.report_exclude=0 )
	--select * from #EmpInOutDetails 
    UPDATE #EmpInOutDetails SET AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,'FN', PD.Shift_Id, AttendanceFN),
								AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id,'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails 	
	--select * from #EmpInOutDetails order by date
	set @Count=1
	Declare @SQLFN nvarchar(max)	
	Declare @SQLFN1 nvarchar(max)	
	Declare @SQLTemp nvarchar(max)
	set @SQLFN=''
	set @SQLFN1=''
	set @SQLTemp=''
	Declare @FromDate3 nvarchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
			if(@Count <=@Diff)
			Begin
				set @SQLFN=''
				set @SQLFN1=''
				set @SQLFN = @SQLFN + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as nvarchar(10)) + ' = 
				case when AttendanceFN=''P''	and AttendanceAN =''P''		then ''P''
					 when AttendanceFN=''*P''	and AttendanceAN =''*P''	then ''*P''
					 when AttendanceFN=''P''	and AttendanceAN =''*P''	then ''P''
					 when AttendanceFN=''*P''	and AttendanceAN =''P''		then ''*P''
					 when AttendanceFN=''P''	and AttendanceAN !=''P''	then ''HP''
					 when AttendanceFN=''*P''	and AttendanceAN !=''P''	then ''*HP''
					 when AttendanceFN!=''P''	and AttendanceAN =''P''		then ''HP''
					 when AttendanceFN!=''P''	and AttendanceAN =''*P''	then ''HP''
					 when AttendanceFN=''P#''	and AttendanceAN !=''P#''	then ''HP''
					 when AttendanceFN=''*P#''	and AttendanceAN !=''P#''	then ''*HP''
					 when AttendanceFN!=''P#''	and AttendanceAN =''P#''		then ''HP''
					 when AttendanceFN!=''P#''	and AttendanceAN =''*P#''	then ''HP''
					 else AttendanceFN
				End,
				Present=isnull(Present,0)+case	when AttendanceFN=''P''	and AttendanceAN =''P''		then 1
												when AttendanceFN=''P#''and AttendanceAN =''P#''	then 1
												when AttendanceFN=''*P''and AttendanceAN =''*P''	then 1
												when AttendanceFN=''*P#''and AttendanceAN =''*P#''	then 1
												when AttendanceFN=''P''	and AttendanceAN =''*P''	then 1
												when AttendanceFN=''P#''and AttendanceAN =''*P#''	then 1
												when AttendanceFN=''*P''and AttendanceAN =''P''		then 1
												when AttendanceFN=''*P#''and AttendanceAN =''P#''	then 1
												when AttendanceFN=''P''	and AttendanceAN !=''P''	then 0.5
												when AttendanceFN=''P#''and AttendanceAN !=''P#''	then 0.5
												when AttendanceFN=''*P''and AttendanceAN !=''P''	then 0.5
												when AttendanceFN=''*P#''and AttendanceAN !=''P#''	then 0.5
												when AttendanceFN!=''P''and AttendanceAN =''P''		then 0.5
												when AttendanceFN!=''P#''and AttendanceAN =''P#''	then 0.5
												when AttendanceFN!=''P''and AttendanceAN =''*P''	then 0.5
												when AttendanceFN!=''P#''and AttendanceAN =''*P#''	then 0.5
												else 0
										 End,
				Absent=isnull(Absent,0)+case	when AttendanceFN=''A'' and AttendanceAN =''A'' then 1
												when AttendanceFN=''A#'' and AttendanceAN =''A#'' then 1
												when (AttendanceFN=''A'' and AttendanceAN !=''A'') or (AttendanceFN!=''A'' and AttendanceAN =''A'') then 0.5
												when (AttendanceFN=''A#'' and AttendanceAN !=''A#'') or (AttendanceFN!=''A#'' and AttendanceAN =''A#'') then 0.5
												else 0
										  END,'
				set @SQLFN1 = @SQLFN1 + ' OffDays=isnull(OffDays,0)+case	when AttendanceFN=''WH'' and AttendanceAN =''WH'' then 1
												when AttendanceFN=''*WH'' and AttendanceAN =''*WH'' then 1
												when AttendanceFN=''*WH#'' and AttendanceAN =''*WH#'' then 1
												else 0
										  END,
				Holiday=isnull(Holiday,0)+case	when AttendanceFN=''H'' and AttendanceAN =''H'' then 1
												when AttendanceFN=''H#'' and AttendanceAN =''H#'' then 1
												when AttendanceFN=''RH'' and AttendanceAN =''RH'' then 1
												when AttendanceFN=''RH#'' and AttendanceAN =''RH#'' then 1
												when AttendanceFN=''*H'' and AttendanceAN =''*H'' then 1
												when AttendanceFN=''*H#'' and AttendanceAN =''*H#'' then 1
												when AttendanceFN=''*RH'' and AttendanceAN =''*RH'' then 1
												when AttendanceFN=''*RH#'' and AttendanceAN =''*RH#'' then 1
												else 0
										  END,
				Leave=isnull(Leave,0)+case	when AttendanceFN not in(''P'',''*P'',''P#'',''*P#'',''A'',''WH'',''*WH'',''*WH#'',''H'',''H#'',''RH#'',''RH'',''*H'',''*H#'',''*RH'',''*RH#'') and AttendanceAN not in(''P'',''*P'',''P#'',''*P#'',''A'',''WH'',''*WH'',''*WH#'',''H'',''H#'',''RH'',''RH#'',''*H'',''*RH'',''*H#'',''*RH#'') then 1
											when AttendanceFN in(''P'',''*P'',''A'',''WH'',''*WH'',''H'',''RH'',''*H'',''*RH'') and AttendanceAN not in(''P'',''*P'',''A'',''WH'',''*WH'',''H'',''RH'',''*H'',''*RH'') then 0.5
											when AttendanceFN not in(''P'',''*P'',''A'',''WH'',''*WH'',''H'',''RH'',''*H'',''*RH'') and AttendanceAN in(''P'',''*P'',''A'',''WH'',''*WH'',''H'',''RH'',''*H'',''*RH'') then 0.5
											when AttendanceFN=''*RH'' and AttendanceAN =''*RH'' then 1
											else 0
										  END
				from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	
				#EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date =   CONVERT(DATETIME, ''' + @Fromdate1 + ''' , 102)'
				exec(@SQLFN+@SQLFN1)				
			End
			set @SQLTemp=''
			set @SQLTemp = @SQLTemp + ' update #TempHeader set Day'+cast(@Count as nvarchar(10)) + '=(select '''+cast(@Count as nvarchar(10)) + '''+''#''+isnull(convert(varchar,SUM(isnull(DayPresent,0))),'''')+''#''+isnull(convert(varchar,SUM(isnull(DayAbsent,0))),'''')+''#''+
										isnull(convert(varchar,SUM(isnull(DayLeave,0))),'''')
				from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	
				#EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date =   CONVERT(DATETIME, ''' + @Fromdate1 + ''' , 102))'
			print(@SQLTemp)
			exec(@SQLTemp)
			set @Fromdate1=dateadd(d,1,@Fromdate1)
			set @Count=@Count +1
		end	
	select SlNo=ROW_NUMBER()over(order by Employee_Code_Id), Employee_Code_Id,Name,Designation,
		   F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
		   Present,Absent,Leave,Holiday,OffDays
		   --,TotalDays
	from #AllEmpInOutDetails A
	--select *from #TempTotal
	select * from #TempHeader
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #TempProcessedData
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptEmployeeSchedule]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Senthil
-- ALTER  date: 06-Aug-2007
-- Description:	Reports - Employee Schedule
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_rptEmployeeSchedule]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(18) 
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT     convert(nvarchar(20),dbo.TA_Tbl_ShiftAllocation.From_Date,101) as 
from_Date, convert(nvarchar(20),dbo.TA_Tbl_ShiftAllocation.To_Date,101) as to_date, dbo.TA_Tbl_ShiftPattern.Pattern_Name, '
        set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + 
dbo.TA_Tbl_Employee.Employee_LastName as empName, dbo.TA_Tbl_ShiftAllocationDetails.Employee_Id, '
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee.Designation_Id, dbo.Ta_Tbl_levelDetails.name,  
dbo.TA_Tbl_Title.TitleName'
		set @sqlQuery = @sqlQuery + ' FROM         dbo.TA_Tbl_ShiftAllocationDetails INNER JOIN'
        set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_ShiftAllocation ON dbo.TA_Tbl_ShiftAllocationDetails.ShiftAllocation_Id = 
dbo.TA_Tbl_ShiftAllocation.ShiftAllocation_Id INNER JOIN'
        set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_ShiftPattern ON dbo.TA_Tbl_ShiftAllocation.ShiftPattern_Id = 
dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id INNER JOIN'
        set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ShiftAllocationDetails.Employee_Id = 
dbo.TA_Tbl_Employee.Employee_Id INNER JOIN'
        set @sqlQuery = @sqlQuery + ' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id 
INNER JOIN'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = 
dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' WHERE     (dbo.TA_Tbl_Employee.Isdeleted = 1)  
(dbo.TA_Tbl_Employee.Employee_Status = 1) AND '
		set @sqlQuery = @sqlQuery + ' (dbo.TA_Tbl_ShiftAllocation.From_Date >= CONVERT(DATETIME, '''+ cast( @fromDat 
as nvarchar(50))   + ''', 101)) AND '
        set @sqlQuery = @sqlQuery + ' (dbo.TA_Tbl_ShiftAllocation.To_Date <= CONVERT(DATETIME, ''' + cast( @toDat as 
nvarchar(50))   +  ''', 101))'
		if not(@EmployeeName='' or @EmployeeName='0')
		begin
			set @sqlQuery = @sqlQuery + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + 
cast(@EmployeeName+'%' as nvarchar(100)) + ''''
		end
		if not (@empId='' or @empId='0')
		begin
			set @sqlQuery = @sqlQuery + ' and ta_tbl_processedData.Employee_Code_Id = ''' + cast (@empId as 
nvarchar(50)) + ''' '
		end
		if not(@LevelID='' or @LevelID='0')
		begin
			set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.LevelId = ' + cast (@LevelId as nvarchar(50)) 
		end	
			set @sqlQuery = @sqlQuery + ' order by ta_tbl_employee.Employee_firstName'
		exec (@sqlQuery)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author		: senthil
-- ALTER  date  : 04August08   
-- Modified By	: Sashma
-- Modified On	: 12-May-2011
--Modified By		:	Gopinath.K
--Modified Date	:	04-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--Descriptions	:	SQL Query OPtimazation for handle EMPID.
-- Proc_Ta_RptEmployeeShiftNotAlloc '04/17/2009','04/17/2012','','','',[0,1],'','','','SuperAdmin','','',0,0,'Both'
-- Description:	Report Employee Details
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]
(
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(20),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint
)
AS
BEGIN
	if(charIndex('-',@ToDat)>0)
		begin
			set @ToDat=(select convert(varchar(30),getdate(),102))
		end
	SET NOCOUNT ON;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'SELECT replace(dept.name,''&amp;'',''&'') as department, dbo.TA_Tbl_Employee.Employee_code_Id as employee_id,dbo.TA_Tbl_Employee.Employee_Id as empAutoId,status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
	set @sqlQuery = @sqlQuery + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname,convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as dateOfBirth,dbo.TA_Tbl_Employee.Nationality,'
	set @sqlQuery = @sqlQuery + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, Convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as dateJoin,dbo.TA_Tbl_Employee.Report_Exclude,TA_Tbl_Employee.Gender'		
	set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_Employee '
	set @sqlQuery = @sqlQuery + ' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
	set @sqlQuery = @sqlQuery + ' INNER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id'
	set @sqlQuery = @sqlQuery + ' INNER join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @sqlQuery = @sqlQuery + ' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'') '
	if(@UserGroupName<>'SuperAdmin')
		begin
			set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' '
		end
	if not(@fromDat='')		
		begin
			set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '			End
	if not (@ToDat='')
		begin
			set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 			end
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@EmployeeStatus='Active')
		begin
			set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_Status = 1) '
		end		
	else if(@EmployeeStatus='InActive')
		begin		
			set @sqlQuery = @sqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_Status = 0) '	
		end		
	--if(@EmpAutoId > 0)
	--		BEGIN
	--		   set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
	--		END
	set @sqlQuery = @sqlQuery + ' order by dbo.TA_Tbl_Employee.Employee_code_Id '
	exec(@sqlQuery)
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name		:	Proc_TA_RptFirstInPunchDifference
Created By				:	A.K.T.MOORTHI
Created on				:	11-Jun-2014
Description			:	To Get the Employee Shift-In, Break-In, Lunch-In Punch With Work Place In Punch Difference
EXEC Proc_TA_RptFirstInPunchDifference 
	@EmployeeID=N'',@LevelID=N'0',@FromDate=N'02/Jun/2014',@ToDate=N'07/Jun/2014',@EmployeeName=N'Karthi',
	@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpAutoId=0,@MaxWorkPlaceIn=N'00:00',
	@PunchType = N'', @ParentId = 0
	exec Proc_TA_RptFirstInPunchDifference @FromDate=N'01/Jan/2015',@ToDate=N'30/Jan/2015',@EmployeeName=N'',
	@LevelID=N'107',@EmployeeID=N'',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',
	@EmpAutoId=0,@MaxWorkPlaceIn=N'',@PunchType=N'''Shift In'',''Lunch In''',@ParentId=107
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference]
	@FromDate DATETIME,  
	@ToDate DATETIME,  
	@EmployeeName VARCHAR(250),  
	@LevelID VARCHAR(MAX),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(20),
	@GradeLevel VARCHAR(20),
	@EmpAutoId BIGINT,
	@MaxWorkPlaceIn NVARCHAR(5),
	@PunchType VARCHAR(40)
AS  
BEGIN  
Set @LevelID='107,108,109,110,111,112,113,114,115,123';
--Temporary table's creation
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #ExceptionEmployeeIds(EmployeeId VARCHAR(100), ExceptionDate DATETIME, ExceptionHours BIGINT)
	--CREATE TABLE #LevelRights(LevelId INT)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId)
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	--INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel
		SELECT Elevel.EmployeeId, EL.levelId,Elevel.EffectiveDate FROM(
			SELECT MAX(el.EffectiveDate) AS EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel el
				INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) ELevel
		INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate = ELevel.EffectiveDate AND EL.employeeid = ELevel.EmployeeId AND
		EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
		SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate FROM(
			SELECT MAX(ed.EffectiveDate) AS EffectiveDate, ed.EmployeeId FROM TA_Tbl_EmployeeDesignation ed
				INNER JOIN ta_tbl_employee emp ON ed.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EDesig
		INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND ED.employeeid = EDesig.EmployeeId AND
		ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType
		SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
			SELECT MAX(et.EffectiveDate) AS EffectiveDate, et.EmployeeId FROM TA_Tbl_EmployeeType et
				INNER JOIN ta_tbl_employee emp ON et.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpType
		INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId AND
		EType.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
		SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
			SELECT MAX(ec.EffectiveDate) AS EffectiveDate, ec.EmployeeId FROM TA_Tbl_EmployeeCategory ec
				INNER JOIN ta_tbl_employee emp ON ec.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpCategory
		INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate AND ECategory.employeeid = EmpCategory.EmployeeId AND
		ECategory.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ECategory.CategoryId IS NOT NULL
	INSERT INTO #ExceptionEmployeeIds
		SELECT IPD.EmployeeCodeId, IPD.[Date], SUM(IPD.PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference IPD
			WHERE IPD.[Date] BETWEEN CONVERT(DATETIME, CAST(@FromDate AS VARCHAR(11)), 102) AND CONVERT(DATETIME, CAST(@ToDate AS VARCHAR(11)), 102) 
		GROUP BY IPD.[Date], IPD.EmployeeCodeId HAVING SUM(IPD.PunchDifferenceMins) > DATEDIFF(MI, '00:00', ISNULL(@MaxWorkPlaceIn, '00:03'))
	DECLARE @Query VARCHAR(MAX)
	SET @Query = 'SELECT IPD.[Date], IPD.EmployeeCodeId, ISNULL(E.Employee_FirstName, '''') + SPACE(1) + ISNULL(E.Employee_LastName, '''') AS EmployeeName, IPD.EntranceName, '
	SET @Query = @Query + 'IPD.EntranceType, IPD.EntranceTime, ISNULL(IPD.FloorName, ''?'') FloorName, ISNULL(IPD.FloorType, ''?'') FloorType, ISNULL(IPD.FloorTime, ''?'') FloorTime, (CASE WHEN IPD.PunchDifference = ''23:59'' THEN ''?'' ELSE IPD.PunchDifference END) PunchDifference, IPD.PunchDifferenceMins FROM TA_VW_FirstInPunchDifference IPD '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = IPD.EmployeeCodeId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Title T ON T.TitleId = ED.DesignationId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeCategory EC ON EC.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeType ET ON ET.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN #EmpLevel TL ON TL.EffectiveDate = EL.EffectiveDate AND TL.EmployeeId = EL.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpType TT ON TT.EffectiveDate = ET.EffectiveDate AND TT.EmployeeId = ET.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpDesignation TD ON TD.EffectiveDate = ED.EffectiveDate AND TD.EmployeeId = ED.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpCategory TC ON TC.EffectiveDate = EC.EffectiveDate AND TC.EmployeeId = EC.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #ExceptionEmployeeIds ExEmp ON ExEmp.ExceptionDate = IPD.[Date] AND ExEmp.EmployeeId = IPD.EmployeeCodeId '
	--SET @Query = @Query + 'INNER JOIN #LevelRights LR ON LR.LevelId = TL.LevelId '		
	--SET @Query = @Query + 'WHERE IPD.PunchDifference > ''' + ISNULL(@MaxWorkPlaceIn, '00:03') + ''' AND E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 '
	SET @Query = @Query + 'WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 '
	SET @Query = @Query + 'AND IPD.[Date] BETWEEN CONVERT(DATETIME, ''' + CAST(@FromDate AS VARCHAR(11)) + ''', 102) AND CONVERT(DATETIME, ''' + CAST(@ToDate AS VARCHAR(11)) + ''', 102) '
	IF(@UserGroupName <> 'SuperAdmin')
	BEGIN
		SET @Query = @Query + CASE WHEN @EmpAutoId != 0 THEN 'AND G.Grade_Level >= ' + @GradeLevel + ' AND (E.Reporting_To = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''' OR E.Leave_Sanc_Authority = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''' OR E.Employee_Id = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''') '
													ELSE 'AND (G.Grade_Level >= ' + @GradeLevel + ' OR E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''') ' END 
	END 
	IF NOT(@EmployeeName = '')  
	BEGIN
		SET @Query = @Query + 'AND (E.Employee_FirstName + '' '' + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName + '%' AS NVARCHAR(100)) + ''') '
	END
	IF NOT(@EmployeeId = '')
	BEGIN
		SET @Query = @Query + 'AND (E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''') '
	END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @Query = @Query + 'AND EC.CategoryId = ' + CAST(@EmployeeCategory AS NVARCHAR(8)) + ' '
	END
	IF(@EmployeeType <> 0)
	BEGIN
		SET @Query = @Query + 'AND ET.TypeId = ' + CAST(@EmployeeType AS NVARCHAR(8)) + ' '
	END
	IF(@PunchType <> '')
	BEGIN
		SET @Query = @Query + 'AND IPD.EntranceType IN(' + @PunchType + ') '
	END	
	IF(NOT(@LevelID = '' OR @LevelID = '0'))
		BEGIN
			SET @Query = @Query + ' AND (TL.levelId IN (' + @LevelID + ')) '
		END
	if(@isReportingto > 0)
            BEGIN
               set @Query = @Query + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	SET @Query = @Query + 'ORDER BY IPD.[Date], IPD.EmployeeCodeId'
	EXEC(@Query)
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory	
	DROP TABLE #EmployeeIds		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference_email]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference_email]
	@FromDate DATETIME,  
	@ToDate DATETIME,  
	@EmployeeName VARCHAR(250),  
	@LevelID VARCHAR(MAX),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(20),
	@GradeLevel VARCHAR(20),
	@EmpAutoId BIGINT,
	@MaxWorkPlaceIn NVARCHAR(5),
	@PunchType VARCHAR(40)
AS  
BEGIN  
Set @LevelID='107,108,109,110,111,112,113,114,115,123';
--Temporary table's creation
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #ExceptionEmployeeIds(EmployeeId INT, ExceptionDate DATETIME, ExceptionHours BIGINT)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId)
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel
		SELECT Elevel.EmployeeId, EL.levelId,Elevel.EffectiveDate FROM(
			SELECT MAX(el.EffectiveDate) AS EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel el
				INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) ELevel
		INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate = ELevel.EffectiveDate AND EL.employeeid = ELevel.EmployeeId AND
		EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
		SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate FROM(
			SELECT MAX(ed.EffectiveDate) AS EffectiveDate, ed.EmployeeId FROM TA_Tbl_EmployeeDesignation ed
				INNER JOIN ta_tbl_employee emp ON ed.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EDesig
		INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND ED.employeeid = EDesig.EmployeeId AND
		ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType
		SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
			SELECT MAX(et.EffectiveDate) AS EffectiveDate, et.EmployeeId FROM TA_Tbl_EmployeeType et
				INNER JOIN ta_tbl_employee emp ON et.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpType
		INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId AND
		EType.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
		SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
			SELECT MAX(ec.EffectiveDate) AS EffectiveDate, ec.EmployeeId FROM TA_Tbl_EmployeeCategory ec
				INNER JOIN ta_tbl_employee emp ON ec.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpCategory
		INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate AND ECategory.employeeid = EmpCategory.EmployeeId AND
		ECategory.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ECategory.CategoryId IS NOT NULL
	INSERT INTO #ExceptionEmployeeIds
		SELECT IPD.EmployeeCodeId, IPD.[Date], SUM(IPD.PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference IPD
			WHERE IPD.[Date] BETWEEN CONVERT(DATETIME, CAST(@FromDate AS VARCHAR(11)), 102) AND CONVERT(DATETIME, CAST(@ToDate AS VARCHAR(11)), 102) 
		GROUP BY IPD.[Date], IPD.EmployeeCodeId HAVING SUM(IPD.PunchDifferenceMins) > DATEDIFF(MI, '00:00', ISNULL(@MaxWorkPlaceIn, '00:03'))
	DECLARE @Query VARCHAR(MAX)
	SET @Query = 'SELECT IPD.[Date], IPD.EmployeeCodeId, ISNULL(E.Employee_FirstName, '''') + SPACE(1) + ISNULL(E.Employee_LastName, '''') AS EmployeeName, IPD.EntranceName, '
	SET @Query = @Query + 'IPD.EntranceType, IPD.EntranceTime, ISNULL(IPD.FloorName, ''?'') FloorName, ISNULL(IPD.FloorType, ''?'') FloorType, ISNULL(IPD.FloorTime, ''?'') FloorTime, (CASE WHEN IPD.PunchDifference = ''23:59'' THEN ''?'' ELSE IPD.PunchDifference END) PunchDifference, IPD.PunchDifferenceMins FROM TA_VW_FirstInPunchDifference IPD '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = IPD.EmployeeCodeId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Title T ON T.TitleId = ED.DesignationId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeCategory EC ON EC.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN TA_Tbl_EmployeeType ET ON ET.EmployeeId = E.Employee_Id '
	SET @Query = @Query + 'INNER JOIN #EmpLevel TL ON TL.EffectiveDate = EL.EffectiveDate AND TL.EmployeeId = EL.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpType TT ON TT.EffectiveDate = ET.EffectiveDate AND TT.EmployeeId = ET.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpDesignation TD ON TD.EffectiveDate = ED.EffectiveDate AND TD.EmployeeId = ED.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #EmpCategory TC ON TC.EffectiveDate = EC.EffectiveDate AND TC.EmployeeId = EC.EmployeeId '
	SET @Query = @Query + 'INNER JOIN #ExceptionEmployeeIds ExEmp ON ExEmp.ExceptionDate = IPD.[Date] AND ExEmp.EmployeeId = IPD.EmployeeCodeId '
	--SET @Query = @Query + 'WHERE IPD.PunchDifference > ''' + ISNULL(@MaxWorkPlaceIn, '00:03') + ''' AND E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 '
	SET @Query = @Query + 'WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 '
	SET @Query = @Query + 'AND IPD.[Date] BETWEEN CONVERT(DATETIME, ''' + CAST(@FromDate AS VARCHAR(11)) + ''', 102) AND CONVERT(DATETIME, ''' + CAST(@ToDate AS VARCHAR(11)) + ''', 102) '
	IF(@UserGroupName <> 'SuperAdmin')
	BEGIN
		SET @Query = @Query + CASE WHEN @EmpAutoId != 0 THEN 'AND G.Grade_Level >= ' + @GradeLevel + ' AND (E.Reporting_To = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''' OR E.Leave_Sanc_Authority = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''' OR E.Employee_Id = ''' + CAST(@EmpAutoId AS VARCHAR(30)) + ''') '
													ELSE 'AND (G.Grade_Level >= ' + @GradeLevel + ' OR E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''') ' END 
	END 
	IF NOT(@EmployeeName = '')  
	BEGIN
		SET @Query = @Query + 'AND (E.Employee_FirstName + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName + '%' AS NVARCHAR(100)) + ''') '
	END
	IF NOT(@EmployeeId = '')
	BEGIN
		SET @Query = @Query + 'AND (E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''') '
	END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @Query = @Query + 'AND EC.CategoryId = ' + CAST(@EmployeeCategory AS NVARCHAR(8)) + ' '
	END
	IF(@EmployeeType <> 0)
	BEGIN
		SET @Query = @Query + 'AND ET.TypeId = ' + CAST(@EmployeeType AS NVARCHAR(8)) + ' '
	END
	IF(@PunchType <> '')
	BEGIN
		SET @Query = @Query + 'AND IPD.EntranceType IN(' + @PunchType + ') '
	END	
    IF((@EmpAutoId = 0) AND (NOT(@LevelID = '' OR @LevelID = '0')))
	BEGIN
		SET @Query = @Query + 'AND (TL.levelId IN (' + @LevelID + ')) '
	END
	ELSE
	BEGIN
		SET @Query = @Query + 'AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds)) '  
	END	
	SET @Query = @Query + 'ORDER BY IPD.[Date], IPD.EmployeeCodeId'
	EXEC(@Query)
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory	
	DROP TABLE #EmployeeIds		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
-- Proc_TA_RptGAttendance '','','04/22/2005','04/22/2008','','','',''
--Proc_TA_RptGAttendance '','','01/01/2007','12/12/2009','',0,0,0,'SuperAdmin','1',''
--
CREATE PROCEDURE [dbo].[Proc_TA_RptGAttendance]
(
@EmployeeID VarChar(50), 
@LevelID VarChar(8000),
@FromDate VarChar(50), 
@ToDate VarChar(50), 
@EmployeeName varchar(50),
@shift int,
@EmployeeCategory int,
@EmployeeType int,
@UserGroupName varchar(250),
@GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @EmpAutoID int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	Declare @SelectSQL As Varchar(8000)
	Set @EmployeeName = @EmployeeName + '%'
	Set @SelectSQL = ' '  
	Set @SelectSQL = @SelectSQL + 'SELECT PD.Process_Rec_ID,ED.Employee_Code_Id AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '
    	Set @SelectSQL = @SelectSQL + 'replace(T.TitleName,''&amp;'',''&'')  AS Designation, '
	set @SelectSQL = @SelectSQL + 'replace(L.name,''&amp;'',''&'')  AS [Level Name],sh.Shift_StartTime,replace(sh.shift_shortName,''&amp;'',''&'') as shift_shortName, '	 
	Set @SelectSQL = @SelectSQL + 'CONVERT(varchar,Date ,101) AS Date, InTime,LateIn as LateBy,LateInMins,PD.LateEntryReason,DATENAME(Month,[Date]) AS ''Month'' FROM TA_Tbl_Employee ED  '
	Set @SelectSQL = @SelectSQL + 'INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + 'INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id '
	Set @SelectSQL = @SelectSQL + 'INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + 'INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId '
	SET @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'
	set @SelectSQL = @SelectSQL + ' inner join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
    set @SelectSQL = @SelectSQL + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
    set @SelectSQL = @SelectSQL + ' inner join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
    set @SelectSQL = @SelectSQL + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	--Set @SelectSQL = @SelectSQL + 'INNER JOIN Ta_Tbl_levelDetails L ON ED.LevelId = L.Id  '	
	Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_ProcessedData PD ON ED.SwipeCardNo = PD.Employee_Code_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id '
    Set @SelectSQL = @SelectSQL + ' Where '
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @SelectSQL = @SelectSQL + ' TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' AND '
	end
	if(@shift<>0)
	begin
		Set @SelectSQL = @SelectSQL + ' PD.shift_id= '+  cast (@shift as nvarchar(50))  + ' AND '
	end
	Set @SelectSQL = @SelectSQL + ' ( ED.Employee_Status = 1 or ( ED.Employee_Status = 0 and  convert(varchar(11), ED.InActiveDate,102) >= convert(varchar(11),getdate(),102))) AND (ED.Isdeleted = 0) AND (ED.report_exclude = 0)'
	Set @SelectSQL = @SelectSQL + ' and ED.Employee_FirstName + '' '' + isnull(ED.Employee_LastName,'''') like ''' + @EmployeeName + ''' '
	Set @SelectSQL = @SelectSQL + ' AND Lev.EffectiveDate=(select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId=ED.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	Set @SelectSQL = @SelectSQL + ' AND EDesig.EffectiveDate=(select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=ED.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'	
	set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
    set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	If Not (@EmployeeId = '' Or @EmployeeId = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Employee_code_Id = ''' + @EmployeeID + ''' '
	End
	if(@isReportingto > 0)
	BEGIN
		set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
	END
		If Not (@EmpSwipeCard = '')  
			 Begin  
			  Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			 End
	If (@EmployeeCategory <> 0)
		begin
			set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeCategory.CategoryId = ' +cast(@EmployeeCategory as nvarchar(8))
		end
	If (@EmployeeType <> 0)
		begin
			set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeType.TypeId = ' +cast(@EmployeeType as nvarchar(8))
		end
	If (@FromDate <> '')
	Begin
		Set @SelectSQL = @SelectSQL + 'And PD.Date >= ''' + @FromDate + ''' '
	End
	If (@ToDate <> '')
	Begin
		Set @SelectSQL = @SelectSQL + 'And PD.Date <= ''' + @ToDate + ''' '
	End
	if not(@LevelID='' or @LevelID='0')
		Begin
			set @SelectSQL = @SelectSQL + ' and (Lev.LevelId IN (' + @LevelID + ')) '
		End
	set @SelectSQL = @SelectSQL + ' order by ED.Employee_Code_Id,pd.Date , pd.Intime'
	exec (@SelectSQL)
	End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGeneralMonthlyAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Proc_TA_RptGeneralMonthlyAttendance '787','2020/06/01','2020/07/01','','0',0,0,'superadmin','0',0,0,'Both',0,0

exec Proc_TA_RptGeneralMonthlyAttendance @DesignationID=N'0',@fromDat=N'05-02-2024 00:00:00',@Gender=N'Both',
@EmployeeId=N'BB002',@EmpAutoId=N'0',@EmployeeName=N'',@shift=N'0',@MinWorkHours=N'',@GradeLevel=N'0',@UserGroupName=N'SuperAdmin'
,@Export=N'0',@EmpSwipeCard=N'',@LevelID=N'37',@employeeType=N'0',@ParentId=N'37',@ToDat=N'05-02-2024 00:00:00',@employeeCategory=N'0',
@DataLoading=N'0'

*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptGeneralMonthlyAttendance]
(   
	@EmployeeId varchar(max),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),	
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@ShiftId int,
	@EmpAutoID int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  
	

	--Set @fromDat= CONVERT(Datetime, @fromDat,105);
	--Set @ToDat= CONVERT(Datetime, @ToDat,105);

	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=CONVERT(Datetime, @fromDat,105)
	set @local_ToDate=CONVERT(Datetime, @ToDat,105)
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@ShiftId
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoId=@EmpAutoId
	
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),
		HrsWork nvarchar(10),LateInmin nvarchar(10),EarlyOutMin nvarchar(10),
		Inpunch varchar(20),Outpunch varchar(20),Indate datetime,Outdate datetime,
		Excess varchar(10),Remarks nvarchar(max)
		,FNAttendanceCode nvarchar(30),ANAttendanceCode nvarchar(30),ExcessMins varchar(10),HrsLess varchar(10),
		BreakHours int default(0),LunchHours int default(0),BreakHoursMins int,LunchHoursMins int,isNightShift bit default(0),
		ShftShrtName varchar(100)
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId  
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	if(@local_Gender<>'Both')  
		begin  
			set @sqlCommon = @sqlCommon + ' and Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '  
		end	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 '
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@local_EmployeeID = '')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
			End
	If Not (@local_EmployeeName = '')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
			End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_ToDate,@local_EmployeeID,@local_DesignationID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_ToDate,@local_EmployeeID,@local_employeeType
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	Declare @sqlTempProcessedData1 varchar(max)
	insert into #TempProcessedData 
	select	EmployeeId,
			P.Date,
			P.Employee_Code_Id,
			P.InTime,
			P.OutTime,
			P.HrsWork,
			LateInMins,
			case when charindex('.',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex('.',convert(varchar(20),EarlyOutmins))))
				 else EarlyOutmins 
			end,
			Inpunch,
			Outpunch,
			Indate,
			Outdate,
			HrsExtra,'',
			FNAttendanceCode,
			ANAttendanceCode,
			ExtraMins,
			HrsLess,
			isnull(BreakHrsInmins,0),
			isnull(LunchHrsInmins,0),
			BreakHrsInmins,
			LunchHrsInmins,
			case	when SUBSTRING(S.Shift_StartTime,7,8)='PM' and SUBSTRING(S.Shift_Endtime,7,8)='AM' then 1 			
					else 0 
			end,
			case when P.Shift_Id!=-1 then S.Shift_Shortname+' ('+S.Shift_StartTime+'-'+S.Shift_EndTime+')'
			else '-'
			end
	from TA_Tbl_ProcessedData P inner join 
	#EmpLevel on #EmpLevel.SwipeCard=P.Employee_Code_Id  
	left outer join ta_tbl_shift S on S.Shift_Id=P.Shift_Id	
	where ProcessFlag=1 and (P.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102))
	and (@local_shift=0 or (@local_shift!=0 and P.Shift_id=CONVERT(varchar(5),@local_shift)))
	
	create table #TempMonthlyAttendance
	(
		Employee_Id varchar(25),empName varchar(500),
		Designation varchar(250),Date datetime,InTime varchar(30),OutTime varchar(30),HrsWork varchar(30),
		lateinMin nvarchar(10),EarlyOutMin nvarchar(10),
		Inpunch varchar(20),Outpunch varchar(20),Indate datetime,Outdate datetime,
		Excess varchar(10),Remarks nvarchar(max),TotalMinsWorked int default(0),ExcessMins int,HrsLessExist int
		,HrsLessMins int,BreakHours int default(0),LunchHours int default(0)
		,BreakHoursMins int,LunchHoursMins int,manualIndate datetime,manualoutdate datetime,
		EmployeeAutoId int,ShftShrtName varchar(100),
		ManualInExist bit,ManualInStatus varchar(100),
		ManualOutExist bit,ManualOutStatus varchar(100)
	)
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''    	
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,
							isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,
							replace(T.TitleName,''&amp;'',''&'') as Designation,
							pd.date as Date,
							pd.InTime,
							pd.OutTime,
							pd.HrsWork,
							LateInMin,
							EarlyOutMin,
							Inpunch,
							Outpunch,
							Indate,
							Outdate,
							case when Excess=''00:00'' and HrsLess<>''00:00'' then ''-'' + HrsLess else Excess end,
							case 
								when	FNAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'') 
										and ANAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'')then FNAttendanceCode
								when	FNAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'') 
										and ANAttendanceCode in(''absent'')then ANAttendanceCode+'' / ''+''Half day - ''+FNAttendanceCode +'' (Approved)''
								when	FNAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'') 
										and ANAttendanceCode not in(''absent'')then ''Half day - ''+FNAttendanceCode +'' (Approved)''
								when	FNAttendanceCode in(''absent'') 
										and ANAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'')then FNAttendanceCode+'' / ''+''Half day - ''+ANAttendanceCode+'' (Approved)''
								when	FNAttendanceCode not in(''absent'') 
										and ANAttendanceCode not in(''Present'',''absent'',''Weekly Off'',''Holiday'',''RH'')then ''Half day - ''+ANAttendanceCode+'' (Approved)''
								when	FNAttendanceCode=''Absent'' and ANAttendanceCode=''Absent'' then ''Absent''
								when	FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then ''Holiday''
								when	FNAttendanceCode=''RH'' and ANAttendanceCode=''RH'' then ''Holiday''
								when	FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' then ''Weekly Off''
								else ''''
							end	
							Remarks,
							case when HrsWork is null then 0 
								 else ((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) 
							end as TotalMinsWorked,
							ExcessMins,
							case when Excess=''00:00'' and HrsLess<>''00:00'' then 1 
								 else 0 
							end,
							substring(hrsless,0,charindex('':'',hrsless))*60+substring(hrsless,charindex('':'',hrsless)+1,LEN(hrsless))%60, 
							BreakHours,
							LunchHours,
							BreakHoursMins,
							LunchHoursMins,
							date,
							case when isNightShift=1 then dateadd(d,1,date)
								 else date
							end,e.Employee_Id,ShftShrtName,'''','''','''','''' '
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	SET @SQLQUERY = @SQLQUERY + ' WHERE 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, ''' + CAST(@local_FromDate AS NVARCHAR(11)) + ''', 102) AND PD.DATE <= CONVERT(DATETIME, ''' + CAST(@local_ToDate AS NVARCHAR(11)) + ''', 102)))'
	if(@local_UserGroupName<>'SuperAdmin')  
		begin  
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel + ''  
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'	
	insert into #TempMonthlyAttendance 
	exec(@sqlQuery)
	--select * from #TempMonthlyAttendance 
	update #TempMonthlyAttendance set Remarks=	case 
													 when tpd.Remarks=lt.LeaveType then lt.LeaveType + ' (Approved)'
													else tpd.Remarks 
												end from #TempMonthlyAttendance tpd
	inner join TA_Tbl_LeaveType LT on tpd.Remarks=lt.LeaveType where Remarks!='' and Remarks is not null	
	update #TempMonthlyAttendance set Remarks=case when TM.Remarks!='' then TM.Remarks+' / '+ lt.Leavetype +'-'+LAE.status
	else lt.Leavetype +'-'+LAE.status
	end from #TempMonthlyAttendance TM
	inner join ta_tbl_leaveapplicationexists LAE on LAE.Employee_Id=TM.EmployeeAutoId
	inner join ta_tbl_leaveapplication LA on LA.LeaveApplication_Id=LAE.LeaveApplicationId
	inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
	and Tm.Date=LAE.Leave_FromDate and LAE.status not in('Approved','Rejected') and LAE.isDeleted=0	
	--if manual in or out exists then should show the proper remarks.
	update #TempMonthlyAttendance set ManualInExist=1,ManualInStatus=ManualTimeEntry_Status
	from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and ((ManualTimeEntry_InDate=tpd.manualIndate))
	and MTE.ManualTimeEntry_Status!='Rejected' and MTE.isdeleted=0
	update #TempMonthlyAttendance set ManualOutExist=1,ManualOutStatus=ManualTimeEntry_Status
		from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and (ManualTimeEntry_OutDate)=tpd.manualoutdate 
	and MTE.ManualTimeEntry_Status!='Rejected' and MTE.isdeleted=0	
	--Manual Time Entry validation
	update #TempMonthlyAttendance set Remarks=
	case	when ManualInStatus='Pending' and ManualOutStatus='Pending' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending'
								else 'Manual Time Entry - Pending'
								end
				when ManualInStatus='Pending' and ManualOutStatus='Forwarded' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending,Forwarded'
								else 'Manual Time Entry - Pending,Forwarded'
								end
				when ManualInStatus='Pending' and ManualOutStatus='Approved' then  --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending'
								else 'Manual Time Entry - Pending'
								end
				when ManualInStatus='Pending' and ManualOutStatus='' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending'
								else 'Manual Time Entry - Pending'
								end
				when ManualInStatus='' and ManualOutStatus='Pending' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending'
								else 'Manual Time Entry - Pending'
								end
				when ManualInStatus='Forwarded' and ManualOutStatus='Pending' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded,Pending'
								else 'Manual Time Entry - Forwarded,Pending'
								end
				when ManualInStatus='Forwarded' and ManualOutStatus='Forwarded' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded'
								else 'Manual Time Entry - Forwarded'
								end
				when ManualInStatus='Forwarded' and ManualOutStatus='Approved' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded'
								else 'Manual Time Entry - Forwarded'
								end
				when ManualInStatus='Forwarded' and ManualOutStatus='' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded'
								else 'Manual Time Entry - Forwarded'
								end
				when ManualInStatus='' and ManualOutStatus='Forwarded' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded'
								else 'Manual Time Entry - Forwarded'
								end								
				when ManualInStatus='Approved' and ManualOutStatus='Pending' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Pending'
								else 'Manual Time Entry - Pending'
								end
				when ManualInStatus='Approved' and ManualOutStatus='Forwarded' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Forwarded'
								else 'Manual Time Entry - Forwarded'
								end
				when ManualInStatus='Approved' and ManualOutStatus='Approved' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Approved'
								else 'Manual Time Entry - Approved'
								end
				when ManualInStatus='' and ManualOutStatus='Approved' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Approved'
								else 'Manual Time Entry - Approved'
								end
				when ManualInStatus='Approved' and ManualOutStatus='' then --Completed
								case when tpd.Remarks!='' then tpd.Remarks+' / Manual Time Entry - Approved'
								else 'Manual Time Entry - Approved'
								end
				else
								case when tpd.Remarks!='' then tpd.Remarks								
								end
	end
	from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and ((ManualTimeEntry_InDate=tpd.manualIndate) or (ManualTimeEntry_OutDate=tpd.manualoutdate))
	and MTE.ManualTimeEntry_Status!='Rejected' and MTE.isdeleted=0	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	select		
		Employee_Id,
		empName,
		Designation,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		Inpunch,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Indate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Indate, @dateFormat) 
		end AS Indate,	
		case when InTime<>'00:00' then
					case	when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114),0,6)
							else	case	when len(SUBSTRING(intime,0,charindex(':',intime)))=1 then '0'+intime
											else InTime 
									end
					end
			else '' 
		end	InTime,
		Outpunch,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Outdate,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Outdate, @dateFormat) 
		end AS Outdate,
		case when OutTime<>'00:00' then
					case	when (@TimeFormat)='hh:mm' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114),0,6)
							else	case	when len(SUBSTRING(OutTime,0,charindex(':',OutTime)))=1 then '0'+OutTime
											else OutTime 
									end
					end
			else ''
		end OutTime,
		case	when InTime IS null and OutTime is null then '-' 
				when InTime ='' and OutTime ='' then '-'				
				when InTime ='00:00' and OutTime ='00:00' then '-'
				when InTime !='' and OutTime ='' then '-'
				when InTime is not null and OutTime is null then '-'
				when InTime ='' and OutTime !='' then '-'
				when InTime is null and OutTime is not null then '-'
				else HrsWork
		end as HrsWork,
		case	when InTime IS null and OutTime is null then '-' 
				when InTime ='' and OutTime ='' then '-'
				when InTime ='00:00' and OutTime ='00:00' then '-'				
				when InTime !='' and OutTime ='' then '-'
				when InTime is not null and OutTime is null then '-'
				when InTime ='' and OutTime !='' then '-'
				when InTime is null and OutTime is not null then '-'
				else Excess 
		end as Excess,
		case when CHARINDEX('/',
		case	when convert(int,lateinMin)>0		then 'Late In / '				
					else '' 
		end + ''+
		case	when convert(int,EarlyOutMin)>0	then 'Early Exit / '
					else '' 
		end + ''+
		case	when convert(int,HrsLessMins)>0	then 'Less Hours Worked / '
					else '' 
		end + ''+
		case	when (InTime is not null and OutTime is null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when (InTime is null and OutTime is not null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when InTime IS null and OutTime is null and Remarks='' then '-' 
					when InTime ='' and OutTime ='' and Remarks='' then '-'
					else Remarks
		end,		
		LEN(
		case	when convert(int,lateinMin)>0		then 'Late In / '				
					else '' 
		end + ''+
		case	when convert(int,EarlyOutMin)>0	then 'Early Exit / '
					else '' 
		end + ''+
		case	when convert(int,HrsLessMins)>0	then 'Less Hours Worked / '
					else '' 
		end + ''+
		case	when (InTime is not null and OutTime is null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when (InTime is null and OutTime is not null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when InTime IS null and OutTime is null and Remarks='' then '-' 
					when InTime ='' and OutTime ='' and Remarks='' then '-'
					else Remarks
		end))!=0 then
		SUBSTRING(case	when convert(int,lateinMin)>0		then 'Late In / '				
					else '' 
		end + ''+
		case	when convert(int,EarlyOutMin)>0	then 'Early Exit / '
					else '' 
		end + ''+
		case	when convert(int,HrsLessMins)>0	then 'Less Hours Worked / '
					else '' 
		end + ''+
		case	when (InTime is not null and OutTime is null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when (InTime is null and OutTime is not null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when InTime IS null and OutTime is null and Remarks='' then '-' 
					when InTime ='' and OutTime ='' and Remarks='' then '-'
					else Remarks
		end,0,len(case	when convert(int,lateinMin)>0		then 'Late In / '				
					else '' 
		end + ''+
		case	when convert(int,EarlyOutMin)>0	then 'Early Exit / '
					else '' 
		end + ''+
		case	when convert(int,HrsLessMins)>0	then 'Less Hours Worked / '
					else '' 
		end + ''+
		case	when (InTime is not null and OutTime is null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when (InTime is null and OutTime is not null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when InTime IS null and OutTime is null and Remarks='' then '-' 
					when InTime ='' and OutTime ='' and Remarks='' then '-'
					else Remarks
		end)-1)
		else
		case	when convert(int,lateinMin)>0		then 'Late In / '				
					else '' 
		end + ''+
		case	when convert(int,EarlyOutMin)>0	then 'Early Exit / '
					else '' 
		end + ''+
		case	when convert(int,HrsLessMins)>0	then 'Less Hours Worked / '
					else '' 
		end + ''+
		case	when (InTime is not null and OutTime is null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when (InTime is null and OutTime is not null) then 'Missing Punch / '
					else ''
	    end+''+
		case	when InTime IS null and OutTime is null and Remarks='' then '-' 
					when InTime ='' and OutTime ='' and Remarks='' then '-'
					else Remarks
		end
		end		
		as Remarks,
		convert(int,lateinMin)as lateinMin,
		convert(int,EarlyOutMin)as EarlyOutMin,
		Date as format,			
		TotalMinsWorked,
		ExcessMins,
		HrsLessExist,
		isnull(HrsLessMins,0)HrsLessMins,
		BreakHoursMins,				
		case	when (BreakHours Is null Or BreakHours='') then '-' 
				else	case	when LEN(BreakHours/60)=1 then '0'+(CONVERT(varchar(10),(BreakHours/60)))
								else (CONVERT(varchar(10),(BreakHours/60))) 
						end 
						+':'+
						case	when len(BreakHours%60)=1 then '0'+CONVERT(varchar(10),(BreakHours%60))
								else CONVERT(varchar(10),(BreakHours%60)) 
						end 
		end as BreakHours,
		ShftShrtName,
		LunchHoursMins,
		case	when (LunchHours Is null Or LunchHours='') then '-' 
				else	case	when len(LunchHours/60)=1 then '0'+convert(varchar(10),(LunchHours/60))
								else convert(varchar(10),(LunchHours/60)) 
						end 
						+':'+
						case	when LEN(LunchHours%60)=1 then '0'+ CONVERT(varchar(10),(LunchHours%60))
								else CONVERT(varchar(10),(LunchHours%60)) 
						end 
		end as LunchHours					
		from #TempMonthlyAttendance 		
		order by Employee_Id,format 
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	drop table #TempMonthlyAttendance	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGetEmailLog]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-02-2013
-- Description:	Get the Email Log Details
-- [dbo].[Proc_TA_RptGetEmailLog] 34,1,'2013/01/01','2013/01/16','0'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptGetEmailLog]
	-- Add the parameters for the stored procedure here
	@Reportid INT,
	@Frequency INT,
	@Fromdate DATETIME,
	@Todate DATETIME,
	@CreatedBy BIGINT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	Create table #TempScheduleIDs(Scheduleid bigint,row int) 	
	CREATE TABLE #TempMailIds(Scheduleid BIGINT,Tomail NVARCHAR(max),CCmail NVARCHAR(max))		
	Insert into #TempScheduleIDs select ScheduleId,ROW_NUMBER()over(order by scheduleid) from TA_Tbl_EmailSchedule where IsDeleted=1
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	Declare @CountIds int
	Declare @i int
	DECLARE @ToEmailList VARCHAR(8000)	
	DECLARE @CCEmailList VARCHAR(8000)	
	Declare @ScheduleId bigint
	set @i=1
	set @CountIds=(select COUNT(scheduleid)from #TempScheduleIDs)
	while @CountIds>0
		begin		
			select @ScheduleId=scheduleid from #TempScheduleIDs where row=@i			
			SELECT @ToEmailList = COALESCE(@ToEmailList + '; ', '') + CAST(EmailID AS VARCHAR)
			FROM   TA_tbl_MailIdsForTriggeringEmail
			WHERE  ScheduleId = @ScheduleId and MailType = 'To'				
			SELECT @CCEmailList = COALESCE(@CCEmailList + '; ', '') + CAST(EmailID AS VARCHAR)
			FROM   TA_tbl_MailIdsForTriggeringEmail
			WHERE  ScheduleId = @ScheduleId and MailType = 'CC'	
			set @CCEmailList=SUBSTRING(@CCEmailList,1,LEN(@CCEmailList))
			set @ToEmailList=SUBSTRING(@ToEmailList,1,LEN(@ToEmailList))
			insert into #TempMailIds values(@ScheduleId,@ToEmailList,@CCEmailList)
			set @ToEmailList=Null
			set @CCEmailList=Null			
			set @i=@i+1			
			set @CountIds=@CountIds-1
		end	
	--select * from #TempMailIds 
    -- Insert statements for procedure here    
    DECLARE @SQLQUERY NVARCHAR(MAX)
    SET @SQLQUERY	=	'SELECT 
						case when '+cast(@dateFormat as varchar(100))+'=106 then
											      REPLACE(CONVERT(VARCHAR, Sentdate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
											 else CONVERT(VARCHAR, Sentdate, '+cast(@dateFormat as varchar(100))+')
											end as ScheduleDate,
						ScheduleName,
						case when (ESS.Status<> 0 and ESS.Status is not null and ESS.Status<>'''') then 
										case when '+cast(@dateFormat as varchar(100))+'=106 then
											      REPLACE(CONVERT(VARCHAR, Sentdate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
											 else CONVERT(VARCHAR, Sentdate, '+cast(@dateFormat as varchar(100))+')
											end 
							 else '' '' end as actual,
						Employee_FirstName +'' ''+ Employee_LastName AS CreatedBy,
						case when '+cast(@dateFormat as varchar(100))+'=106 then
								  REPLACE(CONVERT(VARCHAR, DurationFrom,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
							 else CONVERT(VARCHAR, DurationFrom, '+cast(@dateFormat as varchar(100))+')							 
							 end as DurationFrom,
						case when '+cast(@dateFormat as varchar(100))+'=106 then
								  REPLACE(CONVERT(VARCHAR, DurationTo,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
							 else CONVERT(VARCHAR, DurationTo, '+cast(@dateFormat as varchar(100))+')							 
							 end as DurationTo,
						Tomail,
						CCMail,
						case when ESS.Status=0 then ''Pending'' when ESS.Status=1 then ''Send'' end AS STATUS 
						FROM TA_Tbl_EmailSchedule ES inner join #TempMailIds MT ON Es.ScheduleId=MT.ScheduleId 
						LEFT OUTER JOIN TA_tbl_EmailScheduleStatus ESS ON ES.ScheduleId=ESS.ScheduleId 
						INNER JOIN TA_Tbl_Employee E ON ES.EmployeeId=E.Employee_Id 
						LEFT OUTER JOIN Ta_tbl_EmailReportNotSendedDetails ERNS on ES.ScheduleId=ERNS.Id and ERNS.AraisedFrom=''Email'''	
	SET @SQLQUERY	=	@SQLQUERY + ' WHERE 1=1 '	
	IF @Reportid is not null and @Reportid<>'' AND @Reportid<>0
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + ' AND ES.Reportid='+cast (@Reportid as nvarchar(50))+''
		END	
	IF @Frequency = 1
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + ' AND ES.Frequency=''Daily'''
		END	
	IF @Frequency = 2
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + ' AND ES.Frequency=''Weekly'''
		END	
	IF @Frequency = 3
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + ' AND ES.Frequency=''Monthly'''
		END	
	IF @CreatedBy IS NOT NULL AND @CreatedBy<>''
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + ' AND E.Employee_id='+@CreatedBy+'' 
		END
	IF ((@Fromdate IS NOT NULL AND @Fromdate<>'') AND (@Todate IS NOT NULL AND @Todate <>''))
		BEGIN
			set @sqlQuery = @sqlQuery + ' and((sentDate >= CONVERT(DATETIME, ''' + cast(@Fromdate as nvarchar(11)) + ''', 102) and sentDate <= CONVERT(DATETIME, ''' + cast(@toDate as nvarchar(11)) + ''', 102)))'
		END
	EXECUTE(@SQLQUERY)
	DROP TABLE #TempMailIds 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_TA_RptGettingNearShiftDetailsUsingInpunch '2017/03/01','','',0,0,'superadmin',0,0,0,'both',0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]
	-- Add the parameters for the stored procedure here
	@FROMDAT DATETIME,	
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@SHIFT INT,	
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		CompanyId int,
		AllocatedShiftStartTime varchar(10)		
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_EMPLOYEE_CODE_ID] ON [DBO].[#TEMPPROCESSEDDATA]([DATE],[EMPLOYEE_CODE_ID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @FROMDAT,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @FROMDAT,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @FROMDAT,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@FROMDAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	'INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID ' 
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id '
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0'
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	SET @SQLTEMPPROCESSEDDATA1=
	'INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	TE.EMPAUTOID,
			PD.DATE,
			PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			[dbo].[Func_TA_GetParentIds](TE.LEVELID),
			S.SHIFT_STARTTIME
	FROM TA_TBL_PROCESSEDDATA PD INNER JOIN #TEMPEMPLOYEE TE ON TE.EMPSWIPECARDNO=PD.EMPLOYEE_CODE_ID  	
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=PD.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (PD.DATE= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))and intime is not null and intime<>''00:00'' ' 
	IF(@SHIFT<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + ' AND PD.SHIFT_ID= '+  CAST (@SHIFT AS NVARCHAR(50))
		END
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	--select * from #TEMPPROCESSEDDATA
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		AllocatedShiftStartTime varchar(10),
		CloseShifts varchar(max),
		CompanyId int,
		Gender varchar(10),
		ClosestShiftID int,
		EmployeeAutoID bigint
	)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	E.EMPLOYEE_CODE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&''),
	REPLACE(T.TITLENAME,''&AMP;'',''&''),
	CONVERT(VARCHAR(20),PD.DATE,101),
	PD.INTIME,PD.AllocatedShiftStartTime,
	[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,1,DATE),
	CompanyId,E.Gender,
	(select top 1 ShiftID from [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime](CompanyId,DATE+intime,1,DATE))
	,E.Employee_ID'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     	
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId '
	SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)
		AND(PD.DATE = CONVERT(DATETIME, ''' + CAST(@FROMDAT AS NVARCHAR(11)) + ''', 102))'    
	IF(@GENDER<>'BOTH')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND E.GENDER = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' '  
		END	
	if(@EmpAutoId > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	IF(@USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @GRADELEVEL + ''  
		END	
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	 --Get current date time format.
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(20)
	DECLARE @TimeFormat as nvarchar(10)
	SELECT @date=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat() --TimeFormat FROM TA_Tbl_DateandTimeFormat
      IF(@date='dd/MM/yyyy')
            BEGIN
                  SET @dateFormat = 103
            END
      ELSE IF(@date='MM/dd/yyyy')
            BEGIN
                  SET @dateFormat = 101
            END
      ELSE
            BEGIN
                  SET @dateFormat = 106
            END 
	update TM set CloseShifts=
	case	when	([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)='') or 
					([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE) is null)then 
					CloseShifts
			else CloseShifts+';'+[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)
	end from #TEMPMONTHLYATTENDANCE TM
	select
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,
		BRANCHNAME Level,
		DESIGNATION Title,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		case when Intime<>'00:00' then
					CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
							ELSE SUBSTRING(InTime,13,5)+' ' + SUBSTRING(InTime,18,2)
					END
			else '' 
		end
		ActualShiftIn,		
		case	when (@TimeFormat)='hh:mm' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,AllocatedShiftStartTime,0)), 114)
				else	SUBSTRING(InTime,13,5)+' ' + SUBSTRING(AllocatedShiftStartTime,18,2) 
		end AllocatedShift,
		CloseShifts NearestShift,Gender,CompanyId,DATE as Format,ClosestShiftID ShiftID,EmployeeAutoID
	from #TEMPMONTHLYATTENDANCE order by EMPLOYEE_ID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_RptHeadCountDetails] '22-Jun-11','SuperAdmin','0',1
CREATE PROCEDURE [dbo].[Proc_TA_RptHeadCountDetails]          
	@Date datetime,      
	@UserGroupName varchar(250),      
	@ParentId int,
	@ShiftId int,
	@EmpAutoID int 
AS    
BEGIN    
	-- SET NOCOUNT ON added to prevent extra result sets from    
	-- interfering with SELECT statements.    
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
	create table #LevelRights(LevelId int)    
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id nvarchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,HrsWork nvarchar(10),Status nvarchar(50),Attendance nvarchar(20),anAttendanceCode nvarchar(15),fnAttendanceCode nvarchar(15))  
	create table #TempHeadCountDetails(EmployeeId nvarchar(50),EmpName nvarchar(150),OrgLevel nvarchar(255),FirstSession nvarchar(20),SecondSession nvarchar(20),ShiftName nvarchar(100))  
	--#TempProcessedData Indexes  	
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId        
	--Employee Level insert in Temporary table  
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId  
	where emp.Isdeleted=0 group by EmployeeId) ELevel  
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102) and EL.LevelId is not null  
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id  
	where SwipeCardNo is not null  
	--select * from #TempEmployee  
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork,
	TA_Tbl_ProcessedData.Status,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.anAttendanceCode,TA_Tbl_ProcessedData.fnAttendanceCode   
	from TA_Tbl_ProcessedData   
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id  
	where dbo.TA_Tbl_ProcessedData.Date = CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102)    
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''    
	set @sqlQuery = 'insert into #TempHeadCountDetails select e.Employee_Code_Id as EmployeeId,isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as EmpName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as OrgLevel,'
	set @sqlQuery = @sqlQuery + 'pd.fnAttendanceCode as FirstSession,'  
	set @sqlQuery = @sqlQuery + ' pd.anAttendanceCode as SecondSession '
	set @sqlQuery = @sqlQuery + ',shf.Shift_Name + '' ('' + shf.Shift_StartTime + '' - '' + shf.Shift_EndTime + '')''  as ShiftName '  
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'
	Set @sqlQuery = @sqlQuery + ' INNER JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id '
	set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and pd.date = CONVERT(DATETIME, ''' + cast(@Date as nvarchar(11)) + ''', 102) '    
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@ShiftId<>0)  
		begin  
			Set @sqlQuery = @sqlQuery + ' AND pd.shift_id= '+  cast (@ShiftId as nvarchar(50))  + ''  
		end  
	exec(@sqlQuery)  
	declare @Shift_FirstHalf_StartTime as varchar(50)
	declare @Shift_SecondHalf_StartTime as varchar(50)
	declare @FirstHalf_StartTime as varchar(50)
	declare @SecondHalf_StartTime as varchar(50)
	select @Shift_FirstHalf_StartTime=substring(Shift_FirstHalf_StartTime,7,2),@FirstHalf_StartTime=Shift_FirstHalf_StartTime,
	@Shift_SecondHalf_StartTime=substring(Shift_SecondHalf_StartTime,7,2),@SecondHalf_StartTime=Shift_SecondHalf_StartTime from ta_tbl_shift where shift_id=@ShiftId
	if(@Shift_FirstHalf_StartTime='PM' and @Shift_SecondHalf_StartTime='AM')
		begin
			set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
			set @Shift_SecondHalf_StartTime=CONVERT(varchar,dateadd(d,1,@Date) , 101) + space(1) + @SecondHalf_StartTime	
		end
	else
		begin
			set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
			set @Shift_SecondHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @SecondHalf_StartTime		
		end
	if (getdate()<cast(@Shift_SecondHalf_StartTime as datetime))
		begin
			update #TempHeadCountDetails set SecondSession='Not Started' where SecondSession='Absent'
		end
	if (getdate()<cast(@Shift_FirstHalf_StartTime as datetime))
		begin
			update #TempHeadCountDetails set FirstSession='Not Started' where FirstSession='Absent'
		end
	select * from #TempHeadCountDetails
	--Remove the temporary tables here 
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #TempEmployee
	drop table #TempHeadCountDetails        
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountDetailSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>

-- Proc_TA_RptHeadCountDetailSummary @shiftID=2,@shiftDate='2023-04-01'
CREATE PROCEDURE [dbo].[Proc_TA_RptHeadCountDetailSummary] 
	-- Add the parameters for the stored procedure here
	@shiftID int,
	@shiftDate datetime
	--@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	Declare @ShiftDay varchar(20)
	Set @ShiftDay=DAY(@shiftDate)

	--print @ShiftDay

	Declare @PermanentShiftEmployee as Table (EmployeeId int,ParentId int)

	Declare @sqlquery varchar(Max)

	set @sqlquery='Select ps.EmployeeId,([dbo].[Func_TA_GetParentIds](empl.LevelId)) as LevelID From TA_Tbl_PermanentShiftAllocation PS inner join TA_Tbl_EmployeeLevel empl on ps.EmployeeId=empl.EmployeeId where Day'+@ShiftDay+'Shift='+Convert(varchar(2), @shiftID)

	insert into @PermanentShiftEmployee Exec(@sqlQuery)

	

	Declare @organizationId int

	Set @organizationId= (Select distinct ParentId From @PermanentShiftEmployee)

	Declare @LevelDetails as Table (Id int,levelId int,parentId int,name varchar(200))
	
	Insert into @LevelDetails
	Select ID,levelId,parentId,name  From Ta_Tbl_levelDetails l inner join (select * from [dbo].[fn_TA_GetParentChild]('Superadmin',@organizationId)) as l1 on l1.ParentChildId=l.id where l.isDeleted=0


    -- Insert statements for procedure here
	Declare @tempTbl As Table (ID int identity(1,1),OrgName varchar(100),BranchName varchar(100),DeptID int,DeptName varchar(100))


	Insert into @tempTbl
	select  org.name as OrgName, brn.name as BranchName, dep.id as DeptID, dep.name as DeptName  from 
	(select * from @LevelDetails where levelId = 1) org inner join
	(select * from @LevelDetails where levelId = 2) brn on org.id = brn.parentId inner join 
	(select * from @LevelDetails where levelId = 3) dep on brn.id = dep.parentId 


	Declare @tempCount int 

	Set @tempCount= (Select  Count(*) From @tempTbl)

	Declare @TempEmployee As Table (ID int Identity(1,1),NoofEmployee int,PresentFN int,PresentAN int,AbsentFN int,AbsentAN int,LeaveFN int,LeaveAN int,LOPFN int,LOPAN int)
	
	Declare @count int=1

	while (@count<=@tempCount)
	begin

	
	--Declare @EmployeeCount int

		insert into @TempEmployee(NoofEmployee) 
    Select Count(distinct emp.Employee_Id)as NofEmployee From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId  where tmp.ID=@count 
	
		update @TempEmployee set PresentFN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.FNAttendanceCode having pd.FNAttendanceCode='Present') 
	where ID=@count

		update @TempEmployee set PresentAN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.ANAttendanceCode having pd.ANAttendanceCode='Present') 
	where ID=@count

		update @TempEmployee set AbsentFN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.FNAttendanceCode having pd.FNAttendanceCode='Absent') 
	where ID=@count

	update @TempEmployee set AbsentAN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.ANAttendanceCode having pd.ANAttendanceCode='Absent') 
	where ID=@count

	update @TempEmployee set LeaveFN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.FNAttendanceCode having pd.FNAttendanceCode!='LOP' and pd.FNAttendanceCode!='Present' and pd.FNAttendanceCode!='Absent') 
	where ID=@count

		update @TempEmployee set LeaveAN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.ANAttendanceCode having pd.ANAttendanceCode!='LOP' and pd.ANAttendanceCode!='Present' and pd.ANAttendanceCode!='Absent') 
	where ID=@count


		update @TempEmployee set LOPFN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.FNAttendanceCode having pd.FNAttendanceCode='LOP') 
	where ID=@count

		update @TempEmployee set LOPAN=
	(Select  Count(distinct emp.Employee_Code_Id) From TA_Tbl_Employee  emp inner Join TA_Tbl_EmployeeLevel emplevel on emplevel.EmployeeId=emp.Employee_Id 
	inner Join @tempTbl tmp on tmp.DeptID=emplevel.LevelId inner join TA_Tbl_ProcessedData PD on pd.Employee_Code_Id=emp.Employee_Code_Id where pd.Date=@shiftDate and pd.Shift_Id=@shiftID  and tmp.ID=@count
	group by pd.ANAttendanceCode having pd.ANAttendanceCode='LOP') 
	where ID=@count

		--print @EmployeeCount

		set @count=@count+1
		--print @count

	End

	Select tb1.ID,tb1.OrgName,tb1.BranchName,tb1.DeptName,tb.NoofEmployee,tb.PresentFN,tb.PresentAN,tb.AbsentFN,tb.AbsentAN,tb.LeaveFN,tb.LeaveAN,tb.LOPFN,tb.LOPAN From @TempEmployee tb inner Join @tempTbl tb1 on tb1.ID=tb.ID

	--select Shift_Name + ' (' + Shift_StartTime + ' - ' + Shift_EndTime + ')'  as ShiftName from ta_tbl_shift where shift_id=@ShiftId

END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_RptHeadCountSummary '14/Sep/2016','SuperAdmin',0,2,0,15
/*
exec Proc_TA_RptHeadCountSummary @Date=N'05-02-2024 00:00:00',@shiftId=N'14',@ExportType=N'1',
@EmpAutoId=N'0',@ParentId=N'37',@UserGroupName=N'SuperAdmin'
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptHeadCountSummary]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int,
 @ShiftId int,
 @ExportType int,
 @EmpAutoID int
)    
AS      
BEGIN   


Set @Date=CONVERT(Datetime, @Date,105)

create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
--select * from #tempProcessSecSummary
CREATE TABLE #TempProcessedData(
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Date] [datetime] NULL,
	[Shift_Id] [int] NULL,
	[InTime] [nvarchar](25) NULL,
	[OutTime] [nvarchar](25) NULL,
	[HrsWork] [nvarchar](10) NULL,
	[HrsOT] [nvarchar](10) NULL,
	[NormOT] [nvarchar](10) NULL,
	[OffOT] [nvarchar](10) NULL,
	[HolOT] [nvarchar](10) NULL,
	[EarlyOut] [nvarchar](10) NULL,
	[LateIn] [nvarchar](10) NULL,
	[Attendance] [nvarchar](20) NULL,
	[WorkHrs] [nvarchar](10) NULL,
	[HrsLess] [nvarchar](10) NULL,
	[HrsExtra] [nvarchar](10) NULL,
	[LateInMins] [float] NULL,
	[EarlyOutMins] [float] NULL,
	[ExtraMins] [float] NULL,
	[OtMins] [float] NULL,
	[OvertimeStatus] [nvarchar](50) NULL,
	[TotalDays] [numeric](18, 1) NULL,
	[LeaveCode] [nvarchar](20) NULL,
	[LateEntryReason] [nvarchar](260) NULL,
	[EarlyOutReason] [nvarchar](260) NULL,
	[ProcessFlag] [bit] NULL,
	[Status] [nvarchar](50) NULL,
	[FNAttendanceCode] [nvarchar](15) NULL,
	[ANAttendanceCode] [nvarchar](15) NULL)
	declare @SQL varchar(4000)
	set @SQL =''
	set @SQL = @SQL + 'insert into #TempProcessedData select Employee_Code_Id,Date,Shift_Id,InTime,OutTime,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut, '
	set @SQL = @SQL + 'LateIn,Attendance,WorkHrs,HrsLess,HrsExtra,LateInMins,EarlyOutMins,ExtraMins,OtMins,OvertimeStatus,TotalDays,LeaveCode, '
	set @SQL = @SQL + 'LateEntryReason,EarlyOutReason,ProcessFlag,Status,FNAttendanceCode,ANAttendanceCode from TA_tbl_ProcessedData '
	set @SQL = @SQL + 'where Date = ''' + @Date + ''' '
	if(@ShiftId<>0)  
		begin  
				Set @SQL = @SQL + ' AND Ta_Tbl_ProcessedData.shift_id= '+  cast (@ShiftId as nvarchar(50))  + ''  
	 end  
	 exec (@SQL)
 --select * from #TempProcessedData   
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempHeadCountSummary '    
set @SelectSQL = @SelectSQL + ' select replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,Ta_tbl_Employee.SwipeCardNo  '
set @SelectSQL = @SelectSQL + ' as PEmployee_Code_Id,#TempProcessedData.Date as PDate,#TempProcessedData.FNAttendanceCode as FNAttendanceCode,#TempProcessedData.ANAttendanceCode as ANAttendanceCode,'
set @SelectSQL = @SelectSQL + ' '''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''' as FS_Status,'''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees'
set @SelectSQL = @SelectSQL + ' From #TempProcessedData inner join Ta_tbl_Employee on #TempProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo'    
set @SelectSQL = @SelectSQL + ' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where 
((Ta_tbl_Employee.Employee_Status=1)
or
(Ta_tbl_Employee.Employee_Status=0 and convert(nvarchar(11),Ta_tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))) 
and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
--if(@ShiftId<>0)  
--		begin  
--				Set @SelectSQL = @SelectSQL + ' AND Ta_Tbl_ProcessedData.shift_id= '+  cast (@ShiftId as nvarchar(50))  + ''  
--	 end  
exec (@SelectSQL)     
--select * from  #tempHeadCountSummary
--create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummaryFinal (levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempHeadCountSummaryFinal (levelID,Dept,level,Parent,ParentName) select distinct levelID,Dept,level,Parent,ParentName from #tempHeadCountSummary '    
--set @SelectSQL = @SelectSQL + ' select distinct replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,'''' as  '
--set @SelectSQL = @SelectSQL + 'PEmployee_Code_Id,''' + @Date +  ''' as PDate,'''' as FNAttendanceCode,'''' as ANAttendanceCode, '
----,0 as EarlyOutMins,0 as LateInMins,'''' as  intime,'''' as outtime '    
----set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 '    
--set @SelectSQL = @SelectSQL + ' '''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''' as FS_Status,'''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees'
--set @SelectSQL = @SelectSQL + ' From Ta_tbl_Employee'    
--set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
--set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
--set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
--set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId '    
--set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
exec (@SelectSQL)     
--select * from #tempHeadCountSummaryFinal
update #tempHeadCountSummaryFinal set PresentFS=PresentCount.PresentFS    
from (select count(*) as PresentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'Present'
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
--select * from #tempHeadCountSummaryFinal  
update #tempHeadCountSummaryFinal set PresentSS=PresentCount.PresentSS    
from (select count(*) as PresentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'Present'
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
update #tempHeadCountSummaryFinal set AbsentFS=AbsentCount.AbsentFS    
from (select count(*) as AbsentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'Absent'
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID    
update #tempHeadCountSummaryFinal set AbsentSS=AbsentCount.AbsentSS    
from (select count(*) as AbsentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'Absent'
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID  
update #tempHeadCountSummaryFinal set LeaveFS=LeaveCount.LeaveFS    
from (select count(*) as LeaveFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode != 'LOP' and FNAttendanceCode != 'Present' and FNAttendanceCode != 'Absent'
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID    
update #tempHeadCountSummaryFinal set LeaveSS=LeaveCount.LeaveSS    
from (select count(*) as LeaveSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode != 'LOP' and ANAttendanceCode != 'Present' and ANAttendanceCode != 'Absent'
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID 
update #tempHeadCountSummaryFinal set LOPFS=LOPCount.LOPFS    
from (select count(*) as LOPFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'LOP'
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID    
update #tempHeadCountSummaryFinal set LOPSS=LOPCount.LOPSS    
from (select count(*) as LOPSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'LOP'
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID  
update #tempHeadCountSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees 
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID    
inner join  #TempProcessedData on #TempProcessedData.employee_Code_id=TA_Tbl_Employee.SwipeCardNo
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0 
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=TotalEmployeesCount.levelID    
update #tempHeadCountSummaryFinal set OrgLevel=Dept
update #tempHeadCountSummaryFinal set LOPFS=0 where LOPFS is null
update #tempHeadCountSummaryFinal set LOPSS=0 where LOPSS is null
update #tempHeadCountSummaryFinal set LeaveSS=0 where LeaveSS is null
update #tempHeadCountSummaryFinal set LeaveFS=0 where LeaveFS is null
update #tempHeadCountSummaryFinal set AbsentFS=0 where AbsentFS is null
update #tempHeadCountSummaryFinal set AbsentSS=0 where AbsentSS is null
update #tempHeadCountSummaryFinal set PresentSS=0 where PresentSS is null
update #tempHeadCountSummaryFinal set PresentFS=0 where PresentFS is null
update #tempHeadCountSummaryFinal set FS_Status=0 where FS_Status is null
update #tempHeadCountSummaryFinal set SS_Status=0 where SS_Status is null
--select * from #tempHeadCountSummaryFinal
--Status update
declare @Shift_FirstHalf_StartTime as varchar(50)
	declare @Shift_SecondHalf_StartTime as varchar(50)
	declare @FirstHalf_StartTime as varchar(50)
	declare @SecondHalf_StartTime as varchar(50)
	select @Shift_FirstHalf_StartTime=substring(Shift_FirstHalf_StartTime,7,2),@FirstHalf_StartTime=Shift_FirstHalf_StartTime,
	@Shift_SecondHalf_StartTime=substring(Shift_SecondHalf_StartTime,7,2),@SecondHalf_StartTime=Shift_SecondHalf_StartTime from ta_tbl_shift where shift_id=@ShiftId
	if(@Shift_FirstHalf_StartTime='PM' and @Shift_SecondHalf_StartTime='AM')
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,dateadd(d,1,@Date) , 101) + space(1) + @SecondHalf_StartTime		
		end
	else
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @SecondHalf_StartTime		
	end
	
   --select getdate()
   --select @Shift_SecondHalf_StartTime
   --select @Shift_FirstHalf_StartTime
   --Select * from #tempHeadCountSummaryFinal

   --if (getdate()<cast(@Shift_SecondHalf_StartTime as datetime))
	  -- begin
			--update #tempHeadCountSummaryFinal set SS_Status=18000000,PresentSS=0,AbsentSS=0
	  -- end
   --if (getdate()<cast(@Shift_FirstHalf_StartTime as datetime))
	  -- begin
			--update #tempHeadCountSummaryFinal set FS_Status=18000000,PresentFS=0,AbsentFS=0
	  -- end

----To Load Details  Summary Report   
if(@ExportType=1)
	begin	 
		select * from #tempHeadCountSummaryFinal order by level  
	end
else
	begin
		create table #tempHeadCount (Sl int identity(1,1), levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
	,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)
	insert into #tempHeadCount select * from #tempHeadCountSummaryFinal order by level  
	declare @couLevel int
	set @couLevel=(select COUNT(*) from #tempHeadCount)
	declare @i int
	set @i=1
	declare @SQLString1 nvarchar(Max)
	set @SQLString1=''
	while @i<=@couLevel
		begin
			set @SQLString1 = @SQLString1 + cast((select OrgLevel from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '$' + cast((select TotalEmployees from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +cast((select PresentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select PresentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select AbsentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select AbsentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LeaveFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LeaveSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LOPFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LOPSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '#'
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
	end
--To Load Shift Name in Summary Report    
if not exists (select Shift_Name + ' (' + Shift_StartTime + ' - ' + Shift_EndTime + ')'  as ShiftName from ta_tbl_shift where shift_id=@ShiftId)
begin
select 'All Shifts' as ShiftName
end
else
begin
select Shift_Name + ' (' + Shift_StartTime + ' - ' + Shift_EndTime + ')'  as ShiftName from ta_tbl_shift where shift_id=@ShiftId
end
drop table #tempHeadCountSummary 
drop table #tempHeadCountSummaryFinal   
drop table #TempProcessedData
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END   
--select * from ta_tbl_processeddata where date='06/21/2011'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountSummary_backup20230523]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_RptHeadCountSummary '14/Sep/2016','SuperAdmin',0,2,0,15
Create PROCEDURE [dbo].[Proc_TA_RptHeadCountSummary_backup20230523]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int,
 @ShiftId int,
 @ExportType int,
 @EmpAutoID int
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
--select * from #tempProcessSecSummary
CREATE TABLE #TempProcessedData(
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Date] [datetime] NULL,
	[Shift_Id] [int] NULL,
	[InTime] [nvarchar](25) NULL,
	[OutTime] [nvarchar](25) NULL,
	[HrsWork] [nvarchar](10) NULL,
	[HrsOT] [nvarchar](10) NULL,
	[NormOT] [nvarchar](10) NULL,
	[OffOT] [nvarchar](10) NULL,
	[HolOT] [nvarchar](10) NULL,
	[EarlyOut] [nvarchar](10) NULL,
	[LateIn] [nvarchar](10) NULL,
	[Attendance] [nvarchar](20) NULL,
	[WorkHrs] [nvarchar](10) NULL,
	[HrsLess] [nvarchar](10) NULL,
	[HrsExtra] [nvarchar](10) NULL,
	[LateInMins] [float] NULL,
	[EarlyOutMins] [float] NULL,
	[ExtraMins] [float] NULL,
	[OtMins] [float] NULL,
	[OvertimeStatus] [nvarchar](50) NULL,
	[TotalDays] [numeric](18, 1) NULL,
	[LeaveCode] [nvarchar](20) NULL,
	[LateEntryReason] [nvarchar](260) NULL,
	[EarlyOutReason] [nvarchar](260) NULL,
	[ProcessFlag] [bit] NULL,
	[Status] [nvarchar](50) NULL,
	[FNAttendanceCode] [nvarchar](15) NULL,
	[ANAttendanceCode] [nvarchar](15) NULL)
	declare @SQL varchar(4000)
	set @SQL =''
	set @SQL = @SQL + 'insert into #TempProcessedData select Employee_Code_Id,Date,Shift_Id,InTime,OutTime,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut, '
	set @SQL = @SQL + 'LateIn,Attendance,WorkHrs,HrsLess,HrsExtra,LateInMins,EarlyOutMins,ExtraMins,OtMins,OvertimeStatus,TotalDays,LeaveCode, '
	set @SQL = @SQL + 'LateEntryReason,EarlyOutReason,ProcessFlag,Status,FNAttendanceCode,ANAttendanceCode from TA_tbl_ProcessedData '
	set @SQL = @SQL + 'where Date = ''' + @Date + ''' '
	if(@ShiftId<>0)  
		begin  
				Set @SQL = @SQL + ' AND Ta_Tbl_ProcessedData.shift_id= '+  cast (@ShiftId as nvarchar(50))  + ''  
	 end  
	 exec (@SQL)
 --select * from #TempProcessedData   
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempHeadCountSummary '    
set @SelectSQL = @SelectSQL + ' select replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,Ta_tbl_Employee.SwipeCardNo  '
set @SelectSQL = @SelectSQL + ' as PEmployee_Code_Id,#TempProcessedData.Date as PDate,#TempProcessedData.FNAttendanceCode as FNAttendanceCode,#TempProcessedData.ANAttendanceCode as ANAttendanceCode,'
set @SelectSQL = @SelectSQL + ' '''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''' as FS_Status,'''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees'
set @SelectSQL = @SelectSQL + ' From #TempProcessedData inner join Ta_tbl_Employee on #TempProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo'    
set @SelectSQL = @SelectSQL + ' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where 
((Ta_tbl_Employee.Employee_Status=1)
or
(Ta_tbl_Employee.Employee_Status=0 and convert(nvarchar(11),Ta_tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))) 
and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
--if(@ShiftId<>0)  
--		begin  
--				Set @SelectSQL = @SelectSQL + ' AND Ta_Tbl_ProcessedData.shift_id= '+  cast (@ShiftId as nvarchar(50))  + ''  
--	 end  
exec (@SelectSQL)     
--select * from  #tempHeadCountSummary
--create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummaryFinal (levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempHeadCountSummaryFinal (levelID,Dept,level,Parent,ParentName) select distinct levelID,Dept,level,Parent,ParentName from #tempHeadCountSummary '    
--set @SelectSQL = @SelectSQL + ' select distinct replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,'''' as  '
--set @SelectSQL = @SelectSQL + 'PEmployee_Code_Id,''' + @Date +  ''' as PDate,'''' as FNAttendanceCode,'''' as ANAttendanceCode, '
----,0 as EarlyOutMins,0 as LateInMins,'''' as  intime,'''' as outtime '    
----set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 '    
--set @SelectSQL = @SelectSQL + ' '''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''' as FS_Status,'''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees'
--set @SelectSQL = @SelectSQL + ' From Ta_tbl_Employee'    
--set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
--set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
--set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
--set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId '    
--set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
exec (@SelectSQL)     
--select * from #tempHeadCountSummaryFinal
update #tempHeadCountSummaryFinal set PresentFS=PresentCount.PresentFS    
from (select count(*) as PresentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'Present'
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
--select * from #tempHeadCountSummaryFinal  
update #tempHeadCountSummaryFinal set PresentSS=PresentCount.PresentSS    
from (select count(*) as PresentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'Present'
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
update #tempHeadCountSummaryFinal set AbsentFS=AbsentCount.AbsentFS    
from (select count(*) as AbsentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'Absent'
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID    
update #tempHeadCountSummaryFinal set AbsentSS=AbsentCount.AbsentSS    
from (select count(*) as AbsentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'Absent'
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID  
update #tempHeadCountSummaryFinal set LeaveFS=LeaveCount.LeaveFS    
from (select count(*) as LeaveFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode != 'LOP' and FNAttendanceCode != 'Present' and FNAttendanceCode != 'Absent'
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID    
update #tempHeadCountSummaryFinal set LeaveSS=LeaveCount.LeaveSS    
from (select count(*) as LeaveSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode != 'LOP' and ANAttendanceCode != 'Present' and ANAttendanceCode != 'Absent'
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID 
update #tempHeadCountSummaryFinal set LOPFS=LOPCount.LOPFS    
from (select count(*) as LOPFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = 'LOP'
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID    
update #tempHeadCountSummaryFinal set LOPSS=LOPCount.LOPSS    
from (select count(*) as LOPSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = 'LOP'
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID  
update #tempHeadCountSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees 
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID    
inner join  #TempProcessedData on #TempProcessedData.employee_Code_id=TA_Tbl_Employee.SwipeCardNo
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0 
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=TotalEmployeesCount.levelID    
update #tempHeadCountSummaryFinal set OrgLevel=Dept
update #tempHeadCountSummaryFinal set LOPFS=0 where LOPFS is null
update #tempHeadCountSummaryFinal set LOPSS=0 where LOPSS is null
update #tempHeadCountSummaryFinal set LeaveSS=0 where LeaveSS is null
update #tempHeadCountSummaryFinal set LeaveFS=0 where LeaveFS is null
update #tempHeadCountSummaryFinal set AbsentFS=0 where AbsentFS is null
update #tempHeadCountSummaryFinal set AbsentSS=0 where AbsentSS is null
update #tempHeadCountSummaryFinal set PresentSS=0 where PresentSS is null
update #tempHeadCountSummaryFinal set PresentFS=0 where PresentFS is null
update #tempHeadCountSummaryFinal set FS_Status=0 where FS_Status is null
update #tempHeadCountSummaryFinal set SS_Status=0 where SS_Status is null
--select * from #tempHeadCountSummaryFinal
--Status update
declare @Shift_FirstHalf_StartTime as varchar(50)
	declare @Shift_SecondHalf_StartTime as varchar(50)
	declare @FirstHalf_StartTime as varchar(50)
	declare @SecondHalf_StartTime as varchar(50)
	select @Shift_FirstHalf_StartTime=substring(Shift_FirstHalf_StartTime,7,2),@FirstHalf_StartTime=Shift_FirstHalf_StartTime,
	@Shift_SecondHalf_StartTime=substring(Shift_SecondHalf_StartTime,7,2),@SecondHalf_StartTime=Shift_SecondHalf_StartTime from ta_tbl_shift where shift_id=@ShiftId
	if(@Shift_FirstHalf_StartTime='PM' and @Shift_SecondHalf_StartTime='AM')
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,dateadd(d,1,@Date) , 101) + space(1) + @SecondHalf_StartTime		
		end
	else
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @SecondHalf_StartTime		
	end
   --select getdate()
   --select @Shift_SecondHalf_StartTime
   --select @Shift_FirstHalf_StartTime
   if (getdate()<cast(@Shift_SecondHalf_StartTime as datetime))
	   begin
			update #tempHeadCountSummaryFinal set SS_Status=18000000,PresentSS=0,AbsentSS=0
	   end
   if (getdate()<cast(@Shift_FirstHalf_StartTime as datetime))
	   begin
			update #tempHeadCountSummaryFinal set FS_Status=18000000,PresentFS=0,AbsentFS=0
	   end
----To Load Details  Summary Report   
if(@ExportType=1)
	begin	 
		select * from #tempHeadCountSummaryFinal order by level  
	end
else
	begin
		create table #tempHeadCount (Sl int identity(1,1), levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
	,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)
	insert into #tempHeadCount select * from #tempHeadCountSummaryFinal order by level  
	declare @couLevel int
	set @couLevel=(select COUNT(*) from #tempHeadCount)
	declare @i int
	set @i=1
	declare @SQLString1 nvarchar(Max)
	set @SQLString1=''
	while @i<=@couLevel
		begin
			set @SQLString1 = @SQLString1 + cast((select OrgLevel from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '$' + cast((select TotalEmployees from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +cast((select PresentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select PresentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select AbsentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select AbsentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LeaveFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LeaveSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LOPFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '~' +  cast((select LOPSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + '#'
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
	end
--To Load Shift Name in Summary Report    
if not exists (select Shift_Name + ' (' + Shift_StartTime + ' - ' + Shift_EndTime + ')'  as ShiftName from ta_tbl_shift where shift_id=@ShiftId)
begin
select 'All Shifts' as ShiftName
end
else
begin
select Shift_Name + ' (' + Shift_StartTime + ' - ' + Shift_EndTime + ')'  as ShiftName from ta_tbl_shift where shift_id=@ShiftId
end
drop table #tempHeadCountSummary 
drop table #tempHeadCountSummaryFinal   
drop table #TempProcessedData
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END   
--select * from ta_tbl_processeddata where date='06/21/2011'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateExit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  senthilkumar.np  
-- ALTER  date: 02-August-07  
-- Modified By : sashma
-- Modified Date : 12-May-2011
-- Description: Getting Late Exit - report  
-- Modified By : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description: Sql Query Optimization 
--	Proc_TA_RptLateExit '2016/01/04','2016/12/04','',0,'','',0,0,'SuperAdmin','0','',0,0,'Both'
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_RptLateExit]  
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeId varchar(max),  
	 @shift int,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @MINExceptionHOURS AS VARCHAR(6),
	 @EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;  
	DECLARE @dateFormat as int
	Declare @sqlTempProcessedData varchar(max)
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)
	declare @sqlQuery as varchar(max)
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@MINExceptionHOURS,0,CHARINDEX(':',@MINExceptionHOURS))*60 + SUBSTRING(@MINExceptionHOURS,CHARINDEX(':',@MINExceptionHOURS)+1,2)
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsExtra nvarchar(10),
		ExtraMins int
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([EmpAutoId],[Date],[Employee_Code_Id],[Shift_Id],[HrsExtra],[ExtraMins] ASC) ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end 
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	--Employee Level insert in Temporary table
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where SwipeCardNo is not null and emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End		
	Execute(@sqlEmpLevel)
	set @sqlTempProcessedData=
	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	if(@Gender<>'Both')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	'insert into #TempProcessedData select	#TempEmployee.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.LateExitHours,
											PD.lateExitMins 
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id
	where lateexit=1 and  (PD.Date >= CONVERT(DATETIME,'''+cast( @fromDat as nvarchar(50))+''', 102))   
	AND (PD.Date <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102))
	and PD.OutTime <> ''0'' and PD.OutTime <> ''00:00:00'' and PD.OutTime <> ''00:00'' 
	and PD.OutTime is not null and PD.OutTime <>'''' and PD.lateExitMins > 0
	'
	if(@shift<>0)
		begin
			set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' And PD.Shift_Id = ' +  cast(@shift  as nvarchar(20))  
		end
	IF (@MINExceptionHOURS<>'')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND PD.lateExitMins >= ' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	set @sqlQuery = ''   
	set @sqlQuery = @sqlQuery + ' select	#EmpLevel.LevelId,
											replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],
											right(dbo.ta_tbl_shift.Shift_EndTime,8)  as shiftOut,
											ta_tbl_shift.shift_shortName ,
											dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Code_Id,											
											case	when '+cast(@dateFormat as varchar(100))+'=106 then
													REPLACE(CONVERT(VARCHAR, Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
											else CONVERT(VARCHAR, Date, '+cast(@dateFormat as varchar(100))+') 
											end AS Date,
											#TempProcessedData.OutTime,
											#TempProcessedData.shift_id,
											#TempProcessedData.hrsExtra,' 
	set @sqlQuery = @sqlQuery + '			dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''') as empname,
											replace(Ta_tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
											TA_Tbl_Employee.Gender,
											ExtraMins 
								  FROM  #TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_ID=#TempProcessedData.EmpAutoId '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' where 
	(
		(
			(TA_Tbl_Employee.Employee_Status=1)
			OR
			(TA_Tbl_Employee.Employee_Status=0 and convert(nvarchar(11),TA_Tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))
		)and ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 
	)' 			
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
	set @sqlQuery = @sqlQuery + ' order by #TempProcessedData.Employee_Code_Id,#TempProcessedData.Date' 
	Exec(@sqlQuery)  
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
	drop table #TempProcessedData
	drop table #TempEmployee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateIn]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_RptLateIn '','0','2020/01/01','2020/07/30','Sathishkumar ,Manikandan ,',0,0,0,'SuperAdmin','1','',0,0,'Both',0,1,' '
CREATE  PROCEDURE [dbo].[Proc_TA_RptLateIn]  
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int,
	@MINExceptionHOURS AS VARCHAR(6)
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	DECLARE @local_MINExceptionHOURS AS VARCHAR(6)
    SET @local_FROMDAT			= LTRIM(RTRIM(@FromDate))
    SET @local_TODAT			= LTRIM(RTRIM(@ToDate))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))    
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@ExportType))  
    SET @local_MINExceptionHOURS= LTRIM(RTRIM(@MINExceptionHOURS))  
	Declare @sqlTempProcessedData varchar(max) 
	Declare @sqlTempProcessedData2 varchar(max)
	DECLARE @dateFormat as int
	Declare @SelectSQL As Varchar(max)
	DECLARE @TimeFormat as nvarchar(25)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_USERGROUPNAME
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EMPAUTOID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EMPAUTOID) as EmpAutoId
	end
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX(':',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX(':',@local_MINExceptionHOURS)+1,2)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		LateEntryReason nvarchar(260),
		Shift_StartTime nvarchar(10)
	)	
	insert into #LevelRights	select * from [dbo].[fn_TA_GetParentChild](@local_USERGROUPNAME,@local_PARENTID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID	
	insert into #EmpType		exec [Proc_TA_EmpType] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE	
	insert into #EmpCategory	exec [Proc_TA_EmpCategory] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY	
	insert into #EmpLevel		exec  [Proc_TA_EmpLevel] @local_TODAT,@local_EMPLOYEEID	
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@local_EMPLOYEEID is not null and @local_EMPLOYEEID <> '')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EMPLOYEEID)
		end
	if(@local_EMPLOYEENAME is not null and @local_EMPLOYEENAME <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EMPLOYEENAME,',')
		end
	insert into #TempEmployee 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee emp
	inner join #EmpLevel on #EmpLevel.EmployeeId=emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 
	left join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id 
	left join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
	where SwipeCardNo is not null and emp.Isdeleted=0  and emp.report_exclude=0
	and (isnull(@EmployeeID,'')='' or emp.Employee_Code_Id in (select * from #EmployeeID))
	and (isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in (select * from #EmployeeName))
	and (isnull(@Gender,'Both')='Both' or emp.Gender=@Gender)
	insert into #TempProcessedData select	TE.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.Process_Rec_ID,
											PD.LateIn,
											PD.LateInMins,
											PD.LateEntryReason,
											(select Shift_StartTime from ta_tbl_shift where shift_id=PD.Shift_Id)
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee TE on TE.EmpSwipeCardNo=PD.Employee_Code_Id	
	where (PD.Date >= CONVERT(DATETIME,@local_FROMDAT, 102)) 
	AND (PD.Date <= CONVERT(DATETIME,@local_TODAT, 102)) and PD.LateIn <> '00:00:00' And PD.LateIn <> '00:00' And PD.LateIn <> '0' 
	AND LateInMins > 0 AND InTime is not null AND InTime <> '0' AND InTime <> '00:00' and processflag=1
	and(isnull(@shift,0)=0 or PD.shift_id=@shift)
	and (isnull(@TOTALExceptionMIN,0)=0 or PD.LateInMins >=@TOTALExceptionMIN)
	Set @EmployeeName = @local_EMPLOYEENAME 
	--Got error in grid control internally 28-07-2020 change the name to Process_Rec_ID instead of Peocess_Rec_ID
	Create table #TempLate(Process_Rec_ID int, CardNo nVarchar(30), [Employee Name] nvarchar(100),designation nvarchar(100),[Level Name] nvarchar(200),Shift_StartTime nvarchar(20),shift_shortName nvarchar(10),Date nvarchar(30),InTime nvarchar(30),LateBy nvarchar(30),Reason nvarchar(Max),Gender nvarchar(10),LateInMins decimal(18,2),format datetime)
	insert into #TempLate
	SELECT PD.Process_Rec_ID,
	ED.Employee_Code_Id AS CardNo,ED.Employee_FirstName + 
	' ' + isnull(ED.Employee_LastName,'') AS 'Employee Name', 
	replace(T.TitleName,'&amp;','&')  AS Designation, 
	replace(L.name,'&amp;','&')  AS [Level Name],
	PD.Shift_StartTime,replace(sh.shift_shortName,'&amp;','&') as shift_shortName,
	case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, Date,@dateFormat) 
	end AS Date,
	CASE	WHEN @TIMEFORMAT='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
			ELSE InTime
	END InTime,
	LateIn as LateBy,
	PD.LateEntryReason as Reason,
	ED.Gender,
	LateInMins,
	Date as format
	FROM TA_Tbl_Employee ED
	Inner join #EmpLevel Lev on Lev.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id
	Inner join #EmpDesignation  EDesig on EDesig.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID
	Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id
	INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId
	INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id
	Where 1=1 
	AND 
	(
		(ED.employee_status=1) or 
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),Date,102))
	)	
	if(@local_EXPORT=1)
	begin
		select CardNo,[Employee Name],[Level Name],designation,date,shift_shortName,Shift_StartTime, InTime,LateBy,
		Reason,Process_Rec_ID,Gender,LateInMins,format from #TempLate 
		order by CardNo,CONVERT(datetime,format)
	end
	else
	begin		
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(30))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempLate
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempLate order by format
		declare @couLevel int
		select @couLevel=COUNT(*) from #TempLevelName
		declare @couDate int
		select @couDate=COUNT(*) from #TempDate
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + '@'
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempLate where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + '#'
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
		drop table #TempDate
		drop table #TempLevelName
		drop table #TempLate
	end
	drop table #EmpCategory
	drop table #EmpDesignation
	drop table #EmpLevel
	drop table #EmployeeIds	
	drop table #EmpType
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
 End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Proc_TA_RptLeave '2020/01/01','2020/09/24','','0','','0,24','All','All',1,1,'superadmin','0','',0,3,'Both',1
-- =============================================
CREATE     PROCEDURE [dbo].[Proc_TA_RptLeave]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	--Get the Current date time format
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)
	declare @sqlResHoliday as varchar(8000)
	declare @sqlESIDays as varchar(8000)
	declare @sqlCompDays as varchar(8000)
	declare @sqlLOPDays as varchar(8000)
	declare @sqlMonthlyLOP as varchar(8000)
	
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'SELECT 
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,	
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	
	Case When Status=''Pending'' Then ''-''
	Else E.Employee_FirstName
	End As Approved_BY,
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date,
	
	TA_Tbl_LeaveApplication.Remarks
	FROM dbo.TA_Tbl_LeaveApplication INNER JOIN
	dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id
	INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id 
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id
	INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId
	INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 
	Left join dbo.TA_Tbl_LeaveConversation LC on Lc.Emp_Id= dbo.TA_Tbl_LeaveApplication.Emp_Id and
	LC.LeaveApplicationId=dbo.TA_Tbl_LeaveApplication.LeaveApplication_Id
	Inner join dbo.Ta_Tbl_Employee E on E.Employee_Id=dbo.ta_tbl_LeaveApplication.Emp_Id'
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where dbo.TA_Tbl_LeaveApplication.Type=''Leave'' 
	and 
	((dbo.TA_Tbl_Employee.Employee_Status = 1)
	or
	(dbo.TA_Tbl_Employee.Employee_Status = 0 and 
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_FromDate
	or
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_ToDate)
	)
	)
	) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
	set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlQuery = @sqlQuery + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	if not(@LeaveStatus='All')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end	
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end			
	set @sqlResHoliday=''
	if (@LeaveType='All')
		begin
			set @sqlResHoliday=' UNION '
		end
	set @sqlResHoliday = @sqlResHoliday + ' SELECT  
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	ta_tbl_Holiday.Holiday_Description as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	Case When Status=''Pending'' Then ''-''
	Else E.Employee_FirstName
	End As Approved_BY,
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date,	
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlResHoliday = @sqlResHoliday + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlResHoliday = @sqlResHoliday + ' Left join dbo.TA_Tbl_LeaveConversation LC on Lc.Emp_Id= dbo.TA_Tbl_LeaveApplication.Emp_Id and LC.LeaveApplicationId=dbo.TA_Tbl_LeaveApplication.LeaveApplication_Id'
	set @sqlResHoliday = @sqlResHoliday + ' Inner join dbo.Ta_Tbl_Employee E on E.Employee_Id=dbo.ta_tbl_LeaveApplication.Emp_Id'
	
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlResHoliday = @sqlResHoliday + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlResHoliday = @sqlResHoliday + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlResHoliday = @sqlResHoliday + ' And dbo.ta_tbl_Holiday.Holiday_Type=''Y'' '
	set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) And (dbo.TA_Tbl_LeaveApplication.Type=''Restricted Holiday'')'
	set @sqlResHoliday = @sqlResHoliday + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlResHoliday = @sqlResHoliday + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if (@LeaveType='Restricted Holiday')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  '
		end
	if not(@LeaveStatus='All')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end	
	if(@Gender<>'Both')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlResHoliday = @sqlResHoliday + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlResHoliday = @sqlResHoliday + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end	
	-- ESI Leaves
	set @sqlESIDays=''
	if (@LeaveType='All')
		begin
			set @sqlESIDays=' UNION '
		end
	set @sqlESIDays = @sqlESIDays + ' SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	''ESI'' as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	
	Case When Status=''Pending'' Then ''-''
	Else E.Employee_FirstName
	End As Approved_BY,
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date,
	
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlESIDays = @sqlESIDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlESIDays = @sqlESIDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlESIDays = @sqlESIDays + ' Left join dbo.TA_Tbl_LeaveConversation LC on Lc.Emp_Id= dbo.TA_Tbl_LeaveApplication.Emp_Id and LC.LeaveApplicationId=dbo.TA_Tbl_LeaveApplication.LeaveApplication_Id'
	set @sqlESIDays = @sqlESIDays + ' Inner join dbo.Ta_Tbl_Employee E on E.Employee_Id=dbo.ta_tbl_LeaveApplication.Emp_Id'
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlESIDays = @sqlESIDays + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlESIDays = @sqlESIDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlESIDays = @sqlESIDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
	set @sqlESIDays = @sqlESIDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlESIDays = @sqlESIDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''ESI'''
	if not(@LeaveStatus='All')
		begin
			set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end	
	if(@Gender<>'Both')
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlESIDays = @sqlESIDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlESIDays = @sqlESIDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end	
	-- Comp Off Leaves
	set @sqlCompDays=''
	if (@LeaveType='All')
		begin
			set @sqlCompDays=' UNION '
		end
	set @sqlCompDays = @sqlCompDays + ' SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	''Comp Off'' as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	Case When Status=''Pending'' Then ''-''
	Else E.Employee_FirstName
	End As Approved_BY,
	
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date,
	
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlCompDays = @sqlCompDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlCompDays = @sqlCompDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlCompDays = @sqlCompDays + ' Left join dbo.TA_Tbl_LeaveConversation LC on Lc.Emp_Id= dbo.TA_Tbl_LeaveApplication.Emp_Id and LC.LeaveApplicationId=dbo.TA_Tbl_LeaveApplication.LeaveApplication_Id'
	set @sqlCompDays = @sqlCompDays + ' Inner join dbo.Ta_Tbl_Employee E on E.Employee_Id=dbo.ta_tbl_LeaveApplication.Emp_Id'
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlCompDays = @sqlCompDays + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlCompDays = @sqlCompDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlCompDays = @sqlCompDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ' 		
	set @sqlCompDays = @sqlCompDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlCompDays = @sqlCompDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''Comp Off'''
	if not(@LeaveStatus='All')
		begin
			set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end
	if(@Gender<>'Both')
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlCompDays = @sqlCompDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlCompDays = @sqlCompDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
	--LOP Days
	set @sqlLOPDays = ''
	if (@LeaveType='All')
		begin
			set @sqlLOPDays=' UNION '
		end
	set @sqlLOPDays = @sqlLOPDays + 'SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.ta_tbl_leavetype.leavetype + ''-'' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	Case When Status=''Pending'' Then ''-''
	Else E.Employee_FirstName
	End As Approved_BY,
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,LC.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date,
	
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlLOPDays = @sqlLOPDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlLOPDays = @sqlLOPDays + ' Left join dbo.TA_Tbl_LeaveConversation LC on Lc.Emp_Id= dbo.TA_Tbl_LeaveApplication.Emp_Id and LC.LeaveApplicationId=dbo.TA_Tbl_LeaveApplication.LeaveApplication_Id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join dbo.Ta_Tbl_Employee E on E.Employee_Id=dbo.ta_tbl_LeaveApplication.Emp_Id'
	if not(@LeaveStatus='All')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end
	set @sqlLOPDays = @sqlLOPDays + ' where (dbo.TA_Tbl_LeaveApplication.Type=''LOP'' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlLOPDays = @sqlLOPDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
	set @sqlLOPDays = @sqlLOPDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlLOPDays = @sqlLOPDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	if not(@LeaveStatus='All')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end
	if(@Gender<>'Both')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlLOPDays = @sqlLOPDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlLOPDays = @sqlLOPDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end	
	if (@LeaveType='All')
		begin
			exec(@sqlQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
		end
	if (@LeaveType='Restricted Holiday')
		begin
			exec(@sqlResHoliday)
		end
	if (@LeaveType='Comp Off')
		begin
			exec(@sqlCompDays)
		end
	if (@LeaveType='ESI')
		begin
			exec(@sqlESIDays)
		end
	if (@LeaveType='LOP')
		begin
			exec(@sqlLOPDays)
		end
	else if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='Comp Off' or @LeaveType='ESI' or @LeaveType='LOP')
		begin
			exec(@sqlQuery)
		end
	--print(@sqlQuery)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan
-- Added  date: 28-Jul-2016
-- Description:	Leave Report Angler
-- Proc_TA_RptLeave '01/may/2014','16/May/2014','id1',0,'','107','All',"Approved','Pending','Resend','Forwarded','Rejected','Reply','Canceled",0,0,'SuperAdmin','0','',0,0,107,0,'Both'
-- =============================================
CREATE     PROCEDURE [dbo].[Proc_TA_RptLeave_Angler]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@Unplanned int,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10)		
AS
BEGIN
	SET NOCOUNT ON;
	declare @SQLQueryLeaveStatus as nvarchar(max)
	set @SQLQueryLeaveStatus='';
	if (lower(@LeaveStatus)<>'all' and isnull(@LeaveStatus,'')<>'' )
		begin
			if CHARINDEX('Canceled',@LeaveStatus) = 0
				begin				
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + ' and (TA_Tbl_LeaveApplication.Status IN (''' + @LeaveStatus  + '''))
					and (TA_Tbl_LeaveApplication.IsDeleted=0)'					
				end
			else
				begin
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + ' and ((TA_Tbl_LeaveApplication.Status IN (''' + @LeaveStatus  + '''))'
				end
		End
	else if(@LeaveStatus='All')
		begin		
			if CHARINDEX('Canceled',@LeaveStatus) = 0
				begin				
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + ' and (TA_Tbl_LeaveApplication.Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected'',''Resend'',''Reply'')) and (TA_Tbl_LeaveApplication.IsDeleted=0)'
				end
			else
				begin
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + ' and ((TA_Tbl_LeaveApplication.Status IN (''Pending'',''Forwarded'',''Approved'',''Rejected'',''Resend'',''Reply'')) '
				end
		end
	if CHARINDEX('Canceled',@LeaveStatus) > 0
		begin			
			set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + ' or (TA_Tbl_LeaveApplication.IsDeleted=1))'
		end
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' +
	 cast(@EmpSwipeCard as nvarchar(100)) + ''')'
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(8)) + ''')'
	Execute(@sqlEmpDesi)
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
	Execute(@sqlEmpType)
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102),''' + cast(@EmpSwipeCard as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
	Execute(@sqlEmpCategory)
	declare @sqlQuery as varchar(8000)
	declare @sqlResHoliday as varchar(8000)
	declare @sqlESIDays as varchar(8000)
	declare @sqlCompDays as varchar(8000)
	declare @sqlLOPDays as varchar(8000)
	declare @sqlMonthlyLOP as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
	set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end , '	
	set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '	
	set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_Employee.Gender,TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo '
	set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' where dbo.TA_Tbl_LeaveApplication.Type=''Leave'' 
	and 
	((dbo.TA_Tbl_Employee.Employee_Status = 1)
	or
	(dbo.TA_Tbl_Employee.Employee_Status = 0 and 
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_FromDate
	or
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_ToDate)
	)
	)
	) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlQuery = @sqlQuery + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlQuery=@sqlQuery+@SQLQueryLeaveStatus
	if not(@EmployeeName='')
		begin
			Declare @Tempname nvarchar(200)
			set @Tempname= ' (TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
			set @sqlQuery = @sqlQuery + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		end
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not (@empId='')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end	
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@Unplanned!=0)
		begin
			set @SQLQuery = @SQLQuery + ' And (TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
	set @sqlResHoliday=''
	if (@LeaveType='All')
	begin
	set @sqlResHoliday=' UNION '
	end
	set @sqlResHoliday = @sqlResHoliday + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
	set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,dbo.ta_tbl_Holiday.Holiday_Description as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end , '
	set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
	set @sqlResHoliday = @sqlResHoliday + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo '
	set @sqlResHoliday = @sqlResHoliday + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlResHoliday = @sqlResHoliday + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlResHoliday = @sqlResHoliday + ' And dbo.ta_tbl_Holiday.Holiday_Type=''Y'' '
	set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.Type=''Restricted Holiday'')'
	set @sqlResHoliday = @sqlResHoliday + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlResHoliday = @sqlResHoliday + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if (@LeaveType='Restricted Holiday')
	begin
	set @sqlResHoliday = @sqlResHoliday + ' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  '
	end
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlResHoliday=@sqlResHoliday+@SQLQueryLeaveStatus
	if not(@EmployeeName='')
		begin
			Declare @TempnameRes nvarchar(200)
			set @TempnameRes= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
			set @sqlResHoliday = @sqlResHoliday + ' and '+ @TempnameRes +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		end
	if(@Gender<>'Both')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not (@empId='')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end		
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@Unplanned!=0)
		begin
			set @sqlResHoliday = @sqlResHoliday + ' And (TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
	set @sqlESIDays=''
		if (@LeaveType='All')
			begin
				set @sqlESIDays=' UNION '
			end
	set @sqlESIDays = @sqlESIDays + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
	set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''ESI'' as leavetype, dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end , '
	set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
	set @sqlESIDays = @sqlESIDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo '
	set @sqlESIDays = @sqlESIDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlESIDays = @sqlESIDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 'set @sqlESIDays = @sqlESIDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlESIDays = @sqlESIDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlESIDays = @sqlESIDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	begin
	set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''ESI'''
	end
	set @sqlESIDays=@sqlESIDays+@SQLQueryLeaveStatus
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	if not(@EmployeeName='')
		begin
			Declare @TempnameESI nvarchar(200)
			set @TempnameESI= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
			set @sqlESIDays = @sqlESIDays + ' and '+ @TempnameESI +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		end
	if(@Gender<>'Both')
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not (@empId='')
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end		
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@Unplanned!=0)
		begin
			set @sqlESIDays = @sqlESIDays + ' And (TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
	set @sqlCompDays=''
	if (@LeaveType='All')
		begin
			set @sqlCompDays=' UNION '
		end
	set @sqlCompDays = @sqlCompDays + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
	set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''Comp Off'' as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
	set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
	set @sqlCompDays = @sqlCompDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo '
	set @sqlCompDays = @sqlCompDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlCompDays = @sqlCompDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlCompDays = @sqlCompDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlCompDays = @sqlCompDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlCompDays = @sqlCompDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	begin
	set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''Comp Off'''
	end
	set @sqlCompDays=@sqlCompDays+@SQLQueryLeaveStatus
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	if not(@EmployeeName='')
		begin
			Declare @TempnameCompDays nvarchar(200)
			set @TempnameCompDays= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
			set @sqlCompDays = @sqlCompDays + ' and '+ @TempnameCompDays +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		end
	if(@Gender<>'Both')
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not (@empId='')
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end		
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@Unplanned!=0)
		begin
			set @sqlCompDays = @sqlCompDays + ' And (TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
	set @sqlLOPDays = ''
	if (@LeaveType='All')
	begin
	set @sqlLOPDays=' UNION '
	end
	set @sqlLOPDays = @sqlLOPDays + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
	set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.ta_tbl_leavetype.leavetype + ''-'' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
	set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
	set @sqlLOPDays = @sqlLOPDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo '
	set @sqlLOPDays = @sqlLOPDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlLOPDays = @sqlLOPDays + ' where (dbo.TA_Tbl_LeaveApplication.Type=''LOP'' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlLOPDays = @sqlLOPDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlLOPDays = @sqlLOPDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlLOPDays=@sqlLOPDays+@SQLQueryLeaveStatus
	if not(@EmployeeName='')
		begin
			Declare @TempnameLopDays nvarchar(200)
			set @TempnameLopDays= '(TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(TA_Tbl_Employee.Employee_LastName,'''')'
			set @sqlLOPDays = @sqlLOPDays + ' and '+ @TempnameLopDays +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		end
	if(@Gender<>'Both')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if not (@empId='')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end		
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
		  SET @SQLQuery = @SQLQuery +  ' AND (TA_Tbl_Employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or TA_Tbl_Employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''' or TA_Tbl_Employee.Employee_Id=''' + cast(@EmpAutoId as varchar(30)) +''') ' 
			set @SQLQuery = @SQLQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@Unplanned!=0)
		begin
			set @sqlLOPDays = @sqlLOPDays + ' And (TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
	create table #EmpLeave(Employee_Id varchar(15),applicationDate datetime,		fromDate datetime,		todate datetime,
		NumberOfDays decimal(18,1),		leavetype varchar(100),		Leave_SessionFrom varchar(100),		Leave_SessionTo varchar(100),
		Reason varchar(1050),		status varchar(50),		Remarks varchar(1050),		TitleName varchar(500),
		empname varchar(500),		[name] varchar(500),Gender nvarchar(10),IntimationType varchar(200),		InformTo VARCHAR(MAX)		)
	if (@LeaveType='All')
		begin
			insert into #EmpLeave exec(@SQLQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
		end
	if (@LeaveType='Restricted Holiday')
		begin
			insert into #EmpLeave exec(@sqlResHoliday)
		end
	if (@LeaveType='Comp Off')
		begin
			insert into #EmpLeave exec(@sqlCompDays)
		end
	if (@LeaveType='ESI')
		begin
			insert into #EmpLeave exec(@sqlESIDays)
		end
	if (@LeaveType='LOP')
		begin
			insert into #EmpLeave exec(@sqlLOPDays)
		end
	else if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='Comp Off' or @LeaveType='ESI' or @LeaveType='LOP')
		begin
			insert into #EmpLeave exec(@sqlQuery)
		end
	DECLARE @FromDate DATE, @DisplayName VARCHAR(MAX) = '', @ColumnName VARCHAR(MAX) = '';
	SELECT @FromDate = FromDate FROM TA_Tbl_YearSetting WHERE IsActive = 1;
	WITH [MonthName] AS(
		SELECT Mon = 0
		UNION ALL
		SELECT Mon+1 FROM [MonthName] WHERE Mon < 11)
	SELECT 
		@DisplayName = @DisplayName + (CASE WHEN @DisplayName = '' THEN '[' ELSE ', [' END) + REPLACE(SUBSTRING(CONVERT(VARCHAR(11), DATEADD(M, Mon, @FromDate), 6), 4, 11), ' ', '''') + ']',
		@ColumnName = @ColumnName + (CASE WHEN @ColumnName = '' THEN 'CREATE TABLE TmpLeavedetail (EmployeeId VARCHAR(30), [Month' ELSE ', [Month' END) + CAST((Mon + 1) AS VARCHAR(5)) + '] VARCHAR(50) DEFAULT ''' + SUBSTRING(CONVERT(VARCHAR(11), DATEADD(M, Mon, @FromDate), 6), 4, 11) + ''''
	FROM [MonthName]
	EXEC(@ColumnName + ')')
	IF (@Unplanned=1) 
	BEGIN
		SET @SQLQuery = 'INSERT INTO TmpLeavedetail SELECT Employee_Code_Id, ' + @DisplayName + ' FROM ('		
		SET @SQLQuery = @SQLQuery + 'SELECT LA.NumberOfDays, Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_ToDate, 6), 4, 11), '' '', '''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA '
		SET @SQLQuery = @SQLQuery + 'INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id '
		SET @SQLQuery = @SQLQuery + 'WHERE LA.IntimationType != ''P'' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) = DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''Rejected'' UNION ALL '
		SET @SQLQuery = @SQLQuery + 'SELECT (CASE WHEN (((DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) = 1) AND (LA.NumberOfDays = 1)) THEN 0.5 ELSE (DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) END) NumberOfDays, '
		SET @SQLQuery = @SQLQuery + 'Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_FromDate, 6), 4, 11), '' '', '''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA '
		SET @SQLQuery = @SQLQuery + 'INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id '
		SET @SQLQuery = @SQLQuery + 'WHERE LA.IntimationType != ''P'' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) != DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''Rejected'' UNION ALL '
		SET @SQLQuery = @SQLQuery + 'SELECT (CASE WHEN (((DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) = 1) AND (LA.NumberOfDays = 1)) THEN 0.5 ELSE LA.NumberOfDays - (DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) END) NumberOfDays,'
		SET @SQLQuery = @SQLQuery + 'Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_ToDate, 6), 4, 11), '' '', '''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA '
		SET @SQLQuery = @SQLQuery + 'INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id '
		SET @SQLQuery = @SQLQuery + 'WHERE LA.IntimationType != ''P'' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) != DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''Rejected'' ) Tbl '
		SET @SQLQuery = @SQLQuery + 'PIVOT (SUM(NumberOfDays) FOR LeaveMonth IN (' + @DisplayName + ')) AS Pvt'
		EXEC (@SQLQuery)
	END
	SELECT EL.*,
		LD.EmployeeId, 
		ISNULL(LD.Month1, 0.0) Month1,
		ISNULL(LD.Month2, 0.0) Month2,
		ISNULL(LD.Month3, 0.0) Month3,
		ISNULL(LD.Month4, 0.0) Month4,
		ISNULL(LD.Month5, 0.0) Month5,
		ISNULL(LD.Month6, 0.0) Month6,
		ISNULL(LD.Month7, 0.0) Month7,
		ISNULL(LD.Month8, 0.0) Month8,
		ISNULL(LD.Month9, 0.0) Month9,
		ISNULL(LD.Month10, 0.0) Month10,
		ISNULL(LD.Month11, 0.0) Month11,
		ISNULL(LD.Month12, 0.0) Month12
	FROM #EmpLeave EL
		LEFT JOIN TmpLeavedetail LD ON LD.EmployeeId = EL.Employee_Id
	order by Employee_Id,fromDate asc	
	SELECT [2] M1, [3] M2, [4] M3, [5] M4, [6] M5, [7] M6, [8] M7, [9] M8, [10] M9, [11] M10, [12] M11, [13] M12 FROM 
	(SELECT REPLACE(REPLACE(REPLACE(COLUMN_DEFAULT, '(''', ''), ''')', ''), ' ', '''') COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'TmpLeavedetail' AND COLUMN_NAME != 'EmployeeId' ) Tbl 
	PIVOT (MAX(COLUMN_DEFAULT) FOR ORDINAL_POSITION IN([2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13])) Pvt
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights		
	DROP TABLE TmpLeavedetail
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Test]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-07
-- Description:	Leave Report
-- Modified By : Sasireka.M
-- Modified On : 06.03.09
-- Description : For Monthly Leave Policy
--Modified By  : A.Amsaveni on 20.05.2013
--Description  : Display detail based on unplanned condition also. 
-- Proc_TA_RptLeave '04/01/2009','01/31/2010','','','','','All','All','','','SuperAdmin',1,'','0','1'
-- Proc_TA_RptLeave '01/26/2010','01/26/2010','','','','','All','All','','','lll',1,'','0','1'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptLeave_Test]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@Unplanned int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		declare @sqlResHoliday as varchar(8000)
		declare @sqlESIDays as varchar(8000)
		declare @sqlCompDays as varchar(8000)
		declare @sqlLOPDays as varchar(8000)
		declare @sqlMonthlyLOP as varchar(8000)
		set @sqlQuery = ''		
		set @sqlQuery = @sqlQuery + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,'
		set @sqlQuery = @sqlQuery + ' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name ,dbo.TA_Tbl_LeaveApplication.IntimationType'
		set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' where dbo.TA_Tbl_LeaveApplication.Type=''Leave'' and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		if (@LeaveStatus='Canceled')
		begin
		set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) '
		end
		set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlQuery = @sqlQuery + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  --+ ' AND (TA_Tbl_Employee.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or TA_Tbl_Employee.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''')'
		end		
		if not(@EmployeeName='')
		begin
			set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		If Not (@EmpSwipeCard = '')  
		 Begin  
		  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		 End 
		if not (@empId='')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
		if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
if not(@LeaveStatus='All' or @LeaveStatus='Canceled')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
			set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlQuery = @sqlQuery + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
			end	
		END
		ELSE
			BEGIN
			   set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			END
if(@Unplanned!=0)
		begin
		set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
--Restricted Holiday
set @sqlResHoliday=''
if (@LeaveType='All')
begin
set @sqlResHoliday=' UNION '
end		
		set @sqlResHoliday = @sqlResHoliday + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,dbo.ta_tbl_Holiday.Holiday_Description as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, '
		set @sqlResHoliday = @sqlResHoliday + ' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
		set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlResHoliday = @sqlResHoliday + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, dbo.TA_Tbl_LeaveApplication.IntimationType'
		set @sqlResHoliday = @sqlResHoliday + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlResHoliday = @sqlResHoliday + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlResHoliday = @sqlResHoliday + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlResHoliday = @sqlResHoliday + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlResHoliday = @sqlResHoliday + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlResHoliday = @sqlResHoliday + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlResHoliday = @sqlResHoliday + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlResHoliday = @sqlResHoliday + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlResHoliday = @sqlResHoliday + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		set @sqlResHoliday = @sqlResHoliday + ' And dbo.ta_tbl_Holiday.Holiday_Type=''Y'' '
		set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.Type=''Restricted Holiday'')'
		if(@Unplanned!=0)
		begin
		set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
		if (@LeaveStatus='Canceled')
		begin
		set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) '
		end
		set @sqlResHoliday = @sqlResHoliday + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlResHoliday = @sqlResHoliday + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlResHoliday = @sqlResHoliday + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end		
		if not(@EmployeeName='')
		begin
			set @sqlResHoliday = @sqlResHoliday + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		If Not (@EmpSwipeCard = '')  
		 Begin  
			Set @sqlResHoliday = @sqlResHoliday + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		 End 
		if not (@empId='')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
		if(@employeeCategory<>0)
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_EmployeeCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_EmployeeType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
if (@LeaveType='Restricted Holiday')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  '
		end
if not(@LeaveStatus='All' or @LeaveStatus='Canceled')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
			set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlResHoliday = @sqlResHoliday + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
			end	
		END
		ELSE
			BEGIN
			   set @sqlResHoliday = @sqlResHoliday + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			END
--exec(@sqlResHoliday)
-- ESI Leaves
set @sqlESIDays=''
if (@LeaveType='All')
begin
set @sqlESIDays=' UNION '
end			
		set @sqlESIDays = @sqlESIDays + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''ESI'' as leavetype, dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,'
		set @sqlESIDays = @sqlESIDays + ' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
		set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlESIDays = @sqlESIDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, dbo.TA_Tbl_LeaveApplication.IntimationType'
		set @sqlESIDays = @sqlESIDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlESIDays = @sqlESIDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlESIDays = @sqlESIDays + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlESIDays = @sqlESIDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlESIDays = @sqlESIDays + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlESIDays = @sqlESIDays + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlESIDays = @sqlESIDays + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlESIDays = @sqlESIDays + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlESIDays = @sqlESIDays + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlESIDays = @sqlESIDays + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlESIDays = @sqlESIDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		if (@LeaveStatus='Canceled')
		begin
		set @sqlESIDays = @sqlESIDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) '
		end
		set @sqlESIDays = @sqlESIDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlESIDays = @sqlESIDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
		begin
			set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''ESI'''
		end
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlESIDays = @sqlESIDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end		
		if not(@EmployeeName='')
		begin
			set @sqlESIDays = @sqlESIDays + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlESIDays = @sqlESIDays + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End 
		if not (@empId='')
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
		if(@employeeCategory<>0)
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_EmployeeCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlESIDays = @sqlESIDays + ' and TA_Tbl_EmployeeType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveStatus='All' or @LeaveStatus='Canceled')
		begin
			set @sqlESIDays = @sqlESIDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
			set @sqlESIDays = @sqlESIDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlESIDays = @sqlESIDays + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
			end	
		END
		ELSE
			BEGIN
			   set @sqlESIDays = @sqlESIDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			END
if(@Unplanned!=0)
		begin
		set @sqlESIDays = @sqlESIDays + ' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
--exec(@sqlESIDays)
-- Comp Off Leaves
set @sqlCompDays=''
if (@LeaveType='All')
begin
set @sqlCompDays=' UNION '
end			
		set @sqlCompDays = @sqlCompDays + ' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''Comp Off'' as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,'
		set @sqlCompDays = @sqlCompDays + ' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
		set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlCompDays = @sqlCompDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, dbo.TA_Tbl_LeaveApplication.IntimationType'
		set @sqlCompDays = @sqlCompDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlCompDays = @sqlCompDays + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlCompDays = @sqlCompDays + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlCompDays = @sqlCompDays + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlCompDays = @sqlCompDays + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlCompDays = @sqlCompDays + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlCompDays = @sqlCompDays + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlCompDays = @sqlCompDays + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlCompDays = @sqlCompDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		if (@LeaveStatus='Canceled')
		begin
		set @sqlCompDays = @sqlCompDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) '
		end
		set @sqlCompDays = @sqlCompDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlCompDays = @sqlCompDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
		begin
			set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''Comp Off'''
		end
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlCompDays = @sqlCompDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end		
		if not(@EmployeeName='')
		begin
			set @sqlCompDays = @sqlCompDays + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if not (@empId='')
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlCompDays = @sqlCompDays + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End 
		if(@employeeCategory<>0)
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_EmployeeCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_EmployeeType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveStatus='All' or @LeaveStatus='Canceled')
		begin
			set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
			set @sqlCompDays = @sqlCompDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		end
      if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlCompDays = @sqlCompDays + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
			end	
		END
		ELSE
			BEGIN
			   set @sqlCompDays = @sqlCompDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			END
if(@Unplanned!=0)
		begin
		set @sqlCompDays = @sqlCompDays + ' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
--LOP Days
set @sqlLOPDays = ''
if (@LeaveType='All')
begin
set @sqlLOPDays=' UNION '
end				
		set @sqlLOPDays = @sqlLOPDays + 'SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, '
		set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.ta_tbl_leavetype.leavetype + ''-'' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,'
		set @sqlLOPDays = @sqlLOPDays + ' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''Canceled'' else TA_Tbl_LeaveApplication.Status end ,'
		set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname , '
		set @sqlLOPDays = @sqlLOPDays + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, dbo.TA_Tbl_LeaveApplication.IntimationType'
		set @sqlLOPDays = @sqlLOPDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
		set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
		set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlLOPDays = @sqlLOPDays + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @sqlLOPDays = @sqlLOPDays + ' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
		set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlLOPDays = @sqlLOPDays + ' where (dbo.TA_Tbl_LeaveApplication.Type=''LOP'' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
		if (@LeaveStatus='Canceled')
		begin
		set @sqlLOPDays = @sqlLOPDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) '
		end
		set @sqlLOPDays = @sqlLOPDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
		set @sqlLOPDays = @sqlLOPDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlLOPDays = @sqlLOPDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end		
		if not(@EmployeeName='')
		begin
			set @sqlLOPDays = @sqlLOPDays + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if not (@empId='')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlLOPDays = @sqlLOPDays + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End 
		if(@employeeCategory<>0)
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_EmployeeCategory.CategoryID = ' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_EmployeeType.TypeID = ' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
if not(@LeaveStatus='All' or @LeaveStatus='Canceled')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
			set @sqlLOPDays = @sqlLOPDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
		end
       if(@EmpAutoId = 0)
	   BEGIN
		if not(@LevelID='' or @LevelID='0')
			begin
				set @sqlLOPDays = @sqlLOPDays + ' and #EmpLevel.LevelId IN (' + @LevelID  + ')'
			end	
		END
		ELSE
			BEGIN
			   set @sqlLOPDays = @sqlLOPDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			END
		if(@Unplanned!=0)
		begin
		set @sqlLOPDays = @sqlLOPDays + ' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''P'') '
		end
create table #EmpLeave(Employee_Id varchar(15),
applicationDate datetime,
fromDate datetime,
todate datetime,
NumberOfDays decimal(18,1),
leavetype varchar(100),
Leave_SessionFrom varchar(100),
Leave_SessionTo varchar(100),
Reason varchar(1050),
status varchar(50),
Remarks varchar(1050),
TitleName varchar(500),
empname varchar(500),
[name] varchar(500),
IntimationType varchar(200),
)
if (@LeaveType='All')
	begin
insert into #EmpLeave exec(@sqlQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
	end
if (@LeaveType='Restricted Holiday')
	begin
	insert into #EmpLeave exec(@sqlResHoliday)
	end
if (@LeaveType='Comp Off')
	begin
	insert into #EmpLeave exec(@sqlCompDays)
	end
if (@LeaveType='ESI')
	begin
	insert into #EmpLeave exec(@sqlESIDays)
	end
if (@LeaveType='LOP')
	begin
	insert into #EmpLeave exec(@sqlLOPDays)
	end
else if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='Comp Off' or @LeaveType='ESI' or @LeaveType='LOP')
	begin
	insert into #EmpLeave exec(@sqlQuery)
	end
	select * from #EmpLeave order by Employee_Id,fromDate asc
drop table #EmpLeave
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveAnalysis]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author	: Kumuthini. L
-- Create Date	: 09-Apr-09
-- Description	: Leave Analysis Report
-- =============================================
--select * from ta_tbl_leveldetails
-- exec [Proc_TA_RptLeaveAnalysis] '01/Feb/2013', '28/feb/2013', '', '', '107','SuperAdmin', 0, 'Planned', 'WI', 'WOI',0
-- Proc_TA_RptLeaveAnalysis '01/Jan/2014','31/Jan/2014','','','3','SuperAdmin','0','Planned','WI','WOI',0
-- Proc_TA_RptLeaveAnalysis '01/Feb/2014','28/Feb/2014','','','107','EIT-PMs','8','Planned','WI','WOI',361
-- Proc_TA_RptLeaveAnalysis '01/Feb/2014','28/Feb/2014','','','107','EIT-PMs','8','Planned','WI','WOI',361
--  Proc_TA_RptLeaveAnalysis '01/Jan/2014','31/Jan/2014','','','3','SuperAdmin','0','Planned','WI','WOI',0
CREATE PROCEDURE [dbo].[Proc_TA_RptLeaveAnalysis] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(1000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@strLeavePlanned varchar(20), 
	@strLeaveWI varchar(20),
	@strLeaveWOI varchar(20),
	@EmpAutoId bigint
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@LevelID) as LevelId
	DECLARE @query AS VARCHAR(8000)
	SET @query = ''
	DECLARE @query1 AS VARCHAR(8000)
	SET @query1 = ''
	CREATE TABLE #Temp(LeaveType nVarchar(10))   
	INSERT INTO #Temp SELECT LeaveType FROM TA_Tbl_LeaveType WHERE IsDeleted = 0
	INSERT INTO #Temp VALUES('LOP')
	INSERT INTO #Temp VALUES('CompOff')
	INSERT INTO #Temp VALUES('ESI')
	INSERT INTO #Temp VALUES('RH')
	CREATE TABLE #TempProcessedData (
		[Employee_Code_Id] [nvarchar](20) NULL,
		[Date] [datetime] NULL,
		[Shift_Id] [int] NULL,
		[InTime] [nvarchar](25) NULL,
		[OutTime] [nvarchar](25) NULL,
		[HrsWork] [nvarchar](10) NULL,
		[HrsOT] [nvarchar](10) NULL,
		[NormOT] [nvarchar](10) NULL,
		[OffOT] [nvarchar](10) NULL,
		[HolOT] [nvarchar](10) NULL,
		[EarlyOut] [nvarchar](10) NULL,
		[LateIn] [nvarchar](10) NULL,
		[Attendance] [nvarchar](20) NULL,
		[WorkHrs] [nvarchar](10) NULL,
		[HrsLess] [nvarchar](10) NULL,
		[HrsExtra] [nvarchar](10) NULL,
		[LateInMins] [float] NULL,
		[EarlyOutMins] [float] NULL,
		[ExtraMins] [float] NULL,
		[OtMins] [float] NULL,
		[OvertimeStatus] [nvarchar](50) NULL,
		[TotalDays] [numeric](18, 1) NULL,
		[LeaveCode] [nvarchar](20) NULL,
		[LateEntryReason] [nvarchar](260) NULL,
		[EarlyOutReason] [nvarchar](260) NULL,
		[BreakOut] [nvarchar](25) NULL,
		[BreakIn] [nvarchar](25) NULL,
		[BreakHours] [nvarchar](10) NULL,
		[BreakLate] [nvarchar](10) NULL,
		[BreakLateMins] [float] NULL,
		[TotalLate] [nvarchar](10) NULL,
		[TotalLateMins] [float] NULL,
		[ProcessFlag] [int] NULL,
		[Status] [nvarchar](50) NULL,
		[FNAttendanceCode] [nvarchar](15) NULL,
		[ANAttendanceCode] [nvarchar](15) NULL,
		[DinnerOut] [nvarchar](15) NULL,
		[DinnerIn] [nvarchar](15) NULL,
		[DinnerHours] [nvarchar](10) NULL,
		[DinnerLate] [nvarchar](10) NULL,
		[DinnerLateMins] [float] NULL,
	[LateExit] [bit] NULL,
		[EarlyEntry] [bit] NULL
	)
	insert into #TempProcessedData 
	select  Employee_Code_Id, Date, Shift_Id, InTime, OutTime, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, Attendance, WorkHrs, HrsLess, HrsExtra, LateInMins, EarlyOutMins, ExtraMins, OtMins, OvertimeStatus, TotalDays, LeaveCode, LateEntryReason, EarlyOutReason, BreakOut, BreakIn, BreakHours, BreakLate, BreakLateMins, TotalLate, TotalLateMins, ProcessFlag, Status, FNAttendanceCode, ANAttendanceCode, DinnerOut, DinnerIn, DinnerHours, DinnerLate, DinnerLateMins, LateExit, EarlyEntry from TA_Tbl_ProcessedData where 
	(ta_tbl_processedData.date >= CONVERT(DATETIME, cast( @fromDat as nvarchar(50)), 102)) 
	AND (ta_tbl_processedData.date <= CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)) 
	SET @query = 'SELECT replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as Level,(dbo.Func_TA_AbsentDate('''+ cast(@fromDat as varchar(20)) + ''', ''' + cast(@toDat as varchar(20)) + ''', emp.employee_Code_id ) + '' '' + dbo.Func_TA_PendingLeaveDate('''+ cast(@fromDat as varchar(20)) + ''', ''' + cast(@toDat as varchar(20)) + ''', emp.employee_id )) as AbsentDate,dbo.Func_TA_LeaveDate('''+ cast(@fromDat as varchar(20)) + ''', ''' + cast(@toDat as varchar(20)) + ''', emp.employee_id ) as LeaveDate,dbo.Func_TA_PermissionDate('''+ cast(@fromDat as varchar(20)) + ''', ''' + cast(@toDat as varchar(20)) + ''', emp.employee_id ) as PermiDate, emp.employee_code_id as [Employee Id],isnull(emp.Employee_FirstName,'''') + SPACE(1) + isnull(emp.Employee_MiddleName,'''')+ SPACE(1) + isnull(emp.Employee_LastName,'''') AS [Employee Name],'
	SET @query = @query + ' ''Total Late Days'' =  ISNULL(count(CASE lateinmins WHEN 0 THEN NULL ELSE CASE FNAttendanceCode WHEN ''Present'' THEN lateinmins ELSE CASE ANAttendanceCode WHEN ''Present'' THEN lateinmins END END END),0)  , '
	SET @query = @query + ' ''Total Late Hours'' =  ISNULL(sum(CASE lateinmins WHEN NULL THEN 0 ELSE CASE FNAttendanceCode WHEN ''Present'' THEN lateinmins ELSE CASE ANAttendanceCode WHEN ''Present'' THEN lateinmins ELSE 0 END END END),0) '	
	SET @query = @query + ' ,ISNULL(Per.PermissionHours,0) AS PermissionHours, isnull(Leave.LeaveType,''CL'') as LeaveType, isnull(Leave.LeaveTypeTotalDays,0) as LeaveTypeTotalDays,isnull(Leave.IntimationType,''P'') as IntimationType FROM '	
	SET @query = @query + ' (SELECT E.Leave_Sanc_Authority,E.Reporting_To,E.Employee_Id,E.SwipeCardNo,E.employee_code_id,E.Employee_FirstName,E.Employee_MiddleName,E.Employee_LastName,E.Employee_Status,E.Report_Exclude,E.IsDeleted from TA_Tbl_Employee E ) emp'
	SET @query = @query + ' inner join #TempProcessedData on #TempProcessedData.Employee_code_id = emp.SwipeCardNo'
	SET @query = @query + ' inner join TA_Tbl_EmployeeLevel on emp.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	SET @query = @query + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id '
	SET @query = @query + ' inner join TA_Tbl_EmployeeDesignation ON emp.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId'
	SET @query = @query + ' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @query = @query + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @query = @query + ' inner join #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId '
    SET @query = @query + ' LEFT OUTER JOIN ( SELECT Per.Employee_Id,SUM(DateDiff(n,Per.Permission_FromTime,Per.Permission_ToTime)) AS PermissionHours '
	SET @query = @query + ' FROM TA_Tbl_Permission Per LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Id = Per.Employee_Id '
	SET @query = @query + ' where (Per.permission_date >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '	
	SET @query = @query + ' and (Per.permission_date <= CONVERT(DATETIME, ''' +cast( @todat as nvarchar(50))   + ''', 102))  and per.permission_status=''Approved'' and per.IsDeleted=''0''	'
	SET @query = @query + ' GROUP BY Per.Employee_Id ) Per ON Per.Employee_Id = emp.Employee_Id '
	SET @query = @query + ' LEFT OUTER JOIN (SELECT L.Employee_Id,LeaveType = CASE L.Type WHEN ''Leave'' THEN '
	SET @query = @query + ' (SELECT LeaveType FROM TA_Tbl_LeaveType WHERE LeaveType_Id = L.LeaveType_id) '
	SET @query = @query + ' ELSE L.Type END, sum(NumberOfDays) AS "LeaveTypeTotalDays" ,L.IntimationType'
	SET @query = @query + ' FROM TA_Tbl_LeaveApplication L '
	SET @query = @query + ' LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id '
	set @query = @query + ' where L.Status=''Approved'' and L.isdeleted=0 and (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between L.Leave_FromDate and L.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between L.Leave_FromDate and L.Leave_ToDate) )'
	set @query = @query + ' or (L.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (L.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if(@strLeavePlanned!='' and @strLeaveWI!='' and @strLeaveWOI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''P'' or L.Intimationtype=''UP-WI'' or L.Intimationtype=''UP-WOI'')'
		end
	else if(@strLeavePlanned!='' and @strLeaveWI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''P'' or L.Intimationtype=''UP-WI'') '
		end
	else if(@strLeaveWI!='' and @strLeaveWOI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''UP-WI'' or L.Intimationtype=''UP-WOI'') '
		end
	else if(@strLeavePlanned!='' and @strLeaveWOI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''P'' or L.Intimationtype=''UP-WOI'') '
		end
	else if (@strLeavePlanned!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''P'') '
		end
	else if(@strLeaveWOI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''UP-WOI'') '
		end
	else if(@strLeaveWI!='')
		begin
			set @query = @query + ' and (L.Intimationtype=''UP-WI'') '
		end
	SET @query = @query + ' GROUP BY L.Employee_Id,E.Employee_Id,E.SwipeCardNo,E.employee_code_id,E.Employee_FirstName,E.Employee_MiddleName,E.Employee_LastName,E.Employee_Status,E.Report_Exclude,E.IsDeleted,L.LeaveType_id,L.Type,L.IntimationType) Leave ON Leave.Employee_Id=emp.Employee_Id '        	SET @query1 = @query1 + ' where  emp.IsDeleted = 0 AND emp.report_exclude = 0 AND emp.employee_status = 1 AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  TA_Tbl_EmployeeLevel.EmployeeId = emp.Employee_Id AND TA_Tbl_EmployeeLevel.EffectiveDate <=CONVERT(DATETIME,''' + cast( @toDat as nvarchar(50))  + ''', 102) order by TA_Tbl_EmployeeLevel.EffectiveDate desc) '
	SET @query1 = @query1 + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @query1 = @query1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' 
			AND (Emp.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or Emp.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''') '
		END 
	IF NOT(@EmployeeName = '' OR @EmployeeName = '0')
		BEGIN
			Declare @Tempname nvarchar(200)
			set @Tempname= '(emp.Employee_FirstName + '' '' + isnull(emp.Employee_LastName,'''')'
			set @query1 = @query1 + ' and '+ @Tempname +'= ''' + cast(@EmployeeName as nvarchar(100)) + ''')'
		END
	IF NOT (@empId = '' OR @empId = '0')
		BEGIN
			SET @query1 = @query1 + ' and emp.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
		END
	 if(@isReportingto > 0)
		BEGIN
			set @query1 = @query1 + ' and (emp.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	SET @query1 = @query1 + ' group by emp.employee_code_id,emp.employee_id,emp.employee_firstname,emp.employee_middlename,emp.employee_lastname, Per.PermissionHours, Leave.LeaveType, Leave.LeaveTypeTotalDays,Leave.IntimationType,ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  emp.employee_firstname'
	EXEC  (@query + @query1)
	DROP TABLE #Temp
	drop table #TempProcessedData
	drop table #EmployeeIds
	drop table #LevelRights
END
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveDetail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Kannappan
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptLeaveDetail]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @LeaveType VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 FromDate varchar(50),
	 ToDate varchar(50),
	 Days varchar(50),
	 Reason varchar(255),
	 Approved varchar(255)
	)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Declare @SelFromDate as varchar(50)
	Declare @SelToDate as varchar(50)
	Declare @Days as varchar(50)
	Declare @Reason as varchar(250)
	Declare @Approved as varchar(250)
	Set @SelFromDate = ''
	Set @SelToDate = ''
	Set @Days = ''
	Set @Reason = ''
	Set @Approved = ''
	Set @SelectSQL = ' '  
	Set @SelectSQL = @SelectSQL + 'SELECT ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + 'case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName 
as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
    Set @SelectSQL = @SelectSQL + 'D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, '
    Set @SelectSQL = @SelectSQL + 'C.Company_Logo AS Logo,R.Region_Name AS Region, convert(varchar,LA.Leave_FromDate,106), 
convert(varchar,LA.Leave_ToDate,106), LA.NumberOfDays, LA.Reason, LA.Status FROM TA_Tbl_Employee ED INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_Region R ON ED.Region_Id = R.Region_Id INNER JOIN '
    Set @SelectSQL = @SelectSQL + 'TA_Tbl_LeaveApplication LA on ED.SwipeCardNo = LA.Employee_Id Where LA.IsDeleted = ''1'' '
	Set @SelectSQL = @SelectSQL + 'And ED.IsDeleted = ''1'' '
	If Not (@EmployeeId = '' Or @EmployeeId = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.SwipeCardNo = ''' + @EmployeeId + ''' '
	End
	If Not (@CompanyID = '' Or @CompanyID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Company_Id = ''' + @CompanyID + ''' '
	End
	If Not (@RegionID = '' Or @RegionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Region_Id = ''' + @RegionID + ''' '
	End
	If Not (@BranchID = '' Or @BranchID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Branch_Id = ''' + @BranchID + ''' '
	End
	If Not (@DeptID = '' Or @DeptID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Dept_Id = ''' + @DeptID + ''' '
	End
	If Not (@SectionID = '' Or @SectionID = '0')
	Begin
		Set @SelectSQL = @SelectSQL + 'And ED.Section_Id = ''' + @SectionID + ''' '
	End
	If (@FromDate <> '' and @ToDate <> '')
	Begin
		Set @SelectSQL = @SelectSQL + 'And (( LA.Leave_FromDate  between ''' + @FromDate + ''' And ''' + @ToDate + 
''') or (LA.Leave_ToDate between ''' + @FromDate + ''' And ''' + @ToDate + '''))'
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  FromDate ,ToDate ,Days ,Reason , 
Approved)		
	Exec (@SelectSQL)
	Set @EmployeeName = @EmployeeName + '%'
	Select * From #TempReportTable where EmployeeName like @EmployeeName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveForEmail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Proc_TA_RptLeaveForEmail '2020/04/11','2022/04/11','','0','','0,24','All','All',0,0,'IndividualUsers','0','',0,0,'Both',5
-- =============================================
CREATE     PROCEDURE [dbo].[Proc_TA_RptLeaveForEmail]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	--Get the Current date time format
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @UserGroupName=ug.groupName from TA_Tbl_Employee e
	inner join TA_Tbl_Usergroup ug on e.UserGroup_Id=ug.groupId
	where e.Employee_Id=@EmpAutoID
	
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!='Superadmin' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)
	declare @sqlResHoliday as varchar(8000)
	declare @sqlESIDays as varchar(8000)
	declare @sqlCompDays as varchar(8000)
	declare @sqlLOPDays as varchar(8000)
	declare @sqlMonthlyLOP as varchar(8000)
	
	delete from #EmployeeIds where EmpAutoId=@EmpAutoID
	
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + 'SELECT 
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,	
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks
	FROM dbo.TA_Tbl_LeaveApplication INNER JOIN
	dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id
	INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id 
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id
	INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId
	INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where dbo.TA_Tbl_LeaveApplication.Type=''Leave'' 
	and 
	((dbo.TA_Tbl_Employee.Employee_Status = 1)
	or
	(dbo.TA_Tbl_Employee.Employee_Status = 0 and 
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_FromDate
	or
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_ToDate)
	)
	)
	) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
	set @sqlQuery = @sqlQuery + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlQuery = @sqlQuery + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_LeaveApplication.Status in(''Forwarded'',''Pending'')'
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end			
	set @sqlResHoliday=''
	if (@LeaveType='All')
		begin
			set @sqlResHoliday=' UNION '
		end
	set @sqlResHoliday = @sqlResHoliday + ' SELECT  
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	ta_tbl_Holiday.Holiday_Description as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,	
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlResHoliday = @sqlResHoliday + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlResHoliday = @sqlResHoliday + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlResHoliday = @sqlResHoliday + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlResHoliday = @sqlResHoliday + ' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlResHoliday = @sqlResHoliday + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlResHoliday = @sqlResHoliday + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlResHoliday = @sqlResHoliday + ' And dbo.ta_tbl_Holiday.Holiday_Type=''Y'' '
	set @sqlResHoliday = @sqlResHoliday + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) And (dbo.TA_Tbl_LeaveApplication.Type=''Restricted Holiday'')'
	set @sqlResHoliday = @sqlResHoliday + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlResHoliday = @sqlResHoliday + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if (@LeaveType='Restricted Holiday')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  '
		end
	set @sqlResHoliday = @sqlResHoliday + ' and dbo.TA_Tbl_LeaveApplication.Status in(''Forwarded'',''Pending'')'	
	if(@Gender<>'Both')
		begin
			set @sqlResHoliday = @sqlResHoliday + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlResHoliday = @sqlResHoliday + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlResHoliday = @sqlResHoliday + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end	
	
	-- Comp Off Leaves
	set @sqlCompDays=''
	if (@LeaveType='All')
		begin
			set @sqlCompDays=' UNION '
		end
	set @sqlCompDays = @sqlCompDays + ' SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	''Comp Off'' as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlCompDays = @sqlCompDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlCompDays = @sqlCompDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlCompDays = @sqlCompDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlCompDays = @sqlCompDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlCompDays = @sqlCompDays + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	set @sqlCompDays = @sqlCompDays + ' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlCompDays = @sqlCompDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ' 		
	set @sqlCompDays = @sqlCompDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlCompDays = @sqlCompDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Type= ''Comp Off'''
	set @sqlCompDays = @sqlCompDays + ' and dbo.TA_Tbl_LeaveApplication.Status in(''Forwarded'',''Pending'')'	
	if(@Gender<>'Both')
		begin
			set @sqlCompDays = @sqlCompDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlCompDays = @sqlCompDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlCompDays = @sqlCompDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
	--LOP Days
	set @sqlLOPDays = ''
	if (@LeaveType='All')
		begin
			set @sqlLOPDays=' UNION '
		end
	set @sqlLOPDays = @sqlLOPDays + 'SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
	replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'')
			else CONVERT(VARCHAR, Leave_ApplicationDate, '+CONVERT(varchar,@dateFormat)+') 
	end as applicationDate, 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_FromDate, '+CONVERT(varchar,@dateFormat)+') 
	end as fromDate , 
	case	when '+CONVERT(varchar,@dateFormat) +'=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
			else CONVERT(VARCHAR, Leave_ToDate, '+CONVERT(varchar,@dateFormat)+') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.ta_tbl_leavetype.leavetype + ''-'' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''  (''+rtrim(Intervening)+'')''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks'
	set @sqlLOPDays = @sqlLOPDays + ' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN'
	set @sqlLOPDays = @sqlLOPDays + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlLOPDays = @sqlLOPDays + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @sqlLOPDays = @sqlLOPDays + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.Status in(''Forwarded'',''Pending'')'	
	set @sqlLOPDays = @sqlLOPDays + ' where (dbo.TA_Tbl_LeaveApplication.Type=''LOP'' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) '
	set @sqlLOPDays = @sqlLOPDays + ' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '
	set @sqlLOPDays = @sqlLOPDays + ' AND (((CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )'
	set @sqlLOPDays = @sqlLOPDays + ' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, ''' +cast(@fromDat as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@todat as nvarchar(50))   + ''', 102)))'
	if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='ESI' or @LeaveType='Comp Off' or @LeaveType='LOP')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= ' + cast(@LeaveType as nvarchar(100))
		end
	if not(@LeaveStatus='All')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and dbo.TA_Tbl_LeaveApplication.Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end
	if(@Gender<>'Both')
		begin
			set @sqlLOPDays = @sqlLOPDays + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlLOPDays = @sqlLOPDays + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlLOPDays = @sqlLOPDays + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end	
	if (@LeaveType='All')
		begin
			exec(@sqlQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
		end
	if (@LeaveType='Restricted Holiday')
		begin
			exec(@sqlResHoliday)
		end
	if (@LeaveType='Comp Off')
		begin
			exec(@sqlCompDays)
		end
	if (@LeaveType='ESI')
		begin
			exec(@sqlESIDays)
		end
	if (@LeaveType='LOP')
		begin
			exec(@sqlLOPDays)
		end
	else if not(@LeaveType='All' or @LeaveType='Restricted Holiday' or @LeaveType='Comp Off' or @LeaveType='ESI' or @LeaveType='LOP')
		begin
			exec(@sqlQuery)
		end
	--print(@sqlQuery)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeavePolicyNotAllocated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptLeavePolicyNotAllocated '01/Jan/2016','31/Aug/2016','','0,1','',0,0,'SuperAdmin','0','',0,0,'Both',0
Created By : Sashma  
Created on : 10-May-2011  
Modified By		:	Gopinath.K
Modified Date	:	21-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
Descriptions	:	SQL Query OPtimazation.
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptLeavePolicyNotAllocated] 
(
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000), 
	 @EmployeeId varchar(max),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(20),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @EmpAutoId bigint
)			
AS  
BEGIN
	SET NOCOUNT ON;
	--Temporary table's creation
	--Get the Current date time format
	DECLARE @dateFormat as int
	set @dateFormat =(Select DateFormat from Func_TA_GetDateTimeFormat())
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
	set @sqlQuery = 'select e.Employee_Code_Id,e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') as EmpName,T.TitleName,Cat.CategoryName,e.Gender,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as LevelName, case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, e.DateOfJoining,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, e.DateOfJoining, '+CONVERT(varchar,@dateFormat)+') end AS ''DateOfJoining'' from TA_Tbl_Employee e '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join TA_Tbl_Category Cat on #EmpCategory.CategoryId = Cat.CategoryId '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where e.Employee_Id not in (select EmployeeID from TA_Tbl_Emp_LeavePolicy '
	set @sqlQuery = @sqlQuery + ' where (FromDate<= case when (CONVERT(DATETIME, '''+cast(@fromDat as nvarchar(20))+''', 102) <= e.DateOfJoining) then e.DateOfJoining else CONVERT(DATETIME, '''+cast(@fromDat as nvarchar(20))+''', 102) end  and ToDate>=CONVERT(DATETIME, '''+cast(@ToDat as nvarchar(20))+''', 102)))  '
	set @sqlQuery = @sqlQuery + ' and e.DateOfJoining<=CONVERT(DATETIME, '''+cast(@ToDat as nvarchar(20))+''', 102) and e.Isdeleted=0  and e.Report_exclude=0 '
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>=' + @GradeLevel  
		end
		if(@isReportingto > 0)
			BEGIN
			   set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
			END
	exec(@sqlQuery)  
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLessHoursWorked]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*     
Procedure Name : Proc_TA_RptMonthlyAttendance     
Tables  : TA_Tbl_Employee and TA_Tbl_ProcessedData     
Created By : Manikandan.R     
Created on : 30-Sep-2011
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
Proc_TA_RptLessHoursWorked '2019/01/01','2019/12/17','','',0,0,'SuperAdmin','','',0,0,'Both',0,'d',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptLessHoursWorked]    
(
 @fromDat datetime,
 @ToDat datetime,
 @EmployeeName varchar(max),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @Shift int,
 @TypeOfReport varchar(20),
 @EmpAutoId bigint
)    
AS     
BEGIN
	SET NOCOUNT ON;   	
	
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_EmployeeName varchar(max)
	Declare @local_EmployeeId varchar(max)
	Declare @local_employeeCategory int
	Declare @local_employeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_Shift int
	Declare @local_TypeOfReport varchar(20)
	Declare @local_EmpAutoId bigint
	
	set @local_fromDat=@fromDat
	set @local_ToDat=@ToDat
	set @local_EmployeeName=@EmployeeName
	set @local_EmployeeId=@EmployeeId
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_Shift=@Shift
	set @local_TypeOfReport=@TypeOfReport
	set @local_EmpAutoId=@EmpAutoId	
	
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	--Temporary table's creation   
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)   
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #LevelRights(LevelId int)   
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId   
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(50),InTime nvarchar(25),OutTime nvarchar(25),
	Shift_Id int,HrsWork nvarchar(10),anAttendanceCode nvarchar(15), 
	fnAttendanceCode nvarchar(15),wrkhrs nvarchar(10),LessFlag bit default(0),TotalLessHrs varchar(20))
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]    
	(   
		[Employee_Code_Id] ASC
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]    
	(   
		[EffectiveDate],[LevelId],[EmployeeId] ASC   
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]    
	(   
		[EffectiveDate],[DesignationId],[EmployeeId] ASC   
	)ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]    
	(   
		[EffectiveDate],[TypeId],[EmployeeId] ASC   
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]    
	(   
		[EffectiveDate],[CategoryId],[EmployeeId] ASC   
	)ON [PRIMARY]   
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_EmployeeId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_EmployeeId,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_EmployeeId,@local_employeeCategory	
	create table #EmployeeID(EmployeeID varchar(25))
	--To split up the comma separated values
	if(@local_EmployeeId is not null and @local_EmployeeId <> '')
		begin
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeId)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@local_EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))   
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData='insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee   
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
	If Not (@local_EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0 and TA_Tbl_Employee.report_exclude=0 '
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@local_Gender<>'Both') 
		begin 
			set @sqlTempProcessedData = @sqlTempProcessedData + ' and TA_Tbl_Employee.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' ' 
		end 
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1='
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,
	TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork, 
	TA_Tbl_ProcessedData.anAttendanceCode,
	TA_Tbl_ProcessedData.fnAttendanceCode,WorkHrs,''''
	,HrsLess
	as TotalLessHrs       
	from TA_Tbl_ProcessedData    
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id   
	where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,'''+cast( @local_fromDat as nvarchar(50))+''', 102))     
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''+cast(@local_ToDat as nvarchar(50))+''', 102))
	and anAttendanceCode not in(''Weekly Off'',''Holiday'')and fnAttendanceCode not in(''Weekly Off'',''Holiday'')'
	if(@local_Shift<>0) 
		begin 
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND TA_Tbl_ProcessedData.shift_id= '+  cast (@local_Shift as nvarchar(50))
		end 
	Execute(@sqlTempProcessedData1)
	update #TempProcessedData set LessFlag=1  where TotalLessHrs is not null and TotalLessHrs<>'00:00' and TotalLessHrs<>''
	declare @sqlQuery as varchar(max)   
	set @sqlQuery=''           
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,
							isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,
							replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,
							replace(T.TitleName,''&amp;'',''&'') as Designation,
							CASE	WHEN '+ CONVERT(varchar,@dateFormat) +'=106 THEN REPLACE(CONVERT(VARCHAR, DATE,'+ CONVERT(varchar,@dateFormat) +'),'' '',''-'') 
									ELSE CONVERT(VARCHAR, DATE, '+ CONVERT(varchar,@dateFormat) +') END AS DATE,
							pd.InTime,
							pd.OutTime,
							isnull(pd.wrkhrs,''00:00'') as shift_TotalWorkingHours,
							pd.HrsWork, 
							pd.TotalLessHrs,
							((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked,
							((substring(isnull(pd.wrkhrs,''00:00''),0,charindex('':'',pd.wrkhrs))*60) + (substring(isnull(pd.wrkhrs,''00:00''),(len(pd.wrkhrs)-1),2))) as TotalMinsAllocated,
							((substring(isnull(pd.TotalLessHrs,''00:00''),0,charindex('':'',pd.TotalLessHrs))*60) + (substring(isnull(pd.TotalLessHrs,''00:00''),(len(pd.TotalLessHrs)-1),2))) as TotalLessMins ' 
	set @sqlQuery = @sqlQuery + ' ,(CASE pd.Shift_Id WHEN ''-1'' THEN ''Weekly Off'' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
							e.Gender'
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e ' 
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ' 
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id' 
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ' 
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId' 
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'    
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id' 
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ' 
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ' 
	set @sqlQuery = @sqlQuery + ' where pd.LessFlag=1 
	and ((e.employee_Status=1)
	or
	(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.date,102))
	) '   
	if(@local_UserGroupName<>'SuperAdmin') 
		begin 
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel + '' 
		end
	DECLARE @sqlquery1 varchar(max)
	set @sqlquery1=@sqlQuery
	set @sqlQuery = @sqlQuery + ' order by e.Employee_Code_Id,e.Employee_FirstName,cast(pd.date as datetime)'
	---For Detailed LessHours Report
	if(@local_TypeOfReport='D')
		begin
			exec(@sqlQuery)  
		end
	---For Summary LessHours Report
	else if @local_TypeOfReport='s'
		begin
			Create table #LessHrsWorkingDaysCount(Employee_id varchar(20),empName varchar(200),BranchName varchar(50),Designation varchar(50),Gender varchar(10),
			TotalLessHrsCountDays varchar(20),TotalMinsAllocated varchar(20),TotalLessHrs varchar(20),WorkingDays varchar(10) default 0)
			set @sqlquery1='select p.Employee_Id,p.empName,p.BranchName,p.Designation,p.Gender,count(Employee_id) as TotalLessHrsCountDays,
			case when len(sum(p.TotalMinsAllocated)/60)=1 then ''0''+ convert(varchar(20),sum(p.TotalMinsAllocated)/60) 
				 else convert(varchar(20),sum(p.TotalMinsAllocated)/60)
			end
			+'':''+ 
			case when len(sum(p.TotalMinsAllocated)%60)=1 then ''0''+ convert(varchar(20),sum(p.TotalMinsAllocated)%60)  
				 else convert(varchar(20),sum(p.TotalMinsAllocated)%60)
			end
			as TotalMinsAllocated
			,
			case when len(convert(varchar(20),sum(p.TotalLessMins)/60))=1 then ''0''+convert(varchar(20),sum(p.TotalLessMins)/60)
			else
			convert(varchar(20),sum(p.TotalLessMins)/60) end +'':''+ 
			case when len(convert(varchar(20),sum(p.TotalLessMins)%60))=1 then ''0''+ convert(varchar(20),sum(p.TotalLessMins)%60)
			else convert(varchar(20),sum(p.TotalLessMins)%60) end
			as TotalLessHrs,''0'' as workingdays from(' + @sqlquery1 +')as p
			Group by Employee_Id,empName,
			p.BranchName,p.Designation,p.Gender order by Employee_Id'
			insert into #LessHrsWorkingDaysCount exec(@sqlQuery1)
			--For Counting Working Days from selected durations
			create table #LessHrsUpdateWorkingDays(WorkingDays varchar(10),Employee_id varchar(20))
			set @sqlQuery ='select * from(select Count(convert(int,datepart(D,[Date])))as Workingday,e.Employee_Code_Id 
			from TA_Tbl_Employee  e inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId  group by e.Employee_Code_Id)as a'
			insert into #LessHrsUpdateWorkingDays exec(@sqlQuery)
			Update #LessHrsWorkingDaysCount set WorkingDays=LHU.WorkingDays from #LessHrsWorkingDaysCount inner join
			#LessHrsUpdateWorkingDays LHU on #LessHrsWorkingDaysCount.Employee_id=LHU.Employee_id
			
			select	Employee_id,
					empName,
					Designation,					
					TotalMinsAllocated,					
					TotalLessHrs,
					WorkingDays,
					TotalLessHrsCountDays,					
					Gender,
					BranchName
			from #LessHrsWorkingDaysCount                        
		end
	--Remove the temporary tables here      
	drop table #EmpLevel   
	drop table #EmpDesignation   
	drop table #EmpType   
	drop table #EmpCategory                
	drop table #EmpProcessedData   
	drop table #LevelRights   
	drop table #TempProcessedData   
	drop table #TempEmployee  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptManualTimeEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Proc_TA_RptManualTimeEntry '','','2020/06/01','2020/07/27','0',0,0,'SuperAdmin','0','all','',0,0,'Male',0
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptManualTimeEntry] 
(
	-- Add the parameters for the stored procedure here
	@employeeName nvarchar(500),
	@employeeId nvarchar(50),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint
)
AS 
BEGIN
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(max)  
	set @sqlQuery = '' 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Temporary table's creation
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,@EmployeeId	
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	Declare @sqlTempProcessedData varchar(max) 
	set @sqlTempProcessedData=
	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'
	Execute(@sqlTempProcessedData)
	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	SET @TimeFormat=(Select TimeFormat from Func_TA_GetDateTimeFormat())
	
	SELECT distinct  dbo.TA_Tbl_Employee.Employee_Code_Id as ManualTimeEntry_Employee_Id, 
									ISNULL(TA_Tbl_Employee.Employee_FirstName, ' ') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, ' ') AS Employee_Name,TA_Tbl_Employee.Gender,replace(dbo.Ta_Tbl_levelDetails.name,'&amp;','&') as name, case when E.Employee_Id=1 then (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,'')) else (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,''))+'-'+E.Employee_code_id end as 'Created_By' , 
	case when @dateFormat=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.TimeStamp,@dateFormat),' ','-') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.TimeStamp, @dateFormat) end 
	+ 
	case	when @TimeFormat='hh:mm' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,TA_Tbl_ManualTimeEntry.TimeStamp,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),13,2),' ',''))=1 then ' 0'+ replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),12,6),' ','')
					else substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),12,6) end
			+' ' + substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),18,2)
	end 
	as 'Created_DateTime',
	case	when IsDiscrepancyEntry=1 then 'D' 
			when TA_Tbl_ManualTimeEntry.IsImported=0 then 'M' 
			when TA_Tbl_ManualTimeEntry.IsImported=1 then 'I' 
			when TA_Tbl_ManualTimeEntry.IsImported=2 then 'Mo' end as IsDiscrepancyEntry,
	case	when @dateFormat=106 then 
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_InDate,101),' ','-') 
	else  CONVERT(VARCHAR, ManualTimeEntry_InDate, 101) 
		end 
	AS ManualTimeEntry_InDate, 
	case	when @TimeFormat='hh:mm' then 
	 			substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,ManualTimeEntry_InTime,0)), 114),0,6)	 			
			else	substring(ManualTimeEntry_InTime,0,6)+' ' + substring(ManualTimeEntry_InTime,10,2) 					
	end ManualTimeEntry_InTime,
	
	case when Latitude_value is not null and Longitude_value is not null then 'M - ' + ManualTimeEntry_InPunchType
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_InPunchType end ManualTimeEntry_InPunchType,
	
	case	when @dateFormat=106 then 
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_OutDate,@dateFormat),' ','-') 
	else  CONVERT(VARCHAR, ManualTimeEntry_OutDate, @dateFormat) 
		end AS ManualTimeEntry_OutDate,
	case	when @TimeFormat='hh:mm' then 
	 			substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,ManualTimeEntry_OutTime,0)), 114),0,6)
			else	substring(ManualTimeEntry_OutTime,0,6)+' ' + substring(ManualTimeEntry_OutTime,10,2) 					
	end ManualTimeEntry_OutTime,
	case when Latitude_value is not null and Longitude_value is not null then 'M - ' + ManualTimeEntry_OutPunchType
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutPunchType end ManualTimeEntry_OutPunchType,
	TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status,
	
	case when Latitude_value is not null and Longitude_value is not null then Clock_Address else 
	replace(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Reason,'&amp;','&') end as ManualTimeEntry_Reason,  TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id,
	Convert(varchar, TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date, 
	TA_Tbl_Title.TitleName,
	
	
	case when E.Employee_Id=1 then
	(E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,'')) else (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,''))+'-'+E.Employee_code_id end as 'Modified_By' 
	,
	case when cast(101 as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.modify_date,101),' ','-') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.modify_date, 101) end 
	+ 
	case	when @TimeFormat='hh:mm' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,TA_Tbl_ManualTimeEntry.modify_date,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),13,2),' ',''))=1 then ' 0'+ replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),12,6),' ','')
					else substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),12,6) end
			+' ' + substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),18,2)
	end 
	Modified_DateTime,
	case when TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status='Pending' then '-'
	 Else E1.Employee_FirstName 
	 End As Approved_BY,
	Case when CONVERT(varchar,@dateFormat)=106 then REPLACE(CONVERT(VARCHAR,TA_Tbl_ManualTimeEntry.Timestamp,@dateFormat),' ','-')
			 else CONVERT(VARCHAR,TA_Tbl_ManualTimeEntry.Timestamp,@dateFormat)
			 End As Approved_Date,
	[Process Status]=case when Clk_Process='N' then 'Not Processed' else 'Processed' end  
	FROM TA_Tbl_Employee INNER JOIN TA_Tbl_ManualTimeEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id 
	Left outer join Ta_tbl_Employee E On E.Employee_id=TA_Tbl_ManualTimeEntry.Emp_Id  
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id  
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_Employee.SwipeCardNo 
	Inner join TA_Tbl_Employee E1 on E1.Employee_Id=TA_Tbl_ManualTimeEntry.Emp_Id 
	WHERE ((TA_Tbl_Employee.Employee_Status = 1) 
	or(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)
	>= 
	convert(varchar(11),TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,102))) 
	AND (TA_Tbl_Employee.Isdeleted = 0) AND 
	(TA_Tbl_Employee.report_exclude = 0) AND 
	(TA_Tbl_ManualTimeEntry.IsOnDuty=0) AND 
	((TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate >= CONVERT(DATETIME, @fromdate, 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate <= CONVERT(DATETIME, @toDate, 102) ) or (TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate >= CONVERT(DATETIME, @fromdate, 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate <= CONVERT(DATETIME, @toDate, 102) ))
	And(@Gender='Both' or TA_Tbl_Employee.Gender=@Gender)
	And(@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	And((ISNULL(@Status,'All')='All' or @Status='') or TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status=@Status)
	and(@isReportingto=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)))
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Procedure Name : Proc_TA_RptMonthClosure  '','1','1','787,788',0,0,'SuperAdmin','0','',1,0,'Both',1
Tables  : TA_Tbl_Employee,TA_Tbl_MonthClosure,TA_Tbl_PayrollProcessDetails,  
TA_Tbl_PayrollProcessLeaveDetails,Ta_Tbl_LeaveType, TA_Tbl_Title,TA_Tbl_LevelDetails  
Created By : Prabakaran    
Created on : 15-Oct-07    
Modified by : sashma
Modified on : 12-May-2011 
Modified By		:	Gopinath.K
Modified Date	:	18-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
Descriptions	:	SQL Query OPtimazation. 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthClosure]    
(  
 @EmployeeName varchar(max),    
 @LevelID varchar(8000),
 @MonthClosureId varchar(500),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoID int	
)
AS    
BEGIN 
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId] ,[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @toDate datetime
	set @toDate=GETDATE()
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @toDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @toDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @toDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @toDate,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as EmployeeName,
	Convert(varchar,MonthClosure_StartDate,106) + '' - '' + Convert(varchar,MonthClosure_EndDate,106) as Duration,
	ppd.HrsWork,ppd.HrsOT,ppd.NormOT,ppd.OFFOT,ppd.HolOT,ppd.EarlyOut,ppd.LateIn,ppd.WorkHrs as TotWorkHrs,
	ppd.HrsLess,ppd.HrsExtra,isnull(ppd.LeaveDays,0) as LeaveDays,isnull(ppd.PresentDays,0) as PresentDays,
	isnull(ppd.AbsentDays,0) as AbsentDays,isnull(ppd.Holidays,0) as Holidays,isnull(ppd.LOPDays,0) as LOPDays,
	replace(T.TitleName,''&amp;'',''&'') as TitleName,e.Gender,ppd.TotalPermissionHours,
	SPEC_NormOT1=isnull(ppd.SPEC_NormOT1,''00:00''),
	SPEC_NormOT2=isnull(ppd.SPEC_NormOT2,''00:00''),
	SPEC_OffOT1=isnull(ppd.SPEC_OffOT1,''00:00''),
	SPEC_OffOT2=isnull(ppd.SPEC_OffOT2,''00:00''),
	SPEC_HOLOT1=isnull(ppd.SPEC_HOLOT1,''00:00''),
	SPEC_HOLOT2=isnull(ppd.SPEC_HOLOT2,''00:00'')
	from TA_Tbl_MonthClosure mc inner join TA_Tbl_PayrollProcessDetails 
	ppd on ppd.MonthClosure_Id=mc.MonthClosure_Id'  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_Employee e on e.SwipeCardNo=ppd.Employee_Id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel Lev on Lev.employeeid = e.Employee_Id '
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID = L.Id '	
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON  T.TitleId = EDesig.DesignationId '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = Lev.levelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id '
		End
				If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and mc.IsDeleted=0'    
	if not(@MonthClosureId='' or @MonthClosureId='0')    
		begin    
			set @sqlQuery = @sqlQuery + ' And (mc.MonthClosure_Id In (' + @MonthClosureId + '))'    
		End 
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName'
	exec(@sqlQuery) 
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Proc_TA_RptMonthlyAttendance @MINWORKHOURS=N'',@FROMDAT='2019-01-01 00:00:00',@TODAT='2022-07-30 00:00:00',
@EMPLOYEENAME=N'',@LEVELID=N'',@EMPLOYEEID=N'',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'',@EMPSWIPECARD=N'',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N'both',@SHIFT=2,@DATALOADING=0,@EMPAUTOID=2,@EXPORT=0

exec Proc_TA_RptMonthlyAttendance @MinWorkHours=N'',@fromDat='2024/02/01 00:00:00',@ToDat='2024/09/04 00:00:00',
@EmployeeName=N'',@LevelID=N'0',@EmployeeId=N'',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=53,@DesignationID=0,@Gender=N'Both',@Shift=0,@DataLoading=0,@EmpAutoId=0,@Export=0

exec Proc_TA_RptMonthlyAttendance @MinWorkHours=N'',@fromDat='2024-02-01',@ToDat='2024-09-26',
@EmployeeName=N'',@LevelID=N'0',@EmployeeId=N'',@employeeCategory=0,@employeeType=0,
@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',
@Shift=0,@DataLoading=0,@EmpAutoId=0,@Export=1


*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
)   
AS    
BEGIN    
	
--	DECLARE @InputDate NVARCHAR(50) = @FROMDAT
--	DECLARE @InputDates NVARCHAR(50) = @TODAT
--	DECLARE @DateInDateTime DATETIME
--	DECLARE @DateInDateTimes DATETIME

---- Convert the input string to datetime
--	SET @DateInDateTime = CONVERT(DATETIME, @InputDate, 120)
--	SET @DateInDateTimes = CONVERT(DATETIME, @InputDates, 120)
---- Convert the datetime to the desired format
--	Set @FROMDAT= CONVERT(NVARCHAR(10), @DateInDateTime, 23)
--	Set @TODAT= CONVERT(NVARCHAR(10), @DateInDateTimes, 23)
--	print @FROMDAT
--	Print @TODAT


	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		id int identity(1,1),
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!='Superadmin')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER='BOTH' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME='Superadmin')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	

	declare @Count int=0, @loop int=1,@SQLStr nvarchar(MAX)=''
	create table #Emptest (
		EmployeeId nvarchar(20),
		LevelId int,
		Level1Name nvarchar(200),
		Level1Details nvarchar(200),
		Level2Name nvarchar(200),
		Level2Details nvarchar(200),
		Level3Name nvarchar(200),
		Level3Details nvarchar(200),
		Level4Name nvarchar(200),
		Level4Details nvarchar(200),
		Level5Name nvarchar(200),
		Level5Details nvarchar(200)
	)
	select @Count=count(*) from #EMPLEVEL
	while(@Count>=@loop)
		begin
			Set @SQLStr=''
			declare @EmpID nvarchar(20),@LoopLevelID bigint
			Select @EmpID=EMPLOYEE_CODE_ID,@LoopLevelID=LEVELID from #EMPLEVEL where id=@loop
			select @SQLStr=dbo.Func_TA_LoadSpace(@EmpID,@LoopLevelID,'#Emptest')
			execute(@SQLStr)
			Set @loop=@loop+1
		end
	
	--select * from #Emptest






	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			--updated by velumani for Abraj Monthly attendance design issue
			--case when vp.INTIME='00:00' then '' else vp.INTIME end,
			--case when vp.OUTTIME='00:00' then '' else vp.OUTTIME end,
			--vp.SHIFT_ID,
			--case when vp.HRSWORK='00:00' then '' else vp.HRSWORK end,
			(case when  vp.INTIME is null or vp.INTIME='00:00'  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME='00:00' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK='00:00' then null else vp.HRSWORK end) as HRSWORK,
		-------------------------
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY'))))
		AND ((INTIME IS NOT NULL OR not(INTIME='00:00')) OR (OUTTIME IS NOT NULL OR not(OUTTIME='00:00')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))
	)
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,'00:00'))
	if(@TOTALMIN='') set @TOTALMIN=0
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(50),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)		
	)	
	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	CASE	WHEN PD.FNATTENDANCECODE='PRESENT' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,'FN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION='M' then ' #' else '' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE ='PRESENT' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,'AN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION='M' then ' #' else '' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,'&AMP;','&') AS BRANCHNAME,
	REPLACE(T.TITLENAME,'&AMP;','&') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE='WEEKLY OFF' AND ANATTENDANCECODE='WEEKLY OFF' THEN	'-' 
			WHEN PD.FNATTENDANCECODE='HOLIDAY'OR ANATTENDANCECODE='HOLIDAY' THEN '-'
			ELSE PD.SUPPOSEDWORKHOURS 
	END 'SUPPOSEDWORKHOURS',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN 'BL' THEN ' - ' ELSE '' END + ISNULL(PD.STATUS,'')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),0,CHARINDEX(':',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE WHEN PD.SHIFT_ID='-1' THEN 'WEEKLY OFF' ELSE SHF.SHIFT_SHORTNAME +'('+SHF.Shift_StartTime+'-' +SHF.Shift_EndTime +')' END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN '-' 
				 WHEN PD.SHIFT_ID=-1 THEN '-'
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),'00:00'
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'NORMOTMINS',
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'WEEKOFFOTMINS',
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'HOLIDAYOTMINS',
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN '-' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	'00:00',
	'00:00',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+'/'+
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME='Superadmin' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'')='' or dbo.ConvertHoursToMinites(isnull(HRSWORK,'00:00'))>=@TOTALMIN)
		
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		BRANCHNAME,
		DESIGNATION,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,
		BREAKHOURS,
		LUNCHHOURS ,	
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION,
		
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		
		
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'' as Intime1,
		'' as OutTime1,		 
		'' as Intime2,
		'' as OutTime2,
		'' as Intime3,
		'' as OutTime3,
		'' as Intime4,
		'' as OutTime4,
		'' as Intime5,
		'' as OutTime5,
		'' as AcutalWorkedHours,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		
		FROM #TEMPMONTHLYATTENDANCE 
		
		ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	else IF(@EXPORT=8)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'' as Intime1,
		'' as OutTime1,		 
		'' as Intime2,
		'' as OutTime2,
		'' as Intime3,
		'' as OutTime3,
		'' as Intime4,
		'' as OutTime4,
		'' as Intime5,
		'' as OutTime5,
		'' as AcutalWorkedHours,
		InLocation,
		OutLocation ,
		InLatitude,
		InLongitude,
		OutLatitude ,
		OutLongitude,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)desc
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	ELSE
	BEGIN
		SELECT	DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth,DENSE_RANK()OVER(ORDER BY EMPLOYEE_ID) AS [SL.NO],
				BRANCHNAME AS LEVEL,
				EMPLOYEE_ID AS [EMPLOYEE ID],
				EMPNAME AS [EMPLOYEE NAME],
				DESIGNATION,
				CATEGORYNAME AS [EMPLOYEE CATEGORY],
				GENDER,
				CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
						ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) 
				END AS DATE,	
				CASE	WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' 
						ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME 
				END [SHIFT SHORTNAME],
				INTIME AS [IN TIME],
				OUTTIME AS [OUT TIME],
				HRSWORK AS [HOURS WORKED],	
				SHIFT_TOTALWORKINGHOURS AS [DEFINED WORK HOURS],
				FIRSTSESSION AS [FIRST SESSION],
				SECONDSESSION AS [SECOND SESSION],
				SPEC_NormOT1,
				SPEC_NormOT2,		
				SPEC_OffOT1,
				SPEC_OffOT2,
				SPEC_HOLOT1,
				SPEC_HOLOT2,
				SUPPOSEDWORKHOURS,
				CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
				Case when FNATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end as present,
				Case when FNATTENDANCECODE in('Absent') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Absent') then 0.5 else 0.0 end as Absent,
				Case when FNATTENDANCECODE in('Weekly Off') then 0.5 else 0.0 end + case when ANATTENDANCECODE IN('Weekly Off') then 0.5 else 0.0 end as WeeklyOff,
				Case when FNATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end as Holiday,
				Case when FNATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH')then 0.5 else 0.0 end as Leave
				,StatusCode,
				EARLYOUT,
				LATEIN,
				OVERTIME,
				NORMOTMIN,
				OFFOTMIN,
				HOLOTMIN,
				NORMOT,
				OFFOT,
				HOLOT,
				LATEINMIN,
				EARLYOUTMIN,
				TOTDEFWORKHRS,
				TOTSUPWORKHRS,
				OVERTIMESTATUS,
				NIGHTORMORN,
				LUNCHINTIME,
				LUNCHOUTTIME
				,INNOTATION,
				OUTNOTATION
				,BREAKHOURS,
				LUNCHHOURS ,
				BREAKHOURSMINS,
				LUNCHHOURSMINS,
				SHIFT_STARTTIME,
				SHIFT_ENDTIME,
				WEEKDAY_WORKHRS,
				WEEKNUMBER ,
				FNATTENDANCECODE,
				ANATTENDANCECODE,
				DESIGNATION,
				BRANCHNAME,DATE processDate
				,'' as Intime1,
				'' as OutTime1,		 
				'' as Intime2,
				'' as OutTime2,
				'' as Intime3,
				'' as OutTime3,
				'' as Intime4,
				'' as OutTime4,
				'' as Intime5,
				'' as OutTime5,
				'' as AcutalWorkedHours,
				MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,MonthNo,WEEKNUMBER
	END	
	
	select EMPLOYEE_ID,
	TotLate_Hours =dbo.ConvertMinsToHours(SUM(isnull(LATEINMIN,0))),
	TotEarlyOut_Hours =dbo.ConvertMinsToHours(SUM(isnull(EARLYOUTMIN,0))),
	TotOT_Hours =dbo.ConvertMinsToHours(SUM(isnull(OVERTIME,0))),
	TotWrk_Hours =dbo.ConvertMinsToHours(SUM(CONVERT(INT,ISNULL(TOTALMINSWORKED,'0')))),
	Prsnt_Days=	SUM(CASE WHEN FNATTENDANCECODE='Present' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Present' THEN 0.5 ELSE 0 END), 
	Absnt_Days=	SUM(CASE WHEN FNATTENDANCECODE='Absent' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Absent' THEN 0.5 ELSE 0 END) ,
	Wkoff_Days=	SUM(CASE WHEN FNATTENDANCECODE='Weekly Off' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Weekly Off' THEN 0.5 ELSE 0 END), 
	H_Days=		SUM(CASE WHEN FNATTENDANCECODE='Holiday' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='Holiday' THEN 0.5 ELSE 0 END) ,
	LOP_Days=	SUM(CASE WHEN FNATTENDANCECODE='LOP' THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE='LOP' THEN 0.5 ELSE 0 END),
	Leave_Days=	SUM(CASE WHEN FNATTENDANCECODE not in('Present','Absent','Weekly off','Holiday','LOP') THEN 0.5 ELSE 0 END)+ 
				SUM(CASE WHEN ANATTENDANCECODE not in('Present','Absent','Weekly off','Holiday','LOP') THEN 0.5 ELSE 0 END),
	Totcalen_Days=DATEDIFF(d,@FROMDAT,@TODAT),
	Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,Level4Name,Level4Details,Level5Name,Level5Details 
	FROM #TEMPMONTHLYATTENDANCE
	Inner join #Emptest ET on #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID=ET.EmployeeId 
	group by #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID,Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,Level4Name,Level4Details,Level5Name,Level5Details 
	order by EMPLOYEE_ID
	
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
Proc_TA_RptMonthlyAttendance_Ardlysis @MINWORKHOURS=N'',@FROMDAT='2019-12-11 00:00:00',@TODAT='2019-12-11 00:00:00',
@EMPLOYEENAME=N'',@LEVELID=N'1',@EMPLOYEEID=N'',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'0',@EMPSWIPECARD=N'',@PARENTID=1,@DESIGNATIONID=0,@GENDER=N'BOTH',@SHIFT=0,@DATALOADING=0,@EMPAUTOID=0,@EXPORT=0
,@FromDashboard=0
*/

--for attendance summary and reports menu monthly @FromDashboard = 0
-- for dashboard present tile click @FromDashboard = 1

CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
	,@FromDashboard  INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT))   
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10)
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF not(@local_GENDER='BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@local_GENDER AS NVARCHAR(8)) + ''' '  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) '  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@local_TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@local_EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	IF NOT (@local_EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			vp.INTIME,
			vp.OUTTIME,
			vp.SHIFT_ID,
			vp.HRSWORK,
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		((@local_DATALOADING=0 or 
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY'))))
		AND ((INTIME IS NOT NULL OR not(INTIME='00:00')) OR (OUTTIME IS NOT NULL OR not(OUTTIME='00:00'))))
		or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))
	)
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	DECLARE @POS AS INT  
	SET @POS = CHARINDEX(':',@local_MINWORKHOURS)  
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = SUBSTRING(@local_MINWORKHOURS,0,@POS)*60 + SUBSTRING(@local_MINWORKHOURS,@POS+1,2)  
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(10),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)		
	)
	CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_INNOTATION_OUTNOTATION] ON [DBO].#TEMPMONTHLYATTENDANCE(FIRSTSESSION,SECONDSESSION,INNOTATION,OUTNOTATION) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_DATE] ON [DBO].#TEMPMONTHLYATTENDANCE(FIRSTSESSION,SECONDSESSION,DATE) ON [PRIMARY]  
	IF (@local_MINWORKHOURS<>'')  
		BEGIN  
			DECLARE @SQLQUERYTEMP AS VARCHAR(MAX)    
			SET @SQLQUERYTEMP=''   
			SET @SQLQUERYTEMP =  'SELECT PD.EMPLOYEE_CODE_ID AS SWIPECARDNO,PD.DATE AS DATE,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALWORKMINS FROM TA_TBL_EMPLOYEE E '
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPDESIGNATION EDESIG ON E.EMPLOYEE_ID = EDESIG.EMPLOYEEID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' LEFT JOIN TA_TBL_SHIFT SH ON SH.SHIFT_ID = PD.SHIFT_ID '
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + ' WHERE  (	(E.EMPLOYEE_STATUS = 1) OR 	
			(E.EMPLOYEE_STATUS = 0 AND  CONVERT(NVARCHAR(11), E.INACTIVEDATE,102) >= CONVERT(NVARCHAR(11),PD.DATE,102)
			)) AND (E.ISDELETED = 0) AND (E.REPORT_EXCLUDE = 0)'
			INSERT INTO #EMPPROCESSEDDATA EXEC(@SQLQUERYTEMP)  
		END
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''PRESENT'' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''FN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END 
			ELSE PD.FNATTENDANCECODE
	END
	AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''PRESENT'' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''AN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END  
			ELSE PD.ANATTENDANCECODE
	END
	AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
	WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
	ELSE PD.SUPPOSEDWORKHOURS END ''SUPPOSEDWORKHOURS'',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED'  
	SET @SQLQUERY = @SQLQUERY + ' ,(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
						 WHEN PD.SHIFT_ID=-1 THEN ''-''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''00:00''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.OFFOT IS NOT NULL	THEN
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
						CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00''	THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''NORMOTMINS'',
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''WEEKOFFOTMINS'',
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''HOLIDAYOTMINS'',
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(NORMOT AS VARCHAR(50)) 
																		END 
		 END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(OFFOT AS VARCHAR(50)) 
																		END
		 END,
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																			ELSE CAST(HOLOT AS VARCHAR(50)) 
																	END
		 END,
	LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' ELSE OVERTIMESTATUS END,NIGHTORMORN,''00:00'',''00:00'',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CATEGORYNAME,WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),FNATTENDANCECODE,ANATTENDANCECODE,
	Case when FNATTENDANCECODE=ANATTENDANCECODE then 
					case	when ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
							else ANATTENDANCECODE
					end
		 else 
				case	when FNATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(FNATTENDANCECODE,1,1)
						else FNATTENDANCECODE
				end
				+''/''+
				case	when ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
						else ANATTENDANCECODE
				end
		end,
	CASE WHEN ISNULL(SPEC_NormOT1,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
																			END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,''00:00'')=''00:00''	THEN ''00:00'' ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
																			END
		 END'
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
	SET @SQLQUERY = @SQLQUERY + ' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID '
	IF (@local_MINWORKHOURS<>'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID'  
		END   
		SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
	
		AND((PD.DATE >= CONVERT(DATETIME, ''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + ''', 102) AND 
		PD.DATE <= CONVERT(DATETIME, ''' + CAST(@local_TODAT AS NVARCHAR(11)) + ''', 102)))
		'    
	--IF(@FromDashboard<>0)
	--	Begin
	--		SET @SQLQUERY = @SQLQUERY + ' AND (PD.FNATTENDANCECODE=''Present'' or PD.FNATTENDANCECODE=''Present'') '  
	--	End
	IF(@local_USERGROUPNAME<>'SUPERADMIN')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ' AND TA_TBL_GRADE.GRADE_LEVEL>=' + @local_GRADELEVEL + ''  
		END	
	IF (@local_MINWORKHOURS<>'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + 'AND #EMPPROCESSEDDATA.TOTALWORKMINS >= ' + CAST(@TOTALMIN AS NVARCHAR(8))    
		END	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	

	UPDATE #TEMPMONTHLYATTENDANCE SET 
	FIRSTSESSION=
		CASE	WHEN FIRSTSESSION IN('PRESENT','*PRESENT','HOLIDAY','*HOLIDAY','WEEKLY OFF','*WEEKLY OFF') AND INNOTATION='M' THEN  FIRSTSESSION+' #'	
				ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION 
		END,
	SECONDSESSION=
		CASE	WHEN SECONDSESSION IN('PRESENT','*PRESENT','HOLIDAY','*HOLIDAY','WEEKLY OFF','*WEEKLY OFF') AND OUTNOTATION='M' THEN  SECONDSESSION+' #'
				ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION 
		END
	FROM #TEMPMONTHLYATTENDANCE
		DECLARE @DATEFORMAT AS INT
		DECLARE @TIMEFORMAT AS NVARCHAR(10)
		SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()

		Create table #ClockDetailsPivot(
		EmpCodeId nvarchar(40),EmployeeAutoId int, Clockdate datetime, clk_Id int, Clocktime datetime, timename varchar(20)
		)

		insert into #ClockDetailsPivot
		select E.Employee_Code_Id,E.Employee_Id as EmployeeAutoId,Clk_Date,[Clk_Id],cast([Clk_InTime] as time(0)) as Clk_InTime,
		'intime'+ convert(varchar, ROW_NUMBER() over(partition by Clk_EmpId,clk_date order by Clk_InTime,Clk_EmpId)) as timename
		from TA_Tbl_ClockDetails 
		inner join TA_Tbl_Employee E on E.SwipeCardNo = TA_Tbl_ClockDetails.Clk_EmpId
		left join #TEMPMONTHLYATTENDANCE PD on PD.EMPLOYEE_ID = E.Employee_Code_Id  and Date = TA_Tbl_ClockDetails.Clk_Date

		where 
		ta_tbl_clockdetails.IsVoid=0 and 
		ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102)
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,CAST( @local_TODAT AS NVARCHAR(50)), 102)
		and Clk_InPunchType is not null 
		--and Clk_OutPunchType is not null
		
	    order by E.[Employee_Id]

		insert into #ClockDetailsPivot
		select E.Employee_Code_Id,E.Employee_Id as EmployeeAutoId,Clk_Date,[Clk_Id],cast([Clk_OutTime] as time(0)) as Clk_OutTime,
		'outtime'+ convert(varchar, ROW_NUMBER()over(partition by Clk_EmpId,clk_date order by Clk_InTime,Clk_EmpId)) as timename
		 from TA_Tbl_ClockDetails 
		inner join TA_Tbl_Employee E on E.SwipeCardNo = TA_Tbl_ClockDetails.Clk_EmpId		
		left join #TEMPMONTHLYATTENDANCE PD on PD.EMPLOYEE_ID = E.Employee_Code_Id and Date = TA_Tbl_ClockDetails.Clk_Date
		
		where 
		ta_tbl_clockdetails.IsVoid=0 and
		ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102)
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,CAST( @local_TODAT AS NVARCHAR(50)), 102)
		--and Clk_InPunchType is not null 
		and Clk_OutPunchType is not null	

		order by E.[Employee_Id]

	    --Pivot table

		create table #MonthlyDataset2 (EmpCodeId nvarchar(40),EmployeeAutoId int, Clockdate datetime, 
		intime1 datetime, outtime1 datetime,
		intime2 datetime, outtime2 datetime,
		intime3 datetime, outtime3 datetime,
		intime4 datetime, outtime4 datetime,
		intime5 datetime, outtime5 datetime
		)
		insert into #MonthlyDataset2 
		SELECT EmpCodeId,EmployeeAutoId,convert(date,Clockdate)Clockdate, 
		intime1,outtime1,intime2,outtime2,intime3,outtime3,intime4,outtime4,intime5,outtime5 
		 FROM   
		(SELECT EmpCodeId, EmployeeAutoId,Clockdate, Clocktime,timename FROM #ClockDetailsPivot) as Tab1  
		PIVOT  
		(  
		Max(Clocktime) FOR timename IN (intime1,intime2,intime3,intime4,intime5,outtime1,outtime2,outtime3,outtime4,outtime5)) AS Tab2 

	--select * from #TEMPMONTHLYATTENDANCE

	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		Format(ds2.intime1,'hh:mm tt') as Intime1,
		Format(ds2.outtime1,'hh:mm tt') as OutTime1,		 
		Format(ds2.intime2,'hh:mm tt') as Intime2,
		Format(ds2.outtime2,'hh:mm tt') as OutTime2,
		Format(ds2.intime3,'hh:mm tt') as Intime3,
		Format(ds2.outtime3,'hh:mm tt') as OutTime3,
		Format(ds2.intime4,'hh:mm tt') as Intime4,
		Format(ds2.outtime4,'hh:mm tt') as OutTime4,
		Format(ds2.intime5,'hh:mm tt') as Intime5,
		Format(ds2.outtime5,'hh:mm tt') as OutTime5,
		HRSWORK,
		dbo.ConvertMinsToHours(case when ds2.intime1 is not null and ds2.outtime1 is not null then DATEDIFF(MINUTE, ds2.intime1 , ds2.outtime1) else 0 end 
		+ case when ds2.intime2 is not null and ds2.outtime2 is not null then DATEDIFF(MINUTE, ds2.intime2 , ds2.outtime2)else 0 end 
		+ case when ds2.intime3 is not null and ds2.outtime3 is not null then DATEDIFF(MINUTE, ds2.intime3 , ds2.outtime3)else 0 end 
		+ case when ds2.intime4 is not null and ds2.outtime4 is not null then DATEDIFF(MINUTE, ds2.intime4 , ds2.outtime4)else 0 end 
		+ case when ds2.intime5 is not null and ds2.outtime5 is not null then DATEDIFF(MINUTE, ds2.intime5 , ds2.outtime5)else 0 end 
		)
		AS AcutalWorkedHours,
		LATEIN,
		EARLYOUT,
		NORMOT,
		LUNCHHOURS ,
		BREAKHOURS,
		FIRSTSESSION,
		SECONDSESSION,	
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,	
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		FROM #TEMPMONTHLYATTENDANCE 

		left join  #MonthlyDataset2 ds2 on (ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
		and ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID)
		--where ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID and ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
		where ((@FromDashboard = 1 and (FIRSTSESSION='Present' or SECONDSESSION='Present')) or (@FromDashboard = 0))
		ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	ELSE
	BEGIN
		SELECT			
				EMPLOYEE_ID AS [EMPLOYEE ID],
				EMPNAME AS [EMPLOYEE NAME],		
				CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
						ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) 
				END AS DATE,	
				CASE	WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' 
						ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME 
				END [SHIFT SHORTNAME],
				INTIME AS [IN TIME],
				OUTTIME AS [OUT TIME],
				Format(ds2.intime1,'hh:mm tt') as Intime1,
				Format(ds2.outtime1,'hh:mm tt') as OutTime1,		 
				Format(ds2.intime2,'hh:mm tt') as Intime2,
				Format(ds2.outtime2,'hh:mm tt') as OutTime2,
				Format(ds2.intime3,'hh:mm tt') as Intime3,
				Format(ds2.outtime3,'hh:mm tt') as OutTime3,
				Format(ds2.intime4,'hh:mm tt') as Intime4,
				Format(ds2.outtime4,'hh:mm tt') as OutTime4,
				Format(ds2.intime5,'hh:mm tt') as Intime5,
				Format(ds2.outtime5,'hh:mm tt') as OutTime5,
				HRSWORK AS [HOURS WORKED],					
			    dbo.ConvertMinsToHours(case when ds2.intime1 is not null and ds2.outtime1 is not null then DATEDIFF(MINUTE, ds2.intime1 , ds2.outtime1) else 0 end 
				+ case when ds2.intime2 is not null and ds2.outtime2 is not null then DATEDIFF(MINUTE, ds2.intime2 , ds2.outtime2)else 0 end 
				+ case when ds2.intime3 is not null and ds2.outtime3 is not null then DATEDIFF(MINUTE, ds2.intime3 , ds2.outtime3)else 0 end 
				+ case when ds2.intime4 is not null and ds2.outtime4 is not null then DATEDIFF(MINUTE, ds2.intime4 , ds2.outtime4)else 0 end 
				+ case when ds2.intime5 is not null and ds2.outtime5 is not null then DATEDIFF(MINUTE, ds2.intime5 , ds2.outtime5)else 0 end 
				)
				 AS AcutalWorkedHours,
				LATEIN,
				EARLYOUT,				
				NORMOT,
				BREAKHOURS,
				LUNCHHOURS ,
				FIRSTSESSION AS [FIRST SESSION],
				SECONDSESSION AS [SECOND SESSION],
				SHIFT_TOTALWORKINGHOURS AS [DEFINED WORK HOURS],			
				SPEC_NormOT1,
				SPEC_NormOT2,		
				SPEC_OffOT1,
				SPEC_OffOT2,
				SPEC_HOLOT1,
				SPEC_HOLOT2,
				SUPPOSEDWORKHOURS,
				CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
				Case when FNATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Present','Present #') then 0.5 else 0.0 end as present,
				Case when FNATTENDANCECODE in('Absent') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Absent') then 0.5 else 0.0 end as Absent,
				Case when FNATTENDANCECODE in('Weekly Off') then 0.5 else 0.0 end + case when ANATTENDANCECODE IN('Weekly Off') then 0.5 else 0.0 end as WeeklyOff,
				Case when FNATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE in('Holiday','RH') then 0.5 else 0.0 end as Holiday,
				Case when FNATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH') then 0.5 else 0.0 end + case when ANATTENDANCECODE not in('Present','Present #','Absent','Weekly Off','Holiday','RH')then 0.5 else 0.0 end as Leave
				,StatusCode,
				OVERTIME,
				NORMOTMIN,
				OFFOTMIN,
				HOLOTMIN,				
				OFFOT,
				HOLOT,
				LATEINMIN,
				EARLYOUTMIN,
				TOTDEFWORKHRS,
				TOTSUPWORKHRS,
				OVERTIMESTATUS,
				NIGHTORMORN,
				LUNCHINTIME,
				LUNCHOUTTIME
				,INNOTATION,
				OUTNOTATION,			
				BREAKHOURSMINS,
				LUNCHHOURSMINS,
				SHIFT_STARTTIME,
				SHIFT_ENDTIME,
				WEEKDAY_WORKHRS,
				WEEKNUMBER ,
				FNATTENDANCECODE,
				ANATTENDANCECODE,
				DESIGNATION,
				DATEPART(D,DATE) as processDay,
				left(datename(MONTH,DATE),3) as processMonth,
				DENSE_RANK()OVER(ORDER BY EMPLOYEE_ID) AS [SL.NO],
				BRANCHNAME AS LEVEL,
				DESIGNATION,
				CATEGORYNAME AS [EMPLOYEE CATEGORY],
				GENDER,
				BRANCHNAME,
				DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth	
		        FROM #TEMPMONTHLYATTENDANCE 
			    left join  #MonthlyDataset2 ds2 on (ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
			    and ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID)
				--where ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID and ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
				where ((@FromDashboard = 1 and (FIRSTSESSION='Present' or SECONDSESSION='Present')) or (@FromDashboard = 0))
		        ORDER BY EMPLOYEE_ID,processDate,WEEKNUMBER
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END	

	drop table #ClockDetailsPivot

	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 
Modified by gopinath on 19Jun15, for adding the break time in report   
Proc_TA_RptMonthlyAttendance_Dashboard '','29/May/2018','29/May/2018','','0','B001273',0,0,'uiStaff','4','',0,0,'Both',0,0,3
Proc_TA_RptMonthlyAttendance '','29/May/2018','29/May/2018','','0','B001273',0,0,'uiStaff','4','',0,0,'Both',0,0,3,0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId bigint
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsWork nvarchar(10),
		SupposedWorkHours nvarchar(10),
		Status nvarchar(50),
		Attendance nvarchar(20),
		anAttendanceCode nvarchar(15),
		fnAttendanceCode nvarchar(15),
		PrevShift_ID int,
		Process_Rec_ID bigint,
		Exactshift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		LateInmin	nvarchar(10),
		EarlyOut nvarchar(10),
		LateIn nvarchar(10),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		OTMINS decimal(18,0),
		EarlyOutMin int,
		overtimeStatus varchar(20),
		NightOrMorn int
		,InNotation char(1),
		OutNotation char(1),
		BreakHours varchar(20),
		LunchHours varchar(20),
		BreakHoursMins int,
		LunchHoursMins int
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Date],[Employee_Code_Id] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] 
	) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId]
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId]
	)ON [PRIMARY]  
	Declare @sqlEmpLevel nvarchar(4000)
	--insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	--insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	--insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(100)) + ''')'
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
	Execute(@sqlEmpCategory)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF(@GENDER<>'BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' '  
	END	
	if(@isReportingto > 0)
    BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + ' and (EMP.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	--if(@EmpAutoId > 0)
 --   BEGIN
	--	set @SQLEMPLEVEL = @SQLEMPLEVEL + ' and (EMP.Employee_ID IN (select * from #EmployeeIds)) '  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	EXECUTE(@SQLEMPLEVEL)	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ' 
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.SwipeCardNo '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.SwipeCardNo '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	'insert into #TempProcessedData 
	select	#EMPLEVEL.EMPLOYEEID,
			TA_Tbl_ProcessedData.Date,
			TA_Tbl_ProcessedData.Employee_Code_Id,
			TA_Tbl_ProcessedData.intime,
			TA_Tbl_ProcessedData.outtime,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.HrsWork,
			TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,
			TA_Tbl_ProcessedData.Attendance,
			TA_Tbl_ProcessedData.anAttendanceCode,
			TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.Process_Rec_ID,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime)
			,LateInMins,
			EarlyOut,
			LateIn,
			TA_Tbl_ProcessedData.NormOT,
			TA_Tbl_ProcessedData.OffOT,
			TA_Tbl_ProcessedData.HolOT,
			OtMins,
			case when charindex(''.'',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex(''.'',convert(varchar(20),EarlyOutmins))))
			else EarlyOutmins end,
			OvertimeStatus,
			0,
			InNotation,
			OutNotation,
			BreakHrs,
			LunchHrs,
			BreakHrsInMins,
			LunchHrsInMins
			FROM TA_TBL_PROCESSEDDATA 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102))
	AND (dbo.TA_Tbl_ProcessedData.ANAttendanceCode=''PRESENT'' or dbo.TA_Tbl_ProcessedData.FNAttendanceCode=''Present'' or (FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (intime<>''00:00'' or outtime<>''00:00''))
						or (FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' and (intime<>''00:00'' or outtime<>''00:00'')))' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND TA_Tbl_ProcessedData.shift_id= '+  cast (@Shift as nvarchar(50))
		end	
	if(@DataLoading<>0)
		begin			
			--Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday'')'  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + (
			select	case	when @DataLoading=1 then ' AND (TA_Tbl_ProcessedData.FNAttendanceCode= ''Holiday'' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''Holiday'')'
							when @DataLoading=2 then ' AND ((TA_Tbl_ProcessedData.FNAttendanceCode= ''Weekly Off'' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''Weekly Off'') or (TA_Tbl_ProcessedData.Shift_ID= -1))'
							else '	AND (((TA_Tbl_ProcessedData.FNAttendanceCode= ''Weekly Off'' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''Weekly Off'')or (TA_Tbl_ProcessedData.Shift_ID= -1))
									OR (TA_Tbl_ProcessedData.FNAttendanceCode= ''Holiday'' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''Holiday''))'					end)
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' and ((Intime is not null or intime<>''00:00'') or (outtime is not null or outtime<>''00:00''))'
		end
	--if(@DataLoading=2)
	--	begin
	--		Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND (pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'')'  
	--	end
	--if(@DataLoading=3)
	--	begin
	--		Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND ((pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'')
	--		OR (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday''))'
	--	end
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode='CL' 	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)='PM' and SUBSTRING(S.Shift_Endtime,7,8)='AM' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)='AM' and SUBSTRING(S.Shift_Endtime,7,8)='PM' and PD.OutTime>'00:00 AM' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id
	declare @pos as int  
	set @pos = charindex(':',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),
	Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),
	Date datetime,InTime varchar(30),OutTime varchar(30),
	HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),
	TotalMinsWorked varchar(30),Shift_ShortName varchar(20),
	shift_TotalWorkingHours varchar(20),Gender nvarchar(10),
	EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),
	NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),
	OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,
	TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),
	NightOrMorn int,LunchInTime nvarchar(20),LunchOutTime nvarchar(20)
	,InNotation char(1),OutNotation char(1)
	,BreakHours varchar(20),LunchHours varchar(20),
	BreakHoursMins int,LunchHoursMins int,
	Shift_StartTime	nvarchar(10),
	Shift_EndTime	nvarchar(10)
	)
	if (@MinWorkHours<>'')  
		begin  
			declare @sqlQueryTemp as varchar(max)    
			set @sqlQueryTemp=''   
			set @sqlQueryTemp =  'select pd.Employee_Code_Id as SwipeCardNo,pd.date as Date,((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalWorkMins from Ta_Tbl_Employee e '
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpDesignation EDesig on e.employee_id = EDesig.EmployeeId '  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '  
			Set @sqlQueryTemp = @sqlQueryTemp + ' Left JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id '
			set @sqlQueryTemp = @sqlQueryTemp + ' where  (	(e.Employee_Status = 1) or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102)
			)) AND (e.Isdeleted = 0) AND (e.report_exclude = 0)'
			insert into #EmpProcessedData exec(@sqlQueryTemp)  
		end
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''    	
	set @sqlQuery = 'select  pd.fnAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''FN'',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end as FirstSession
	,pd.anAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''AN'',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''Weekly Off'' and anAttendanceCode=''Weekly Off'' then	''-'' 
	when pd.fnAttendanceCode=''Holiday''or anAttendanceCode=''Holiday'' then ''-''
	else pd.SupposedWorkHours end ''SupposedWorkHours'',(pd.Attendance +  CASE pd.Status WHEN ''BL'' THEN '' - '' ELSE '''' END + isnull(pd.Status,'''')) as Status,((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked'  
	set @sqlQuery = @sqlQuery + ' ,(CASE pd.Shift_Id WHEN ''-1'' THEN ''Weekly Off'' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN ''-'' 
						 when pd.Shift_Id=-1 then ''-''
						 ELSE shf.shift_TotalWorkingHours END
				),''00:00''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''00:00'' end Overtime,
	CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''NormOTMins'',
	CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''WeekOffOTMins'',
	CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''HolidayOTMins'',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('':'',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('':'',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('':'',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('':'',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''-'' else OvertimeStatus end,NightOrMorn,''00:00'',''00:00'',InNotation,OutNotation,PD.BREAKHOURS,LunchHours,BreakHoursMins,LunchHoursMins,
	Shift_StartTime,Shift_EndTime
	 '
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + ' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id'  
		end   
		set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102)))'    
	if(@Gender<>'Both')  
		begin  
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end		
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')  
		begin  
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''  
		end	
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + 'and #EmpProcessedData.TotalWorkMins >= ' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'     	
	insert into #TempMonthlyAttendance exec(@sqlQuery)	
	Create table #TempOutPunches
	(
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_Date] [datetime] NULL,
		PunchType varchar(20)
	)	
	--insert into #TempOutPunches
	--select Clk_EmpId,min(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	--inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	--where ta_tbl_clockdetails.IsVoid=0
	--and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	--and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	--and Clk_InPunchType in('In','Shift In')	
	--group by Clk_EmpId,Clk_Date,Clk_InPunchType
	--insert into #TempOutPunches
	--select Clk_EmpId,max(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	--inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	--where ta_tbl_clockdetails.IsVoid=0
	--and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	--and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	--and Clk_OutPunchType in('Out','Shift Out')	
	--group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,min(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_OutPunchType in('Lunch Out')	
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,max(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_InPunchType in('Lunch In')	
	group by Clk_EmpId,Clk_Date,Clk_InPunchType	
	--update #TempMonthlyAttendance set InTime=case when (PunchType='Shift In' or PunchType='In') then TP.Clk_OutTime else TM.InTime end
	--from #TempMonthlyAttendance TM
	--inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	--and TP.PunchType in('In','Shift In')
	--update #TempMonthlyAttendance set OutTime=case when (PunchType='Shift Out' or PunchType='Out') then TP.Clk_OutTime else TM.OutTime end
	--from #TempMonthlyAttendance TM
	--inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	--and TP.PunchType in('Out','Shift Out')
	update #TempMonthlyAttendance set LunchInTime=case when PunchType='Lunch In' then TP.Clk_OutTime else TM.LunchInTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType='Lunch In'
	update #TempMonthlyAttendance set LunchOutTime=case when PunchType='Lunch Out' then TP.Clk_OutTime else TM.LunchOutTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType='Lunch Out'	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession='Present' OR FirstSession='*Present' OR FirstSession='Holiday' OR FirstSession='*Holiday' OR FirstSession='Weekly Off' OR FirstSession='*Weekly Off') and InNotation='M' then  FirstSession+' #'	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession='Present' OR SecondSession = '*Present' OR SecondSession ='Holiday' OR SecondSession ='*Holiday' OR SecondSession ='Weekly Off' OR SecondSession ='*Weekly Off')  and OutNotation='M' then  SecondSession+' #'
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	select 
	case	when (@TimeFormat)='hh:mm' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchInTime,0)), 114)
			else	substring(LunchInTime,13,5)+' ' + substring(LunchInTime,18,2) 					
	end LunchIn,
	case	when (@TimeFormat)='hh:mm' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchOutTime,0)), 114)
			else	substring(LunchOutTime,13,5)+' ' + substring(LunchOutTime,18,2) 					
	end LunchOut
	,FirstSession,SecondSession ,Employee_Id,empName,BranchName,Designation,
	case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
	else CONVERT(VARCHAR, Date, @dateFormat) end AS
	Date,
	InTime,OutTime,HrsWork,SupposedWorkHours,
	Status,convert(int,isnull(TotalMinsWorked,'0'))TotalMinsWorked,CASE WHEN Shift_ShortName='Weekly Off' THEN 'Off' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
	shift_TotalWorkingHours,Gender,EarlyOut,LateIn,overtime,NormOTMin,OffOTMin,HolOTMin,NormOT,OffOT,HolOT,
	convert(int,lateinMin)as lateinMin,
	convert(int,EarlyOutMin)as EarlyOutMin,TotDefWorkHrs,TotSupWorkHrs,overtimeStatus,BreakHoursMins,
	BreakHours=isnull(BreakHours,'-'),LunchHoursMins,LunchHours=isnull(LunchHours,'-'),
	Shift_StartTime,Shift_EndTime
	from #TempMonthlyAttendance
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    Script Date: 12/24/2013 14:17:35 ******/
/*
Proc_TA_RptMonthlyAttendance_Detail '','01/Feb/2015','28/Feb/2015','','0,22','',0,0,'SuperAdmin','0','',0,0,'Both',0,2
exec Proc_TA_RptMonthlyAttendance_Detail @MinWorkHours=N'',@fromDat='2014-10-01 00:00:00',@ToDat='2014-10-31 00:00:00',
@EmployeeName=N'',@LevelID=N'0',@EmployeeId=N'1111,',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',@Shift=0,@DataLoading=0
*/    
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    
 @MinWorkHours as varchar(10),   
 @fromDat datetime,    
 @ToDat datetime,    
 @EmployeeName varchar(max),    
 @LevelID varchar(8000),  
 @EmployeeId varchar(max),  
 @employeeCategory int,  
 @employeeType int,  
 @UserGroupName varchar(250),  
 @GradeLevel varchar(20),      
 @EmpSwipeCard varchar(20),  
 @ParentId int, 
@DesignationID int,  
@Gender varchar(10),
@Shift int ,
@DataLoading int,
@EmpAutoID int
AS    
BEGIN    
	SET NOCOUNT ON;
	Declare @Fromdate1 datetime
	set @Fromdate1 = @fromDat
	Declare @Count int
	declare @Diff int
	Declare @SQLDays nvarchar(2000)
	Declare @SQL nvarchar(max)
	Declare @SQLAttnDay nvarchar(max)
	Declare @SQLShiftDay nvarchar(max)
	Declare @SQLInDay nvarchar(max)
	Declare @SQLOutDay nvarchar(max)
	Declare @SQLTWHDay nvarchar(max)
	Declare @SQLLateInDay nvarchar(4000)
	Declare @SQLTempHeader nvarchar(4000)
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	set @Diff = datediff(d,@fromDat,@ToDat) +1
	insert into #TempHeader(id) values(1)
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)  
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,
		Shift_FH_StartTime nvarchar(25),Shift_FH_Endtime datetime,Shfit_SH_StartTime datetime,Shift_SH_Endtime nvarchar(25),HrsWork nvarchar(10),TotalMinsWorked int,
		Status nvarchar(50),Attendance nvarchar(100),anAttendanceCode nvarchar(100), fnAttendanceCode nvarchar(100),
		EarlyOut Numeric(18,0),LateIn Numeric(18,0),TotalLateMins int,TotalLate varchar(20),DayFNAttendanceCode nvarchar(100),
		DayANAttendanceCode nvarchar(100),AttandanceCode nvarchar(100),TotPresentDays nvarchar(15)  DEFAULT '0.0' ,TotHoursWorked nvarchar(15)DEFAULT '00:00',TotLateHrs nvarchar(15) DEFAULT '00:00'
		,TotLeaveDays nvarchar(15) DEFAULT '0.0',TotAbsentDays nvarchar(15) DEFAULT '0.0',PrevShift_ID int,
		TotalEarlyMins int,TotEOHrs nvarchar(15) DEFAULT '00:00',NormOt int,Offot int,Hot int,
		TotNormOT nvarchar(15) DEFAULT '00:00',
		TotOffOT nvarchar(15) DEFAULT '00:00',TotHOT nvarchar(15) DEFAULT '00:00',TotalLateAndEarlymins int,TotalEarlyPerDay nvarchar(20) default '00:00'
	)    
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[LevelId],[EmployeeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
	(  
		[DesignationId],[EmployeeId],[EffectiveDate] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[TypeId],[EmployeeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[CategoryId],[EmployeeId] ASC  
	)ON [PRIMARY]  
	--Employee Level insert in Temporary table
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData=	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ' 
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End	
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'
	Execute(@sqlTempProcessedData)
	select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0  
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @sqlTempProcessedData2 varchar(8000)
	set @sqlTempProcessedData1=	
	'insert into #TempProcessedData  
	select #TempEmployee.EmpAutoId,pd.Date,pd.Employee_Code_Id,REPLACE(lower(pd.InTime),'' '',''''),REPLACE(lower(pd.OutTime),'' '',''''),pd.Shift_Id,S.Shift_FirstHalf_StartTime ,cast(S.Shift_FirstHalf_EndTime as datetime),cast(S.Shift_SecondHalf_StartTime as datetime),
	S.Shift_SecondHalf_EndTime,pd.HrsWork, ((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))),pd.Status,pd.Attendance,  
	case when (anAttendanceCode=''Weekly Off'' and ((OutTime is not null and OutTime <> ''00:00'') or (InTime is not null and InTime <> ''00:00''))) then  anAttendanceCode   
	when (anAttendanceCode=''Holiday'' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then  anAttendanceCode   
	when (fnAttendanceCode=''Holiday'' and (OutTime is null or OutTime = ''00:00'') and (InTime is not null and InTime <> ''00:00'')) then  anAttendanceCode   
	when (anAttendanceCode=''RH'' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then anAttendanceCode   
	when (fnAttendanceCode=''RH'' and (OutTime is null or OutTime = ''00:00'') and (InTime is not null and InTime <> ''00:00'')) then anAttendanceCode   
	when (anAttendanceCode=''Present'' and fnAttendanceCode <> ''Present'' and (pd.EarlyOut <> ''00:00'')) then  pd.anAttendanceCode    
	when (anAttendanceCode=''Present'' and fnAttendanceCode = ''Present'' and (PD.EarlyOut <> ''00:00'' )) then pd.anAttendanceCode   
	else pd.anAttendanceCode   
	end,  
	case when (fnAttendanceCode =''Weekly Off'' and ((OutTime is not null and OutTime <> ''00:00'') or (InTime is not null and InTime <> ''00:00''))) then  fnAttendanceCode  
	when  (fnAttendanceCode=''Holiday'' and S.Shift_FirstHalf_EndTime is not null and CAST(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then fnAttendanceCode  
	when  (fnAttendanceCode=''RH'' and S.Shift_FirstHalf_EndTime is not null and CAST(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when (fnAttendanceCode=''Present'' and anAttendanceCode<>''Present'' and (pd.LateIn <> ''00:00'')) then pd.fnAttendanceCode  
	when (fnAttendanceCode=''Present'' and anAttendanceCode=''Present'' and (pd.LateIn <> ''00:00'')) then pd.fnAttendanceCode  
	else pd.fnAttendanceCode end,pd.EarlyOutMins,Pd.LateInMins,Pd.LateInMins, '''' as TotalLate,
	'''' as DayFNAttendanceCode,''''AS DayANAttendanceCode,'''','''','''','''','''',''''
	,S.Shift_Id,Pd.EarlyOutMins,'''',
	Case when PD.NormOT is not null AND pd.NormOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end, 
	case when Pd.OffOT is not NULL AND pd.OffOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end,
	case when pd.HolOT is not null AND pd.HolOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end,
	'''','''','''',case when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)=0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)=0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 else isnull(EarlyOutMins,0)+isnull(LateInMins,0) end,''''
	from TA_Tbl_ProcessedData PD  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id   
	left outer join TA_Tbl_Shift S on S.Shift_Id=pd.Shift_Id   
	inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)  
	where (date>=CONVERT(DATETIME,'''+cast(@FromDat as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102))'
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND pd.shift_id= '+  cast (@Shift as nvarchar(50))  + ''  
		end
	if(@DataLoading<>0)
		begin			
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + (select case when @DataLoading=1 then ' AND (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday'')'
						when @DataLoading=2 then ' AND ((pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'') or (pd.Shift_ID= -1))'
						else ' AND (((pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'')or (pd.Shift_ID= -1))
			OR (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday''))'
			end)
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' and ((Intime is not null or intime<>''00:00'') or (outtime is not null or outtime<>''00:00''))'
		end	
	Execute(@sqlTempProcessedData1)	   
	set @sqlTempProcessedData2=	
	'insert into #TempProcessedData  
	select #TempEmployee.EmpAutoId,pd.Date,pd.Employee_Code_Id,REPLACE(lower(pd.InTime),'' '',''''),REPLACE(lower(pd.OutTime),'' '',''''),pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,pd.HrsWork,
	((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))),pd.Status,pd.Attendance,  
	case when (anAttendanceCode=''Weekly Off'' and ((OutTime is not null and OutTime <> ''00:00'') or (InTime is not null and InTime <> ''00:00''))) then anAttendanceCode   
	when (anAttendanceCode=''Holiday'' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then  anAttendanceCode   
	when (fnAttendanceCode=''Holiday'' and (OutTime is null or OutTime = ''00:00'') and (InTime is not null and InTime <> ''00:00'')) then  anAttendanceCode   
	when (anAttendanceCode=''RH'' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then anAttendanceCode   
	when (fnAttendanceCode=''RH'' and (OutTime is null or OutTime = ''00:00'') and (InTime is not null and InTime <> ''00:00'')) then anAttendanceCode   
	when (anAttendanceCode=''Present'' and fnAttendanceCode <> ''Present'' and (pd.EarlyOut <> ''00:00'')) then  pd.anAttendanceCode    
	when (anAttendanceCode=''Present'' and fnAttendanceCode = ''Present'' and (PD.EarlyOut <> ''00:00'' )) then  pd.anAttendanceCode   
	else pd.anAttendanceCode end,  
	case when (fnAttendanceCode =''Weekly Off'' and ((OutTime is not null and OutTime <> ''00:00'') or (InTime is not null and InTime <> ''00:00''))) then  fnAttendanceCode  
	when  (fnAttendanceCode=''Holiday'' and S.Shift_FirstHalf_EndTime is not null and cast(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when  (fnAttendanceCode=''RH'' and S.Shift_FirstHalf_EndTime is not null and cast(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when (fnAttendanceCode=''Present'' and anAttendanceCode<>''Present'' and (pd.LateIn <> ''00:00'')) then pd.fnAttendanceCode  
	when (fnAttendanceCode=''Present'' and anAttendanceCode=''Present'' and (pd.LateIn <> ''00:00'')) then  pd.fnAttendanceCode  
	else pd.fnAttendanceCode end,pd.EarlyOutMins,Pd.LateInMins,Pd.LateInMins, LateIn as TotalLate,'''' as DayFNAttendanceCode,''''AS DayANAttendanceCode,'''','''','''','''','''',''''
	,S.Shift_Id,Pd.EarlyOutMins,'''',
	Case when PD.NormOT is not null AND pd.NormOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end, 
	case when Pd.OffOT is not NULL AND pd.OffOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end,
	case when pd.HolOT is not null AND pd.HolOT<>''00:00'' then cast(OtMins as varchar(50)) else 0 end,
	'''','''','''', case when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)=0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)=0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 else isnull(EarlyOutMins,0)+isnull(LateInMins,0) end,''''
	from TA_Tbl_ProcessedData PD  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id   
	left outer join TA_Tbl_Shift S on S.Shift_Id=pd.Shift_Id   
	where   
	(date>=CONVERT(DATETIME,'''+cast(@FromDat as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102))  
	and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + ' AND pd.shift_id= '+  cast (@Shift as nvarchar(50))  + ''  
		end
	if(@DataLoading<>0)
		begin			
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + (select case when @DataLoading=1 then ' AND (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday'')'
						when @DataLoading=2 then ' AND ((pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'') or (pd.Shift_ID= -1))'
						else ' AND (((pd.FNAttendanceCode= ''Weekly Off'' AND pd.ANAttendanceCode= ''Weekly Off'')or (pd.Shift_ID= -1))
			OR (pd.FNAttendanceCode= ''Holiday'' AND pd.ANAttendanceCode= ''Holiday''))'
			end)
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + ' and ((Intime is not null or intime<>''00:00'') or (outtime is not null or outtime<>''00:00''))'
		end	
	Execute(@sqlTempProcessedData2) 	
	--Added by Manjula.P on 19-Feb-2014 for getting weekly off codes from montlhy attendacne vertical
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
	select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
	(
	select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
	from #TempProcessedData where Shift_Id=-1 	
	)
	as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	where
	(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
	select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
	(
	select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
	from #TempProcessedData where PrevShift_ID=-1 	
	)
	as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	where
	(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   
	--Added by Manjula.P on 19-Feb-2014 for updating OD Entry as like from monthly attendacne report horizondal
	update pd set pd.fnAttendanceCode= pd.fnAttendanceCode + 
	[dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,pd.Employee_Code_Id,'FN',
	shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '' else '(BL)' end,	
	pd.anAttendanceCode=pd.anAttendanceCode + 
	[dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,pd.Employee_Code_Id,'AN',
	shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '' else '(BL)' end 
	from #TempProcessedData pd
	left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id
	Inner join TA_Tbl_Employee E on Pd.Employee_Code_Id=E.SwipeCardNo 
	where E.Isdeleted=0
	--**********************************************************************************************************  
	Set @SQL=''
	Set @SQL='Update #TempProcessedData set DayFNAttendanceCode= '
	Set @SQL= @SQL + ' Case #TempProcessedData.fnAttendanceCode ' 
	Set @SQL=@SQL+ 'WHEN ''Present'' THEN  
	CASE 
	WHEN anAttendanceCode=''Present'' and (#TempProcessedData.LateIn<>''0'') THEN ''*P''
	WHEN anAttendanceCode<>''Present'' and (#TempProcessedData.LateIn<>''0'' or #TempProcessedData.EarlyOut<>''0'')
	and cast(Intime as datetime)>=cast(#TempProcessedData.Shift_FH_Starttime as datetime) THEN ''*P''
	ELSE ''P''
	END '
	Set @SQL=@SQL+'WHEN ''Absent'' THEN ''A'' '
	Set @SQL=@SQL+'WHEN ''holiday (on duty)'' THEN ''OD'' '
	set @SQL = @SQL + ' when ''Holiday'' then case when ANAttendanceCode=''Holiday'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*H''
	when ANAttendanceCode<>''Holiday'' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''*H''
	else ''H'' end'
	set @SQL = @SQL + ' when ''Local Holiday'' then case when ANAttendanceCode=''Local Holiday'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*LH''
								  when ANAttendanceCode<>''Local Holiday'' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''*LH''
								  else ''LH'' end'
	set @SQL = @SQL + ' when ''RH'' then case when ANAttendanceCode=''RH'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*RH''
	when ANAttendanceCode<>''RH'' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''*RH''
	else ''RH'' end'
	set @SQL = @SQL + ' when ''Tour'' then ''T'' '	
	set @SQL = @SQL + ' when ''Training'' then ''TG'' '
	set @SQL = @SQL + ' when ''Weekly Off'' then case when (InTime is not null and Intime<> ''00:00'')then ''*W'' else ''W'' end '
	set @SQL = @SQL + ' when ''weekly off (on duty)'' then  ''OD'' '
	set @SQL = @SQL + ' when ''CL'' then ''CL'' '
	set @SQL = @SQL + ' when ''EL'' then ''EL'' '
	set @SQL = @SQL + ' when ''OL'' then ''OL'' '	
	set @SQL = @SQL + ' when ''Present (On Duty)'' then ''OD'' '	
	set @SQL = @SQL + ' when ''Comp Off'' then ''C'' '
	set @SQL = @SQL + ' when ''FieldDuty'' then ''FD'' '	
	set @SQL = @SQL + ' Else '''' + lower(FNAttendanceCode) + '''' '
	set @SQL = @SQL + ' end '
	set @SQL = @SQL + ' ,DayANAttendanceCode =case #TempProcessedData.ANAttendanceCode '
	set @SQL = @SQL + ' when ''Present''  then case 
	when FNAttendanceCode=''present'' and (#TempProcessedData.EarlyOut <> ''0'' ) then ''*P'' 
	when FNAttendanceCode<>''present'' and (#TempProcessedData.EarlyOut <> ''0'' ) then ''*P''
	else ''P'' end'
	set @SQL = @SQL + ' when ''Absent'' then ''A'' '
	Set @SQL=@SQL+'WHEN ''holiday (on duty)'' THEN ''OD'' '
	set @SQL = @SQL + ' when ''Holiday'' then case when FNAttendanceCode=''Holiday'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*H'' 
	when FNAttendanceCode<>''Holiday'' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''*H''
	else ''H'' end'
	set @SQL = @SQL + ' when ''Local Holiday'' then case when FNAttendanceCode=''Local Holiday'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*LH'' 
								  when FNAttendanceCode<>''Local Holiday'' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''*LH''
								  else ''LH'' end'	                             
	set @SQL = @SQL + ' when ''RH'' then case when FNAttendanceCode=''RH'' and (Intime<> ''00:00'' or OutTime<>''00:00'') then ''*RH'' 
	when FNAttendanceCode<>''RH'' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''*RH''
	else ''RH'' end'
	set @SQL = @SQL + ' when ''Tour'' then ''T'' '	
	set @SQL = @SQL + ' when ''Training'' then ''TG'' '	
	set @SQL = @SQL + ' when ''Weekly Off'' then case when (Outtime is not null and Outtime<> ''00:00'') then ''*W'' else ''W'' end '
	set @SQL = @SQL + ' when ''weekly off (on duty)'' then  ''OD'' '
	set @SQL = @SQL + ' when ''CL'' then ''CL'' '
	set @SQL = @SQL + ' when ''EL'' then ''EL'' '
	set @SQL = @SQL + ' when ''OL'' then ''OL'' '	
	set @SQL = @SQL + ' when ''Present (On Duty)'' then ''OD'' '
	set @SQL = @SQL + ' when ''Comp Off'' then ''C'' '	
	set @SQL = @SQL + ' when ''FieldDuty'' then ''FD'' '
	set @SQL = @SQL + ' Else '''' + lower(ANAttendanceCode) + '''''
	Set @SQL= @SQL + ' END'
	Exec (@SQL)
	--Select 1
	Set @SQL=''   
	Set @SQL='Update #TempProcessedData Set AttandanceCode=DayFNAttendanceCode+''/ ''+DayANAttendanceCode'
	Exec (@SQL)Set @SQL='' 
	--Present
	update #TempProcessedData set  TotPresentDays =Isnull (REPLACE(A.Present,'','0.0'),'0.0')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE fnattendanceCode When 'Present' Then 0.5 When 'Holiday' Then 0.5 Else 0 END) + sum(CASE fnattendanceCode When 'Tour' Then 0.5 Else 0 END) + sum(CASE fnattendanceCode When 'Weekly off' Then 0.5 Else 0 END) + 
	sum(CASE anattendanceCode When 'Present' Then 0.5 When 'Holiday' Then 0.5 Else 0 END)+sum(CASE anattendanceCode When 'Tour' Then 0.5 Else 0 END)+sum(CASE anattendanceCode When 'Weekly off' Then 0.5 Else 0 END)) as Present,Employee_code_Id 
	from #TempProcessedData group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
--Total Early out hours
	update #TempProcessedData set  TotEOHrs= Isnull (REPLACE(A.LateInHours,'','00:00'),'00:00')
	from #TempProcessedData TDA inner join 
	(
	select LateInHours=case when len(convert(varchar(20),sum(TotalEarlyMins)/60))=1 then '0'+convert(varchar(20),sum(TotalEarlyMins)/60)
	else convert(varchar(20),sum(TotalEarlyMins)/60)end+':'+
	case when convert(varchar(20),sum(TotalEarlyMins)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(TotalEarlyMins)%60))=1 then '0'+convert(varchar(20),sum(TotalEarlyMins)%60)
	else convert(varchar(20),sum(TotalEarlyMins)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id	
	--Total late hours
	update #TempProcessedData set  TotLateHrs=Isnull (REPLACE(A.LateInHours,'','00:00'),'00:00')
	from #TempProcessedData TDA inner join 
	(	
	select LateInHours=case when len(convert(varchar(20),sum(TotalLateMins)/60))=1 then '0'+convert(varchar(20),sum(TotalLateMins)/60)
	else convert(varchar(20),sum(TotalLateMins)/60)end+':'+
	case when convert(varchar(20),sum(TotalLateMins)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(TotalLateMins)%60))=1 then '0'+convert(varchar(20),sum(TotalLateMins)%60)
	else convert(varchar(20),sum(TotalLateMins)%60)end end
	,Employee_code_Id from 
	#TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	update #TempProcessedData set  TotalEarlyPerDay=Isnull (REPLACE(A.LateInHours,'','00:00'),'00:00')
	from #TempProcessedData TDA inner join 
	(	
	select LateInHours=case when len(convert(varchar(20),TotalLateAndEarlymins/60))=1 then '0'+convert(varchar(20),TotalLateAndEarlymins/60)
	else convert(varchar(20),TotalLateAndEarlymins/60)end+':'+
	case when convert(varchar(20),TotalLateAndEarlymins%60)=0 then
	'00' else case when len(convert(varchar(20),TotalLateAndEarlymins%60))=1 then '0'+convert(varchar(20),TotalLateAndEarlymins%60)
	else convert(varchar(20),TotalLateAndEarlymins%60)end end
	,Employee_code_Id,Date from 
	#TempProcessedData  
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id and A.Date=TDA.Date
	----Calculate late hrs
	----update #TempProcessedData set  TotLateHrs= Isnull (REPLACE(A.LateInHours,'','00:00'),'00:00')
	----from #TempProcessedData TDA inner join 
	----(
	--select LateInHours=
	--case when len(convert(varchar(20),sum(TotalEarlyMins)/60))=1 then (convert(varchar(20),sum(TotalLateMins)/60)+convert(varchar(20),sum(TotalEarlyMins)/60))/60
	--else convert(varchar(30),(convert(varchar(20),sum(TotalLateMins)/60)+convert(varchar(20),sum(TotalEarlyMins)/60))/60) end +':'+
	--case when convert(varchar(20),sum(TotalEarlyMins)%60)=0 then
	--'00' else case when len(convert(varchar(20),sum(TotalEarlyMins)%60))=1 then convert(varchar(30),(convert(varchar(20),sum(TotalLateMins)%60)+convert(varchar(20),sum(TotalEarlyMins)%60))%60)
	--else convert(varchar(20),(convert(varchar(20),sum(TotalLateMins)%60)+convert(varchar(20),sum(TotalEarlyMins)%60))%60) end end
	--,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	----) as A on TDA.Employee_Code_Id = A.Employee_code_Id	
	----End
	update #TempProcessedData set  TotNormOT= Isnull (REPLACE(A.WeekdayOT,'','00:00'),'00:00'),
	TotOffOT= Isnull (REPLACE(A.WOffot,'','00:00'),'00:00'),
	TotHOT= Isnull (REPLACE(A.Holiot,'','00:00'),'00:00')
	from #TempProcessedData TDA inner join 
	(
	select WeekdayOT=case when len(convert(varchar(20),sum(NormOt)/60))=1 then '0'+convert(varchar(20),sum(NormOt)/60)
	else convert(varchar(20),sum(NormOt)/60)end+':'+
	case when convert(varchar(20),sum(NormOt)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(NormOt)%60))=1 then '0'+convert(varchar(20),sum(NormOt)%60)
	else convert(varchar(20),sum(NormOt)%60)end end,
	WOffot=
	case when len(convert(varchar(20),sum(Offot)/60))=1 then '0'+convert(varchar(20),sum(Offot)/60)
	else convert(varchar(20),sum(Offot)/60)end+':'+
	case when convert(varchar(20),sum(Offot)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(Offot)%60))=1 then '0'+convert(varchar(20),sum(Offot)%60)
	else convert(varchar(20),sum(Offot)%60)end end,
	Holiot=
	case when len(convert(varchar(20),sum(Hot)/60))=1 then '0'+convert(varchar(20),sum(Hot)/60)
	else convert(varchar(20),sum(Hot)/60)end+':'+
	case when convert(varchar(20),sum(Hot)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(Hot)%60))=1 then '0'+convert(varchar(20),sum(Hot)%60)
	else convert(varchar(20),sum(Hot)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id		
	----Leave Availed
	update #TempProcessedData set  TotLeaveDays=  Isnull (REPLACE(A.LeaveAvailed,'','0.0'),'0.0')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE	when fnattendanceCode IS NULL  then 0 
						When fnattendanceCode ='Weekly off' Then 0 
						when fnattendanceCode ='Holiday' then 0 
						when fnattendanceCode ='Local Holiday' then 0  
						when fnattendanceCode ='Present' then 0 
						when fnattendanceCode ='Absent' then 0 
						when fnattendanceCode ='Tour' then 0 Else 0.5 END) + 
	sum(CASE When anattendanceCode is null then 0 
			 when anattendanceCode ='Weekly off' Then 0 
			 when anattendanceCode ='Holiday' then 0 
			 when anattendanceCode ='Local Holiday' then 0 
			 when anattendanceCode ='Present' then 0 
			 when anattendanceCode ='Absent' then 0 
			 when anattendanceCode ='Tour' then 0 Else 0.5 END)) as LeaveAvailed,Employee_code_Id 
	from TA_tbl_ProcessedData
	where Date between @fromDat and @ToDat
	group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--Absent
	update #TempProcessedData set  TotAbsentDays = Isnull (REPLACE(A.Absent,'','0.0'),'0.0')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE fnattendanceCode When 'Absent' Then 0.5 Else 0 END) + 
	sum(CASE anattendanceCode When 'Absent' Then 0.5 Else 0 END)) as Absent,Employee_code_Id 
	from #TempProcessedData group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--Total hours Worked
	update #TempProcessedData set  TotHoursWorked= Isnull ( REPLACE(A.LateInHours,'','00.00'),'00:00')
	from #TempProcessedData TDA inner join 
	(
	select LateInHours=case when len(convert(varchar(20),sum(TotalMinsWorked)/60))=1 then '0'+convert(varchar(20),sum(TotalMinsWorked)/60)
	else convert(varchar(20),sum(TotalMinsWorked)/60)end+':'+
	case when convert(varchar(20),sum(TotalMinsWorked)%60)=0 then
	'00' else case when len(convert(varchar(20),sum(TotalMinsWorked)%60))=1 then '0'+convert(varchar(20),sum(TotalMinsWorked)%60)
	else convert(varchar(20),sum(TotalMinsWorked)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	declare @pos as int  
	set @pos = charindex(':',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	if (@MinWorkHours<>'')  
		begin  
			declare @sqlQueryTemp as varchar(8000)    
			set @sqlQueryTemp=''   
			set @sqlQueryTemp = 'select pd.Employee_Code_Id as SwipeCardNo,CONVERT(VARCHAR,cast(pd.date as datetime),111) as Date,   pd.TotalMinsWorked from Ta_Tbl_Employee e '  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'      
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join #EmpDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '   
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join  #EmpCategory on e.Employee_Id =  #EmpCategory.EmployeeId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join #EmpType  on e.Employee_Id = #EmpType.EmployeeId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1'
			if not(@EmployeeName='' or @EmployeeName='0')    
				begin    
					set @sqlQueryTemp = @sqlQueryTemp + 'and (e.Employee_FirstName + isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'  
				end   
			set @sqlQueryTemp = @sqlQueryTemp + ' order by e.Employee_FirstName,cast(pd.date as datetime)'    
			insert into #EmpProcessedData exec(@sqlQueryTemp)
		end  
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''    
	set @sqlQuery = 'select isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,
	e.Employee_Code_Id as Employee_Id, replace(T.TitleName,''&amp;'',''&'') as Designation,
	CONVERT(VARCHAR,cast(pd.date as datetime),111) as Date,Pd.AttandanceCode,
	CASE pd.Shift_Id WHEN ''-1'' THEN ''Off'' ELSE shf.Shift_ShortName END
	Shift_ShortName,
	pd.InTime,
	pd.OutTime,pd.HrsWork,
	pd.TotalLate ,pd.TotPresentDays,pd.TotHoursWorked,pd.TotLateHrs,pd.TotLeaveDays ,pd.TotAbsentDays,pd.TotEOHrs,TotNormOT,
	TotOffOT ,TotHOT,TotalEarlyPerDay' 
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'      
	set @sqlQuery = @sqlQuery + ' inner join #EmpDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '   
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
	set @sqlQuery = @sqlQuery + ' inner join #EmpCategory  on e.Employee_Id = #EmpCategory.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId'  
	set @sqlQuery = @sqlQuery + ' inner join #EmpType  on e.Employee_Id = #EmpType.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId'  
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id '
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + ' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id'  
		end
	set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and((pd.date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102)))'    
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + 'and #EmpProcessedData.TotalWorkMins >= ' + cast(@TotalMin as nvarchar(8))    
		end
	if(@Gender<>'Both')  
		begin  
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')  
		begin  
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''  
		end  	 
	create table #MonthlyAttendancedata
	(EmployeeName nvarchar(255) ,EmployeeID nvarchar(255),Designation nvarchar(255),Date Datetime,Attandance nvarchar(50),ShiftName nvarchar(50),InTime nvarchar(25),OutTime nvarchar(25),
	WorkedHours nvarchar(15),LateHours nvarchar(15),TotPresentDays nvarchar(15),TotHoursWorked nvarchar(15),TotLateHours nvarchar(15),TotLeaveDays nvarchar(15),TotAbsentDays nvarchar(15),TotEOHrs nvarchar(15) DEFAULT '00:00'
	,TotNormOT nvarchar(15) DEFAULT '00:00', TotOffOT nvarchar(15) DEFAULT '00:00',TotHOT nvarchar(15) DEFAULT '00:00' 
,TotalEarlyPerDay nvarchar(20) default '00:00'
	)
	Insert Into #MonthlyAttendancedata 
	exec(@sqlQuery) 
	Set @sqlQuery=''
	create table #AllMonthlyAttendancedata
	(EmployeeName nvarchar(255) ,EmployeeID nvarchar(255),Designation nvarchar(255),TotPresentDays nvarchar(15),TotHoursWorked nvarchar(15),TotLateHours nvarchar(15),TotLeaveDays nvarchar(15),TotAbsentDays nvarchar(15),
	Attn_Day1 nvarchar(100) DEFAULT '-',Attn_Day2 nvarchar(100) DEFAULT '-',Attn_Day3 nvarchar(100) DEFAULT '-',Attn_Day4 nvarchar(100) DEFAULT '-',Attn_Day5 nvarchar(100) DEFAULT '-',Attn_Day6 nvarchar(100) DEFAULT '-',Attn_Day7 nvarchar(100) DEFAULT '-',Attn_Day8 nvarchar(100) DEFAULT '-',Attn_Day9 nvarchar(100) DEFAULT '-',Attn_Day10 nvarchar(100) DEFAULT '-',Attn_Day11 nvarchar(100) DEFAULT '-',Attn_Day12 nvarchar(100) DEFAULT '-',Attn_Day13 nvarchar(100) DEFAULT '-',Attn_Day14 nvarchar(100) DEFAULT '-',Attn_Day15 nvarchar(100) DEFAULT '-',Attn_Day16 nvarchar(100) DEFAULT '-',Attn_Day17 nvarchar(100) DEFAULT '-',Attn_Day18 nvarchar(100) DEFAULT '-',Attn_Day19 nvarchar(100) DEFAULT '-',Attn_Day20 nvarchar(100) DEFAULT '-',Attn_Day21 nvarchar(100) DEFAULT '-',Attn_Day22 nvarchar(100) DEFAULT '-',Attn_Day23 nvarchar(100) DEFAULT '-',Attn_Day24 nvarchar(100) DEFAULT '-',Attn_Day25 nvarchar(100) DEFAULT '-',Attn_Day26 nvarchar(100) DEFAULT '-',Attn_Day27 nvarchar(100) DEFAULT '-',Attn_Day28 nvarchar(100) DEFAULT '-',Attn_Day29 nvarchar(100) DEFAULT '-',Attn_Day30 nvarchar(100) DEFAULT '-',Attn_Day31 nvarchar(100) DEFAULT '-',
	Shift_Day1 nvarchar(100) DEFAULT '-',Shift_Day2 nvarchar(100) DEFAULT '-',Shift_Day3 nvarchar(100) DEFAULT '-',Shift_Day4 nvarchar(100) DEFAULT '-',Shift_Day5 nvarchar(100) DEFAULT '-',Shift_Day6 nvarchar(100) DEFAULT '-',Shift_Day7 nvarchar(100) DEFAULT '-',Shift_Day8 nvarchar(100) DEFAULT '-',Shift_Day9 nvarchar(100) DEFAULT '-',Shift_Day10 nvarchar(100) DEFAULT '-',Shift_Day11 nvarchar(100) DEFAULT '-',Shift_Day12 nvarchar(100) DEFAULT '-',Shift_Day13 nvarchar(100) DEFAULT '-',Shift_Day14 nvarchar(100) DEFAULT '-',Shift_Day15 nvarchar(100) DEFAULT '-',Shift_Day16 nvarchar(100) DEFAULT '-',Shift_Day17 nvarchar(100) DEFAULT '-',Shift_Day18 nvarchar(100) DEFAULT '-',Shift_Day19 nvarchar(100) DEFAULT '-',Shift_Day20 nvarchar(100) DEFAULT '-',Shift_Day21 nvarchar(100) DEFAULT '-',Shift_Day22 nvarchar(100) DEFAULT '-',Shift_Day23 nvarchar(100) DEFAULT '-',Shift_Day24 nvarchar(100) DEFAULT '-',Shift_Day25 nvarchar(100) DEFAULT '-',Shift_Day26 nvarchar(100) DEFAULT '-',Shift_Day27 nvarchar(100) DEFAULT '-',Shift_Day28 nvarchar(100) DEFAULT '-',Shift_Day29 nvarchar(100) DEFAULT '-',Shift_Day30 nvarchar(100) DEFAULT '-',Shift_Day31 nvarchar(100) DEFAULT '-',
	In_Day1 nvarchar(100) DEFAULT '-',In_Day2 nvarchar(100) DEFAULT '-',In_Day3 nvarchar(100) DEFAULT '-',In_Day4 nvarchar(100) DEFAULT '-',In_Day5 nvarchar(100) DEFAULT '-',In_Day6 nvarchar(100) DEFAULT '-',In_Day7 nvarchar(100) DEFAULT '-',In_Day8 nvarchar(100) DEFAULT '-',In_Day9 nvarchar(100) DEFAULT '-',In_Day10 nvarchar(100) DEFAULT '-',In_Day11 nvarchar(100) DEFAULT '-',In_Day12 nvarchar(100) DEFAULT '-',In_Day13 nvarchar(100) DEFAULT '-',In_Day14 nvarchar(100) DEFAULT '-',In_Day15 nvarchar(100) DEFAULT '-',In_Day16 nvarchar(100) DEFAULT '-',In_Day17 nvarchar(100) DEFAULT '-',In_Day18 nvarchar(100) DEFAULT '-',In_Day19 nvarchar(100) DEFAULT '-',In_Day20 nvarchar(100) DEFAULT '-',In_Day21 nvarchar(100) DEFAULT '-',In_Day22 nvarchar(100) DEFAULT '-',In_Day23 nvarchar(100) DEFAULT '-',In_Day24 nvarchar(100) DEFAULT '-',In_Day25 nvarchar(100) DEFAULT '-',In_Day26 nvarchar(100) DEFAULT '-',In_Day27 nvarchar(100) DEFAULT '-',In_Day28 nvarchar(100) DEFAULT '-',In_Day29 nvarchar(100) DEFAULT '-',In_Day30 nvarchar(100) DEFAULT '-',In_Day31 nvarchar(100) DEFAULT '-',
	Out_Day1 nvarchar(100) DEFAULT '-',Out_Day2 nvarchar(100) DEFAULT '-',Out_Day3 nvarchar(100) DEFAULT '-',Out_Day4 nvarchar(100) DEFAULT '-',Out_Day5 nvarchar(100) DEFAULT '-',Out_Day6 nvarchar(100) DEFAULT '-',Out_Day7 nvarchar(100) DEFAULT '-',Out_Day8 nvarchar(100) DEFAULT '-',Out_Day9 nvarchar(100) DEFAULT '-',Out_Day10 nvarchar(100) DEFAULT '-',Out_Day11 nvarchar(100) DEFAULT '-',Out_Day12 nvarchar(100) DEFAULT '-',Out_Day13 nvarchar(100) DEFAULT '-',Out_Day14 nvarchar(100) DEFAULT '-',Out_Day15 nvarchar(100) DEFAULT '-',Out_Day16 nvarchar(100) DEFAULT '-',Out_Day17 nvarchar(100) DEFAULT '-',Out_Day18 nvarchar(100) DEFAULT '-',Out_Day19 nvarchar(100) DEFAULT '-',Out_Day20 nvarchar(100) DEFAULT '-',Out_Day21 nvarchar(100) DEFAULT '-',Out_Day22 nvarchar(100) DEFAULT '-',Out_Day23 nvarchar(100) DEFAULT '-',Out_Day24 nvarchar(100) DEFAULT '-',Out_Day25 nvarchar(100) DEFAULT '-',Out_Day26 nvarchar(100) DEFAULT '-',Out_Day27 nvarchar(100) DEFAULT '-',Out_Day28 nvarchar(100) DEFAULT '-',Out_Day29 nvarchar(100) DEFAULT '-',Out_Day30 nvarchar(100) DEFAULT '-',Out_Day31 nvarchar(100) DEFAULT '-',
	TWH_Day1 nvarchar(100) DEFAULT '-',TWH_Day2 nvarchar(100) DEFAULT '-',TWH_Day3 nvarchar(100) DEFAULT '-',TWH_Day4 nvarchar(100) DEFAULT '-',TWH_Day5 nvarchar(100) DEFAULT '-',TWH_Day6 nvarchar(100) DEFAULT '-',TWH_Day7 nvarchar(100) DEFAULT '-',TWH_Day8 nvarchar(100) DEFAULT '-',TWH_Day9 nvarchar(100) DEFAULT '-',TWH_Day10 nvarchar(100) DEFAULT '-',TWH_Day11 nvarchar(100) DEFAULT '-',TWH_Day12 nvarchar(100) DEFAULT '-',TWH_Day13 nvarchar(100) DEFAULT '-',TWH_Day14 nvarchar(100) DEFAULT '-',TWH_Day15 nvarchar(100) DEFAULT '-',TWH_Day16 nvarchar(100) DEFAULT '-',TWH_Day17 nvarchar(100) DEFAULT '-',TWH_Day18 nvarchar(100) DEFAULT '-',TWH_Day19 nvarchar(100) DEFAULT '-',TWH_Day20 nvarchar(100) DEFAULT '-',TWH_Day21 nvarchar(100) DEFAULT '-',TWH_Day22 nvarchar(100) DEFAULT '-',TWH_Day23 nvarchar(100) DEFAULT '-',TWH_Day24 nvarchar(100) DEFAULT '-',TWH_Day25 nvarchar(100) DEFAULT '-',TWH_Day26 nvarchar(100) DEFAULT '-',TWH_Day27 nvarchar(100) DEFAULT '-',TWH_Day28 nvarchar(100) DEFAULT '-',TWH_Day29 nvarchar(100) DEFAULT '-',TWH_Day30 nvarchar(100) DEFAULT '-',TWH_Day31 nvarchar(100) DEFAULT '-',
	LateIn_Day1 nvarchar(100) DEFAULT '-',LateIn_Day2 nvarchar(100) DEFAULT '-',LateIn_Day3 nvarchar(100) DEFAULT '-',LateIn_Day4 nvarchar(100) DEFAULT '-',LateIn_Day5 nvarchar(100) DEFAULT '-',LateIn_Day6 nvarchar(100) DEFAULT '-',LateIn_Day7 nvarchar(100) DEFAULT '-',LateIn_Day8 nvarchar(100) DEFAULT '-',LateIn_Day9 nvarchar(100) DEFAULT '-',LateIn_Day10 nvarchar(100) DEFAULT '-',LateIn_Day11 nvarchar(100) DEFAULT '-',LateIn_Day12 nvarchar(100) DEFAULT '-',LateIn_Day13 nvarchar(100) DEFAULT '-',LateIn_Day14 nvarchar(100) DEFAULT '-',LateIn_Day15 nvarchar(100) DEFAULT '-',LateIn_Day16 nvarchar(100) DEFAULT '-',LateIn_Day17 nvarchar(100) DEFAULT '-',LateIn_Day18 nvarchar(100) DEFAULT '-',LateIn_Day19 nvarchar(100) DEFAULT '-',LateIn_Day20 nvarchar(100) DEFAULT '-',LateIn_Day21 nvarchar(100) DEFAULT '-',LateIn_Day22 nvarchar(100) DEFAULT '-',LateIn_Day23 nvarchar(100) DEFAULT '-',LateIn_Day24 nvarchar(100) DEFAULT '-',LateIn_Day25 nvarchar(100) DEFAULT '-',LateIn_Day26 nvarchar(100) DEFAULT '-',LateIn_Day27 nvarchar(100) DEFAULT '-',LateIn_Day28 nvarchar(100) DEFAULT '-',LateIn_Day29 nvarchar(100) DEFAULT '-',LateIn_Day30 nvarchar(100) DEFAULT '-',LateIn_Day31 nvarchar(100) DEFAULT '-'
	,TotEarlyOutHours nvarchar(15)	
	,TotNormOT nvarchar(15) DEFAULT '00:00', TotOffOT nvarchar(15) DEFAULT '00:00',TotHOT nvarchar(15) DEFAULT '00:00' 
	,TotalEarlyPerDay nvarchar(20) default '00:00'
	)
	Insert into #AllMonthlyAttendancedata (EmployeeName,EmployeeID,Designation,TotPresentDays,TotHoursWorked,TotLateHours,TotLeaveDays,TotAbsentDays,TotEarlyOutHours,TotNormOT , TotOffOT ,TotHOT)
	select distinct EmployeeName,EmployeeID,Designation,TotPresentDays,TotHoursWorked,TotLateHours,TotLeaveDays,TotAbsentDays,TotEOHrs
	,TotNormOT , TotOffOT ,TotHOT
	from #MonthlyAttendancedata 
	Declare @SQLUpdate varchar(max)
	--select * from #MonthlyAttendancedata
	set @SQLUpdate=''
	set @Count=1
	Set @SQLTempHeader=''
	set @Fromdate1=@fromDat
	while(@Count <=31)
		begin
			set @SQLTempHeader = @SQLTempHeader + ' update #TempHeader set Day'+cast(@Count as varchar(10)) + '=' + cast(datepart(d,@Fromdate1)as varchar(10)) + 'where id=1'
			exec(@SQLTempHeader)
			set @SQLTempHeader=''
			if(@Count <=@Diff and @Count<=31)
				begin 
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set Attn_Day'+ cast(@Count as varchar(10)) + '= Case When len(Isnull(#MonthlyAttendancedata.Attandance,''''))>0 then #MonthlyAttendancedata.Attandance Else ''-'' End'	
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' +CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
					set @SQLUpdate=''
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set Shift_Day'+ cast(@Count as varchar(10)) + ' = Case When len(Isnull(#MonthlyAttendancedata.ShiftName,''''))>0 then #MonthlyAttendancedata.ShiftName Else ''-'' End'
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' + CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
					set @SQLUpdate=''
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set In_Day'+ cast(@Count as varchar(10)) + ' = Case When len(Isnull(#MonthlyAttendancedata.InTime,''''))>0 then #MonthlyAttendancedata.InTime Else ''-'' End'
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' + CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
					set @SQLUpdate=''
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set Out_Day'+ cast(@Count as varchar(10)) + ' = Case When len(Isnull(#MonthlyAttendancedata.OutTime,''''))>0 then #MonthlyAttendancedata.OutTime Else ''-'' End'
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' + CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
					set @SQLUpdate=''
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set TWH_Day'+ cast(@Count as varchar(10)) + ' = Case When len(Isnull(#MonthlyAttendancedata.WorkedHours,''''))>0 then #MonthlyAttendancedata.WorkedHours Else ''-'' End'
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' + CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
					set @SQLUpdate=''
					set @SQLUpdate = @SQLUpdate + ' update #AllMonthlyAttendancedata set LateIn_Day'+ cast(@Count as varchar(10)) + ' = Case When len(Isnull(#MonthlyAttendancedata.TotalEarlyPerDay,''''))>0 then #MonthlyAttendancedata.TotalEarlyPerDay Else ''-'' End'
					set @SQLUpdate = @SQLUpdate + ' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	'
					set @SQLUpdate = @SQLUpdate + '	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, ''' + CAST(@Fromdate1 as varchar(50)) + ''' , 102)'
					exec(@SQLUpdate)
				end
			set @Fromdate1=dateadd(d,1,@Fromdate1)
			set @Count=@Count +1
		end	
	Select * from #AllMonthlyAttendancedata	
	select * from #TempHeader
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #TempHeader   
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee
	Drop table  #AllMonthlyAttendancedata    
	Drop table  #MonthlyAttendancedata 
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 
Modified by gopinath on 19Jun15, for adding the break time in report   
Proc_TA_RptMonthlyAttendance_Dashboard '','29/May/2018','29/May/2018','','0','B001273',0,0,'uiStaff','4','',0,0,'Both',0,0,3
Proc_TA_RptMonthlyAttendanceDashboard_Surguru '','2019-09-05 00:00:00.000','2019-09-05 00:00:00.000','','110','',0,0,'SuperAdmin','0','',110,0,'Both',0,0,0,115
*/
 --select * from TA_Tbl_ProcessedData where Employee_Code_Id in ('3210','3211','3212','3213') and date='20190905'
--select * from ta_tbl_levelDetails
--select * from testmontylysurguru
--Delete from testmontylysurguru
--create table testmontylysurguru (
--	MinWorkHours  nvarchar(10),
--	fromDat datetime,
--	ToDat datetime,
--	EmployeeName varchar(max),
--	LevelID varchar(8000),
--	EmployeeId varchar(max),
--	employeeCategory int,
--	employeeType int,
--	UserGroupName varchar(250),
--	GradeLevel varchar(20),
--	EmpSwipeCard varchar(20),
--	ParentId int,
--	DesignationID int,
--	Gender varchar(10),
--	Shift int,
--	DataLoading int,
--	EmpAutoId bigint,
--	workLocation int
--	)
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId bigint,
	@workLocation int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	--Temporary table's creation  
	insert into testmontylysurguru  values(
	@MinWorkHours,
	@fromDat,
	@ToDat,
	@EmployeeName,
	@LevelID,
	@EmployeeId,
	@employeeCategory,
	@employeeType,
	@UserGroupName,
	@GradeLevel,
	@EmpSwipeCard,
	@ParentId,
	@DesignationID,
	@Gender,
	@Shift,
	@DataLoading,
	@EmpAutoId
	,@workLocation 
	)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsWork nvarchar(10),
		SupposedWorkHours nvarchar(10),
		Status nvarchar(50),
		Attendance nvarchar(20),
		anAttendanceCode nvarchar(15),
		fnAttendanceCode nvarchar(15),
		PrevShift_ID int,
		Process_Rec_ID bigint,
		Exactshift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		LateInmin	nvarchar(10),
		EarlyOut nvarchar(10),
		LateIn nvarchar(10),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		OTMINS decimal(18,0),
		EarlyOutMin int,
		overtimeStatus varchar(20),
		NightOrMorn int
		,InNotation char(1),
		OutNotation char(1),
		BreakHours varchar(20),
		LunchHours varchar(20),
		BreakHoursMins int,
		LunchHoursMins int
		,Skills varchar(max)
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Date],[Employee_Code_Id] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] 
	) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId]
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId]
	)ON [PRIMARY]  
	Declare @sqlEmpLevel nvarchar(4000)
	--insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	--insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	--insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	'insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@DesignationID as nvarchar(100)) + ''')'
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	'insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeType as nvarchar(8)) + ''')'	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	'insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102),''' + cast(@EmployeeId as nvarchar(100)) + ''',''' + cast(@employeeCategory as nvarchar(8)) + ''')'
	Execute(@sqlEmpCategory)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF(@GENDER<>'BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' '  
	END	
	if(@isReportingto > 0)
    BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + ' and (EMP.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	IF NOT (@EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id '
		END
	EXECUTE(@SQLEMPLEVEL)	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ' 
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.SwipeCardNo '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.SwipeCardNo '
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + ' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0'
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	'insert into #TempProcessedData 
	select	#EMPLEVEL.EMPLOYEEID,
			TA_Tbl_ProcessedData.Date,
			TA_Tbl_ProcessedData.Employee_Code_Id,
			TA_Tbl_ProcessedData.intime,
			TA_Tbl_ProcessedData.outtime,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.HrsWork,
			TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,
			TA_Tbl_ProcessedData.Attendance,
			TA_Tbl_ProcessedData.anAttendanceCode,
			TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.Process_Rec_ID,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime)
			,LateInMins,
			EarlyOut,
			LateIn,
			TA_Tbl_ProcessedData.NormOT,
			TA_Tbl_ProcessedData.OffOT,
			TA_Tbl_ProcessedData.HolOT,
			OtMins,
			case when charindex(''.'',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex(''.'',convert(varchar(20),EarlyOutmins))))
			else EarlyOutmins end,
			OvertimeStatus,
			0,
			InNotation,
			OutNotation,
			BreakHrs,
			LunchHrs,
			BreakHrsInMins,
			LunchHrsInMins,
			((case when len(customfield1)>0 then convert(varchar(100),customfield1)+''#'' else '''' End) +
			(case when len(customfield2)>0 then convert(varchar(100),customfield2) +''#'' else '''' End) +
			(case when len(customfield3)>0 then convert(varchar(100),customfield3) +''#'' else '''' End) +
			(case when len(customfield4)>0 then convert(varchar(100),customfield4)+''#'' else '''' End) +
			(case when len(customfield5)>0 then convert(varchar(100),customfield5) +''#'' else '''' End)) 
			as Skills
			FROM TA_TBL_PROCESSEDDATA 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID
	inner join ta_tbl_Employee EM on EM.SwipeCardNo = TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID
	left outer join TA_tbl_ShiftAdd_Location LOC on LOC.employeeId = EM.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102)
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102))
	' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND TA_Tbl_ProcessedData.shift_id= '+  cast (@Shift as nvarchar(50))
		end	
	if(@workLocation<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' AND LOC.LocationId= '+  cast (@workLocation as nvarchar(50))
		end	
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode='CL' 	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)='PM' and SUBSTRING(S.Shift_Endtime,7,8)='AM' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)='AM' and SUBSTRING(S.Shift_Endtime,7,8)='PM' and PD.OutTime>'00:00 AM' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id
	declare @pos as int  
	set @pos = charindex(':',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),
	Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),
	Date datetime,InTime varchar(30),OutTime varchar(30),
	HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),
	TotalMinsWorked varchar(30),Shift_ShortName varchar(20),
	shift_TotalWorkingHours varchar(20),Gender nvarchar(10),
	EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),
	NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),
	OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,
	TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),
	NightOrMorn int,LunchInTime nvarchar(20),LunchOutTime nvarchar(20)
	,InNotation char(1),OutNotation char(1)
	,BreakHours varchar(20),LunchHours varchar(20),
	BreakHoursMins int,LunchHoursMins int,
	Shift_StartTime	nvarchar(10),
	Shift_EndTime	nvarchar(10)
	,Skills nvarchar(max)
	)
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''    	
	set @sqlQuery = 'select  pd.fnAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''FN'',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end as FirstSession
	,pd.anAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''AN'',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''Weekly Off'' and anAttendanceCode=''Weekly Off'' then	''-'' 
	when pd.fnAttendanceCode=''Holiday''or anAttendanceCode=''Holiday'' then ''-''
	else pd.SupposedWorkHours end ''SupposedWorkHours'',(pd.Attendance +  CASE pd.Status WHEN ''BL'' THEN '' - '' ELSE '''' END + isnull(pd.Status,'''')) as Status,((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked'  
	set @sqlQuery = @sqlQuery + ' ,(CASE pd.Shift_Id WHEN ''-1'' THEN ''Weekly Off'' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN ''-'' 
						 when pd.Shift_Id=-1 then ''-''
						 ELSE shf.shift_TotalWorkingHours END
				),''00:00''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''00:00'' end Overtime,
	CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''NormOTMins'',
	CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''WeekOffOTMins'',
	CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''HolidayOTMins'',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('':'',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('':'',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('':'',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('':'',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''-'' else OvertimeStatus end,NightOrMorn,''00:00'',''00:00'',InNotation,OutNotation,PD.BREAKHOURS,LunchHours,BreakHoursMins,LunchHoursMins,
	Shift_StartTime,Shift_EndTime, pd.Skills
	 '
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + ' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id'  
		end   
		set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102)))'    
	if(@Gender<>'Both')  
		begin  
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end		
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')  
		begin  
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''  
		end	
	if (@MinWorkHours<>'')  
		begin  
			set @sqlQuery = @sqlQuery + 'and #EmpProcessedData.TotalWorkMins >= ' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'     	
	insert into #TempMonthlyAttendance exec(@sqlQuery)	
	Create table #TempOutPunches
	(
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_Date] [datetime] NULL,
		PunchType varchar(20)
	)
	insert into #TempOutPunches
	select Clk_EmpId,min(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_OutPunchType in('Lunch Out')	
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,max(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_InPunchType in('Lunch In')	
	group by Clk_EmpId,Clk_Date,Clk_InPunchType	
	update #TempMonthlyAttendance set LunchInTime=case when PunchType='Lunch In' then TP.Clk_OutTime else TM.LunchInTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType='Lunch In'
	update #TempMonthlyAttendance set LunchOutTime=case when PunchType='Lunch Out' then TP.Clk_OutTime else TM.LunchOutTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType='Lunch Out'	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession='Present' OR FirstSession='*Present' OR FirstSession='Holiday' OR FirstSession='*Holiday' OR FirstSession='Weekly Off' OR FirstSession='*Weekly Off') and InNotation='M' then  FirstSession+' #'	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession='Present' OR SecondSession = '*Present' OR SecondSession ='Holiday' OR SecondSession ='*Holiday' OR SecondSession ='Weekly Off' OR SecondSession ='*Weekly Off')  and OutNotation='M' then  SecondSession+' #'
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	select 
	case	when (@TimeFormat)='hh:mm' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchInTime,0)), 114)
			else	substring(LunchInTime,13,5)+' ' + substring(LunchInTime,18,2) 					
	end LunchIn,
	case	when (@TimeFormat)='hh:mm' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchOutTime,0)), 114)
			else	substring(LunchOutTime,13,5)+' ' + substring(LunchOutTime,18,2) 					
	end LunchOut
	,FirstSession,SecondSession ,Employee_Id,empName,BranchName,Designation,
	case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, Date,@dateFormat),' ','-') 
	else CONVERT(VARCHAR, Date, @dateFormat) end AS
	Date,
	InTime,OutTime,HrsWork,SupposedWorkHours,
	Status,convert(int,isnull(TotalMinsWorked,'0'))TotalMinsWorked,CASE WHEN Shift_ShortName='Weekly Off' THEN 'Off' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
	shift_TotalWorkingHours,Gender,EarlyOut,LateIn,overtime,NormOTMin,OffOTMin,HolOTMin,NormOT,OffOT,HolOT,
	convert(int,lateinMin)as lateinMin,
	convert(int,EarlyOutMin)as EarlyOutMin,TotDefWorkHrs,TotSupWorkHrs,overtimeStatus,BreakHoursMins,
	BreakHours=isnull(BreakHours,'-'),LunchHoursMins,LunchHours=isnull(LunchHours,'-'),
	Shift_StartTime,Shift_EndTime, Skills,
	(
	case
	when (b.Onduty_EmployeeID) <> 0 and Status='Present' then 'On Duty' 
 	when (Status='Present') then 'Present' 
	when  (FirstSession not in('Present #','Absent','Weekly Off','Holiday','RH','Present')
	     or SecondSession not in('Present  #','Absent','Weekly Off','Holiday','RH','Present')) then 'Leave'
	when (Status='Absent') then 'Absent'
	End
	) 
	as AttendanceType
	from #TempMonthlyAttendance 
	left outer join TA_Tbl_OndutyEntry b on b.Onduty_EmployeeID = #TempMonthlyAttendance.Employee_Id
	order by AttendanceType
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceLabour]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
[Proc_TA_RptMonthlyAttendanceLabour] @MINWORKHOURS=N'',@FROMDAT='2019-01-01 00:00:00',@TODAT='2019-01-31 00:00:00',
@EMPLOYEENAME=N'Manikandan ,Sathishkumar ,',@LEVELID=N'19',@EMPLOYEEID=N'787,758,',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N'SUPERADMIN',
@GRADELEVEL=N'0',@EMPSWIPECARD=N'',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N'BOTH',@SHIFT=0,@DATALOADING=0,@EMPAUTOID=0,@EXPORT=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceLabour]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId int,
	@Export int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT))  
	
	
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,HrsWork nvarchar(10),SupposedWorkHours nvarchar(10),Status nvarchar(50),Attendance nvarchar(20),anAttendanceCode nvarchar(15),fnAttendanceCode nvarchar(15),PrevShift_ID int,Process_Rec_ID bigint,Exactshift_StartTime nvarchar(25),Shift_Secondhalf_startTime datetime,LateInmin	nvarchar(10),EarlyOut nvarchar(10),LateIn nvarchar(10),NormOT nvarchar(10),OffOT nvarchar(10),HolOT nvarchar(10),OtMins float,EarlyOutMin nvarchar(10),overtimeStatus varchar(20),NightOrMorn int)
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END		
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 '
	IF not(@local_GENDER='BOTH')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' AND EMP.GENDER = ''' + CAST(@local_GENDER AS NVARCHAR(8)) + ''' '  
	END		
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@local_TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	IF NOT (@local_EMPLOYEEID = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	IF NOT (@local_EMPLOYEENAME = '')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + ' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID '
		END
	EXECUTE(@SQLEMPLEVEL)	
	
	Declare @sqlEmpDesi nvarchar(4000)

	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY

	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  	
	Declare @sqlTempProcessedData varchar(8000)

	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	'insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id where SwipeCardNo is not null' 
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sqlTempProcessedData = @sqlTempProcessedData + ' And SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End	
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	'insert into #TempProcessedData 
	select	#TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,
			TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork,TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.anAttendanceCode,TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Process_Rec_ID,S.Shift_startTime,cast(S.Shift_Secondhalf_startTime as datetime)
	,LateInMins,EarlyOut,LateIn,TA_Tbl_ProcessedData.NormOT,TA_Tbl_ProcessedData.OffOT,TA_Tbl_ProcessedData.HolOT,OtMins,EarlyOutMins,OvertimeStatus,0
	from TA_Tbl_ProcessedData inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id  
	left outer join ta_tbl_shift S on S.Shift_Id=TA_Tbl_ProcessedData.Shift_Id	
	where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,'''+cast( @local_FROMDAT as nvarchar(50))+''', 102))    
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''+cast(@local_TODAT as nvarchar(50))+''', 102))' 
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' And TA_Tbl_ProcessedData.Employee_Code_Id = ''' + @EmpSwipeCard + ''' '  
		End
	Execute(@sqlTempProcessedData1)
	
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode='CL' 	
	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@local_FROMDAT as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@local_TODAT as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@local_FROMDAT as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@local_TODAT as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)='PM' and SUBSTRING(S.Shift_Endtime,7,8)='AM' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)='AM' and SUBSTRING(S.Shift_Endtime,7,8)='PM' and PD.OutTime>'00:00 AM' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id

	declare @pos as int  
	set @pos = charindex(':',@local_MINWORKHOURS)  
	declare @TotalMin as int  
	set @TotalMin = substring(@local_MINWORKHOURS,0,@pos)*60 + substring(@local_MINWORKHOURS,@pos+1,2)  

	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),Date varchar(30),InTime varchar(30),OutTime varchar(30),HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),TotalMinsWorked varchar(30),Shift_ShortName varchar(20),shift_TotalWorkingHours varchar(20),Gender nvarchar(10),EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),NightOrMorn int)
	
	if (@local_MINWORKHOURS<>'')  
		begin  
			declare @sqlQueryTemp as varchar(max)    
			set @sqlQueryTemp=''   
			set @sqlQueryTemp =  'select pd.Employee_Code_Id as SwipeCardNo,pd.date as Date,((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalWorkMins from Ta_Tbl_Employee e '
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpDesignation EDesig on e.employee_id = EDesig.EmployeeId '  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
			set @sqlQueryTemp = @sqlQueryTemp + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
			set @sqlQueryTemp = @sqlQueryTemp + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '  
			Set @sqlQueryTemp = @sqlQueryTemp + ' Left JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id '
			set @sqlQueryTemp = @sqlQueryTemp + ' where  (	(e.Employee_Status = 1) or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102)
			)) AND (e.Isdeleted = 0) AND (e.report_exclude = 0)'
			insert into #EmpProcessedData exec(@sqlQueryTemp)  
		end
	
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''    	
	set @sqlQuery = 'select  
	CASE	WHEN PD.FNATTENDANCECODE=''PRESENT'' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''FN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END 
			ELSE PD.FNATTENDANCECODE
	END as FirstSession,
	CASE	WHEN PD.ANATTENDANCECODE =''PRESENT'' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''AN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END  
			ELSE PD.ANATTENDANCECODE
	END as SecondSession, 
	e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''Weekly Off'' and anAttendanceCode=''Weekly Off'' then	''-'' 
	when pd.fnAttendanceCode=''Holiday''or anAttendanceCode=''Holiday'' then ''-''
	else pd.SupposedWorkHours end ''SupposedWorkHours'',(pd.Attendance +  CASE pd.Status WHEN ''BL'' THEN '' - '' ELSE '''' END + isnull(pd.Status,'''')) as Status,((substring(isnull(pd.HrsWork,''00:00''),0,charindex('':'',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''00:00''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked'  
	set @sqlQuery = @sqlQuery + ' ,(CASE pd.Shift_Id WHEN ''-1'' THEN ''Weekly Off'' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN ''-'' 
						 when pd.Shift_Id=-1 then ''-''
						 ELSE shf.shift_TotalWorkingHours END
				),''00:00''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''00:00'' end Overtime,
	CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''NormOTMins'',
	CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''WeekOffOTMins'',
	CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''HolidayOTMins'',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('':'',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('':'',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''Holiday'') OR (pd.anAttendanceCode = ''Holiday'')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('':'',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('':'',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''-'' else OvertimeStatus end,NightOrMorn '  
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e '  
	set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'     
	set @sqlQuery = @sqlQuery + ' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	if (@local_MINWORKHOURS<>'')  
		begin  
			set @sqlQuery = @sqlQuery + ' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id'  
		end   
		set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, ''' + cast(@local_FROMDAT as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@local_TODAT as nvarchar(11)) + ''', 102)))'    
	if(@local_USERGROUPNAME<>'SuperAdmin')  
		begin  
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GRADELEVEL + ''  
		end
	if(@Shift<>0)  
		begin  
			Set @sqlQuery = @sqlQuery + ' AND pd.shift_id= '+  cast (@Shift as nvarchar(50))  + ''  
		end
	if (@local_MINWORKHOURS<>'')  
		begin  
			set @sqlQuery = @sqlQuery + 'and #EmpProcessedData.TotalWorkMins >= ' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,cast(pd.date as datetime)'     	
	
	insert into #TempMonthlyAttendance exec(@sqlQuery)
	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession='Present' OR FirstSession='*Present' OR FirstSession='Holiday' OR FirstSession='*Holiday' OR FirstSession='Weekly Off' OR FirstSession='*Weekly Off') and ME.ManualTimeEntry_InTime IS NOT NULL then  FirstSession+' #'	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id and isnull(ME.ManualTimeEntry_Id,0)<>0 
	and (ME.ManualTimeEntry_InDate=#TempMonthlyAttendance.Date) and isnull(ME.IsOnDuty,0)=0 
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status='Approved'	
	and (cast(#TempMonthlyAttendance.Date+CONVERT(datetime,#TempMonthlyAttendance.InTime) as datetime)=cast(Me.ManualTimeEntry_InDate+CONVERT(datetime,Me.ManualTimeEntry_InTime) as datetime))
		
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession='Present' OR SecondSession = '*Present' OR SecondSession ='Holiday' OR SecondSession ='*Holiday' OR SecondSession ='Weekly Off' OR SecondSession ='*Weekly Off')  and ME.ManualTimeEntry_OutTime IS NOT NULL  then  SecondSession+' #'
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id and isnull(ME.ManualTimeEntry_Id,0)<>0 
	and ME.ManualTimeEntry_OutDate=#TempMonthlyAttendance.Date 
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status='Approved'	
	and isnull(ME.IsOnDuty,0)=0 and (cast( #TempMonthlyAttendance.Date+convert(datetime,#TempMonthlyAttendance.OutTime) as datetime)=cast(Me.ManualTimeEntry_OutDate+CONVERT(datetime,Me.ManualTimeEntry_OutTime) as datetime))

	update #TempMonthlyAttendance set SecondSession=case when (SecondSession='Present' OR SecondSession = '*Present' OR SecondSession ='Holiday' OR SecondSession ='*Holiday' OR SecondSession ='Weekly Off' OR SecondSession ='*Weekly Off')  and ME.ManualTimeEntry_OutTime IS NOT NULL  then  SecondSession+' #'
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance 
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id 	
	and ME.ManualTimeEntry_OutDate=dateadd(d,1,#TempMonthlyAttendance.Date)	
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status='Approved'	
	and (cast( dateadd(d,1,#TempMonthlyAttendance.Date)+convert(datetime,#TempMonthlyAttendance.OutTime) as datetime)=cast(Me.ManualTimeEntry_OutDate+CONVERT(datetime,Me.ManualTimeEntry_OutTime) as datetime))
	and NightOrMorn=1	
		 
	select 
		Employee_Id,
		empName,
		Date,
		CASE WHEN Shift_ShortName='Weekly Off' THEN 'Off' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
		InTime,
		OutTime,
		[Shift Hours]=shift_TotalWorkingHours,
		'' as BreakHours,
		HrsWork,
		LateIn,
		EarlyOut,
		NormOT,
		OffOT,
		HolOT,		
		FirstSession,		
		SecondSession ,
		SupposedWorkHours,
		---
		BranchName,
		Designation,
		Status,
		convert(int,isnull(TotalMinsWorked,'0'))TotalMinsWorked,
		Gender,
		overtime,
		NormOTMin,
		OffOTMin,
		HolOTMin,
		lateinMin,
		EarlyOutMin,
		TotDefWorkHrs,
		TotSupWorkHrs,
		overtimeStatus ,
		shift_TotalWorkingHours
	from #TempMonthlyAttendance order by Employee_Id,Date
	
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
exec [Proc_TA_RptMonthlyDeviationHrs] 
@FromDate=N'06/jun/2016',@ToDate=N'02/jul/2016',@EmployeeName=N'',@LevelID=N'0',@EmployeeID=N'787,956,916,926,801',@EmployeeCategory=0,
@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@EmpAutoId=0,@Deviation=0,@ParentId=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT,
    @ParentId INT
AS  
BEGIN  
	SET NOCOUNT ON
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
			--To split up the comma separated values			
	if(@EmployeeId is not null and @EmployeeId <> '')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from dbo.SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != 'Sunday' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = 'Week' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + ', TargetWorkHours_' + @WeekName + ' VARCHAR(10), ActualWorkHours_' + @WeekName + ' VARCHAR(10), ArmisWorkHours_' + @WeekName + ' VARCHAR(10), [Leave_Permision_' + @WeekName + '] VARCHAR(10), DeviationHours_' + @WeekName + ' VARCHAR(30)', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FinalAttendanceSummary')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC('CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)' + @TableColumns + ')')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = 'Week' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Level insert in Temporary table
		Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
	If Not (@EmployeeId = '')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id '
			End
	If Not (@EmployeeName = '')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id '
			End		
	DECLARE @sqlEmpLevel nVARCHAR(4000)	
	SET @sqlEmpLevel=
	'INSERT INTO #EmpLevel 	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from	(
	SELECT	max(el.EffectiveDate) as EffectiveDate,	el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId '
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nVARCHAR(50))+''', 102) and EL.LevelId is not null'			
	EXECUTE(@sqlEmpLevel)	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,''	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
			--SET @SQLQuery = 'SELECT * FROM 
			--[ProjectManagementV3].[dbo].[Fn_GetProgressReport](''' + CAST(@FromDate AS VARCHAR(20)) + ''',''' + CAST(@ToDate AS VARCHAR(20)) + '''' + (CASE WHEN @EmployeeId = '' OR @EmployeeId IS NULL THEN ', NULL)' ELSE ', ' + @EmployeeId + ')' END)
			--INSERT INTO @ArmisTable
			--EXEC(@SQLQuery)			
			--select * from @ArmisTable
  		SET @SQLQuery = 'SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END,'
  		SET @SQLQuery = @SQLQuery + ' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''), REPLACE(LD.Name, ''&amp;'', ''&''),'
  		SET @SQLQuery = @SQLQuery + ' REPLACE(T.TitleName, ''&amp;'', ''&''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''-''), ISNULL(PD.OutTime, ''-''),'
  		SET @SQLQuery = @SQLQuery + ' ISNULL(PD.HrsWork, ''-''), ((SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 4, 2))),'
		SET @SQLQuery = @SQLQuery + ' (S.Shift_ShortName + '' ('' + S.Shift_StartTime + '' - ''  + S.Shift_EndTime + '')''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''-''),'
		SET @SQLQuery = @SQLQuery + ' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' (CASE WHEN (ISNULL(PD.BreakIn, '''') = '''' OR ISNULL(PD.BreakOut, '''') = '''') AND PD.BreakHours <> ''00:00'' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')),ISNULL(SS.MaxWorkPlaceInHours, ''00:10''), NULL FROM Ta_Tbl_Employee E'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id'    
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId'   
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId '
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId'		
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId '		
		If Not (@EmployeeId = '')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End	
  		SET @SQLQuery = @SQLQuery + ' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, ''' + CAST(@FromDate AS NVARCHAR(11)) + ''', 102) AND PD.Date <= CONVERT(DATETIME, ''' + CAST(@ToDate AS NVARCHAR(11)) + ''', 102)))'
		IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel + ''
		END	 
		if(@isReportingto > 0)
            BEGIN
               set @SQLQuery = @SQLQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		SET @SQLQuery = @SQLQuery + ' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)'   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = 'Saturday' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != 'Sunday'
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
			--select 
			--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
			CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
					 (ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
															(
																substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX('.',convert(varchar(10),ArmisWorkHours)))*60
																+
																substring(convert(varchar(10),ArmisWorkHours),CHARINDEX('.',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
																+ 
																[Leave_Permision] *60
																+ 
																(DefinedWorkHours - TargetWorkHours)*60
															)
														)
					ELSE 0 
			END 
			FROM #TempAttendanceSummary TAS
			INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
			INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  			INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
  			--where E.Employee_Code_Id='787'
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), '.', ':') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + ':' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, '.', ':') AS ArmisWorkHours,
			REPLACE([Leave_Permision], '.', ':') AS [Leave_Permision],
			'T:'+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN '0' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			'A:'+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN '0' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END 
			AS DeviationHours
		 INTO #TempFinalResult 
		 FROM #TempAttendanceSummary	
		 WHERE 		 
		 (@Deviation = 1 AND DeviationHours != 0) 
		 OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = 'UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_' + @WeekName + ' = TR.TargetWorkHours,
							ActualWorkHours_' + @WeekName + ' = TR.ActualWorkHours,
							ArmisWorkHours_' + @WeekName + ' = TR.ArmisWorkHours,
							[Leave_Permision_' + @WeekName + '] = TR.[Leave_Permision],
							DeviationHours_' + @WeekName + ' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName'
		EXEC(@SQLQuery)
		SET @SQLQuery = 'INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_' + @WeekName + ', ActualWorkHours_' + @WeekName + ', ArmisWorkHours_' + @WeekName + ', [Leave_Permision_' + @WeekName + '], DeviationHours_' + @WeekName + ')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL'
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE #LevelRights
	DROP TABLE FinalAttendanceSummary
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs_New
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
Updated By		:	A.K.T.MOORTHI
Updated on		:	20-Jun-2013
Description		:	Subtract The Exception Hours From Work Hours
EXEC [Proc_TA_RptMonthlyDeviationHrs_New] '28/Oct/2013','02/Nov/2013','','107,108,109,110,111,112,113,114,115,123','',0,0,'SuperAdmin',0,'804',0,0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT
AS  
BEGIN  
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id BIGINT, [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != 'Sunday' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = 'Week' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + ', TargetWorkHours_' + @WeekName + ' VARCHAR(10), ActualWorkHours_' + @WeekName + ' VARCHAR(10), ArmisWorkHours_' + @WeekName + ' VARCHAR(10), [Leave_Permision_' + @WeekName + '] VARCHAR(10), DeviationHours_' + @WeekName + ' VARCHAR(10)', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FinalAttendanceSummary')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC('CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)' + @TableColumns + ')')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = 'Week' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs BIT)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
		(
			[PayId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Level insert in Temporary table
		INSERT INTO #EmpLevel 
			SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
				SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
					INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
			INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
			AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
		INSERT INTO #EmpDesignation
			SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
				SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
					INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
			INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
			AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
		INSERT INTO #EmpType 
			SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
				SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
					INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
					WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
			INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
			AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
		INSERT INTO #EmpCategory
			SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
				SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
					INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102)
				GROUP BY EmployeeId) EmpCategory
			INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
				AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
		INSERT INTO #EmpPay
			SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
				SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
					INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
			INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
				AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
			SET @SQLQuery = 'SELECT * FROM [ProjectManagementV3].[dbo].[Fn_GetProgressReport](''' + CAST(@FromDate AS VARCHAR(20)) + ''',''' + CAST(@ToDate AS VARCHAR(20)) + '''' + (CASE WHEN @EmployeeId = '' OR @EmployeeId IS NULL THEN ', NULL)' ELSE ', ' + @EmployeeId + ')' END)
			INSERT INTO @ArmisTable
				EXEC(@SQLQuery)
  		SET @SQLQuery = 'SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END,'
  		SET @SQLQuery = @SQLQuery + ' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''), REPLACE(LD.Name, ''&amp;'', ''&''),'
  		SET @SQLQuery = @SQLQuery + ' REPLACE(T.TitleName, ''&amp;'', ''&''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''-''), ISNULL(PD.OutTime, ''-''),'
  		SET @SQLQuery = @SQLQuery + ' ISNULL(PD.HrsWork, ''-''), ((SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 4, 2))),'
		SET @SQLQuery = @SQLQuery + ' (S.Shift_ShortName + '' ('' + S.Shift_StartTime + '' - ''  + S.Shift_EndTime + '')''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''-''),'
		SET @SQLQuery = @SQLQuery + ' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' (CASE WHEN (ISNULL(PD.BreakIn, '''') = '''' OR ISNULL(PD.BreakOut, '''') = '''') AND PD.BreakHours <> ''00:00'' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''00:00'', ISNULL(''00:05'', ''00:05'')),ISNULL(''00:05'', ''00:05''), NULL FROM Ta_Tbl_Employee E'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id'    
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId'   
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId '
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, ''' + CAST(@FromDate AS NVARCHAR(11)) + ''', 102) AND PD.Date <= CONVERT(DATETIME, ''' + CAST(@ToDate AS NVARCHAR(11)) + ''', 102)))'
		IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel + ''
		END
		IF NOT(@EmployeeName = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_FirstName + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName +'%' AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmployeeId='')  
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmpSwipeCard = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND E.SwipeCardNo = ''' + @EmpSwipeCard + ''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		IF(@EmpAutoId = 0)
		BEGIN
			IF NOT(@LevelID = '' OR @LevelID = '0')  
			BEGIN
				SET @SQLQuery = @SQLQuery + ' AND (TEL.levelId IN (' + @LevelID + '))'  
			END
		END
		ELSE
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds))'
		END
		SET @SQLQuery = @SQLQuery + ' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)'   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = 'Saturday' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != 'Sunday'
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = CASE WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 1 ELSE 0 END FROM #TempAttendanceSummary TAS
				INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
				INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  				INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), '.', ':') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + ':' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, '.', ':') AS ArmisWorkHours,
			REPLACE([Leave_Permision], '.', ':') AS [Leave_Permision],
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN '0' + CAST((DeviationHours/60) AS VARCHAR(25)) ELSE CAST((DeviationHours/60) AS VARCHAR(25)) END + ':' + CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((DeviationHours%60) AS VARCHAR(25)) ELSE CAST((DeviationHours%60) AS VARCHAR(25)) END AS DeviationHours
		 INTO #TempFinalResult FROM #TempAttendanceSummary	WHERE (@Deviation = 1 AND DeviationHours != 0) OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		SET @SQLQuery = 'UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_' + @WeekName + ' = TR.TargetWorkHours,
							ActualWorkHours_' + @WeekName + ' = TR.ActualWorkHours,
							ArmisWorkHours_' + @WeekName + ' = TR.ArmisWorkHours,
							[Leave_Permision_' + @WeekName + '] = TR.[Leave_Permision],
							DeviationHours_' + @WeekName + ' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName'
		EXEC(@SQLQuery)
		SET @SQLQuery = 'INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_' + @WeekName + ', ActualWorkHours_' + @WeekName + ', ArmisWorkHours_' + @WeekName + ', [Leave_Permision_' + @WeekName + '], DeviationHours_' + @WeekName + ')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL'
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory
		DROP TABLE #EmpPay		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE FinalAttendanceSummary
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
exec [Proc_TA_RptMonthlyDeviationHrsNew] 
@FromDate=N'25/Apr/2016',@ToDate=N'30/apr/2016',@EmployeeName=N'',@LevelID=N'107',@EmployeeID=N'659',@EmployeeCategory=0,
@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@EmpAutoId=0,@Deviation=1,@ParentId=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT,
    @ParentId INT
AS  
BEGIN  
	SET NOCOUNT ON
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != 'Sunday' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = 'Week' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + ', TargetWorkHours_' + @WeekName + ' VARCHAR(10), ActualWorkHours_' + @WeekName + ' VARCHAR(10), ArmisWorkHours_' + @WeekName + ' VARCHAR(10), [Leave_Permision_' + @WeekName + '] VARCHAR(10), DeviationHours_' + @WeekName + ' VARCHAR(30)', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FinalAttendanceSummary')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC('CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)' + @TableColumns + ')')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = 'Week' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
		(
			[PayId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]		
--Employee Level insert in Temporary table
		INSERT INTO #EmpLevel 
			SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
				SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
					INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
			INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
			AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
		INSERT INTO #EmpDesignation
			SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
				SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
					INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
			INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
			AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
		INSERT INTO #EmpType 
			SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
				SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
					INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
					WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
			INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
			AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
		INSERT INTO #EmpCategory
			SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
				SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
					INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102)
				GROUP BY EmployeeId) EmpCategory
			INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
				AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
		INSERT INTO #EmpPay
			SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
				SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
					INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
			INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
				AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
			SET @SQLQuery = 'SELECT * FROM 
			[ProjectManagementV3].[dbo].[Fn_GetProgressReport](''' + CAST(@FromDate AS VARCHAR(20)) + ''',''' + CAST(@ToDate AS VARCHAR(20)) + '''' + (CASE WHEN @EmployeeId = '' OR @EmployeeId IS NULL THEN ', NULL)' ELSE ', ' + @EmployeeId + ')' END)
			INSERT INTO @ArmisTable
			EXEC(@SQLQuery)			
			--select * from @ArmisTable
  		SET @SQLQuery = 'SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END,'
  		SET @SQLQuery = @SQLQuery + ' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''), REPLACE(LD.Name, ''&amp;'', ''&''),'
  		SET @SQLQuery = @SQLQuery + ' REPLACE(T.TitleName, ''&amp;'', ''&''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''-''), ISNULL(PD.OutTime, ''-''),'
  		SET @SQLQuery = @SQLQuery + ' ISNULL(PD.HrsWork, ''-''), ((SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 4, 2))),'
		SET @SQLQuery = @SQLQuery + ' (S.Shift_ShortName + '' ('' + S.Shift_StartTime + '' - ''  + S.Shift_EndTime + '')''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''-''),'
		SET @SQLQuery = @SQLQuery + ' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' (CASE WHEN (ISNULL(PD.BreakIn, '''') = '''' OR ISNULL(PD.BreakOut, '''') = '''') AND PD.BreakHours <> ''00:00'' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')),ISNULL(SS.MaxWorkPlaceInHours, ''00:10''), NULL FROM Ta_Tbl_Employee E'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id'    
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId'   
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId'
  		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId '
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId '		
  		SET @SQLQuery = @SQLQuery + ' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, ''' + CAST(@FromDate AS NVARCHAR(11)) + ''', 102) AND PD.Date <= CONVERT(DATETIME, ''' + CAST(@ToDate AS NVARCHAR(11)) + ''', 102)))'
		IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel + ''
		END
		IF NOT(@EmployeeName = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_FirstName + '' '' + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName +'%' AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmployeeId='')  
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_Code_Id = ''' + CAST(@EmployeeId AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmpSwipeCard = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND E.SwipeCardNo = ''' + @EmpSwipeCard + ''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		--IF(@EmpAutoId = 0)
		--BEGIN
		--	IF NOT(@LevelID = '' OR @LevelID = '0')  
		--	BEGIN
		--		SET @SQLQuery = @SQLQuery + ' AND (TEL.levelId IN (' + @LevelID + '))'  
		--	END
		--END
		--ELSE
		--BEGIN
		--	SET @SQLQuery = @SQLQuery + ' AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds))'
		--END
		SET @SQLQuery = @SQLQuery + ' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)'   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = 'Saturday' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != 'Sunday'
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			select * from #TempAttendanceDetails
			select * from #TempAttendanceSummary
			UPDATE #TempAttendanceSummary SET DeviationHours = case when actualworkHours=0 then 0 else (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60)) end
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = case when actualworkHours=0 then 0 else ISNULL(A.TotalTask, 0) end FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
			case when actualworkHours=0 then 0 else
			--select 
			--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
			CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
					 (ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
															(
																substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX('.',convert(varchar(10),ArmisWorkHours)))*60
																+
																substring(convert(varchar(10),ArmisWorkHours),CHARINDEX('.',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
																+ 
																[Leave_Permision] *60
																+ 
																(DefinedWorkHours - TargetWorkHours)*60
															)
														)
					ELSE 0 
			END
			End
			FROM #TempAttendanceSummary TAS
			INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
			INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
  		--where E.Employee_Code_Id='787'
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), '.', ':') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + ':' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, '.', ':') AS ArmisWorkHours,
			REPLACE([Leave_Permision], '.', ':') AS [Leave_Permision],
			'T:'+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN '0' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			'A:'+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN '0' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END 
			AS DeviationHours
		 INTO #TempFinalResult 
		 FROM #TempAttendanceSummary	
		 WHERE 		 
		 (@Deviation = 1 AND DeviationHours != 0) 
		 OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = 'UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_' + @WeekName + ' = TR.TargetWorkHours,
							ActualWorkHours_' + @WeekName + ' = TR.ActualWorkHours,
							ArmisWorkHours_' + @WeekName + ' = TR.ArmisWorkHours,
							[Leave_Permision_' + @WeekName + '] = TR.[Leave_Permision],
							DeviationHours_' + @WeekName + ' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName'
		EXEC(@SQLQuery)
		SET @SQLQuery = 'INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_' + @WeekName + ', ActualWorkHours_' + @WeekName + ', ArmisWorkHours_' + @WeekName + ', [Leave_Permision_' + @WeekName + '], DeviationHours_' + @WeekName + ')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL'
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory
		DROP TABLE #EmpPay		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE #LevelRights
	DROP TABLE FinalAttendanceSummary
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*

exec Proc_TA_RptMovementsEntry @EmployeeID=N'',@LevelID=N'0',@FromDate=N'01/Jul/2024',@ToDate=N'21/Oct/2024'
,@EmployeeName=N'',@shift=0,@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',
@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',@InTime=N'12:00:00 AM',@OutTime=N'11:59:59 PM',
@EmpAutoId=0,@ExportType=0,@punchTypeValue=N'All'


*/


CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry]      
(
	@EmployeeID VarChar(50), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@punchTypeValue varchar(20),
	@EmpAutoId bigint,
	@ExportType int 
)      
AS      
BEGIN
	SET NOCOUNT ON;

--	DECLARE @InputDate NVARCHAR(50) = @FromDate
--	DECLARE @InputDates NVARCHAR(50) = @ToDate	
--	DECLARE @DateInDateTime DATETIME
--	DECLARE @DateInDateTimes DATETIME

---- Convert the input string to datetime
--	SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
--	SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
---- Convert the datetime to the desired format
--	Set @FromDate= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
--	Set @ToDate= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)
--	print @FromDate
--	Print @ToDate

	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=CONVERT(Datetime, @FromDate,111)
	set @local_ToDate=CONVERT(Datetime,@ToDate,111)
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_punchTypeValue=@punchTypeValue
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	
	
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	create table #EmpLevel(id int identity(1,1),EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,
		[Clk_CompId] varchar(10) ,
		[Clk_EmpId] nvarchar(20) ,
		[Clk_InDeviceId] nvarchar(20) ,
		[Clk_InDate] datetime,
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25) ,
		[Clk_OutDeviceId] nvarchar(20) ,
		[Clk_OutDate] datetime,
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,
		[Clk_Process] nvarchar(1) ,
		[Clk_Remarks] nvarchar(255) ,
		[Clk_User] nvarchar(20) ,
		[Clk_Date] datetime,
		[Clk_Status] char(1) ,
		[IsVoid] bit,
		PunchType_Remarks nvarchar(max)
	)
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End	
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=
		'insert into #TempClockDetails
		select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
		[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid],PunchType_Remarks
		from TA_Tbl_ClockDetails Inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ClockDetails.clk_empid
		where ta_tbl_clockdetails.IsVoid=0 and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,'''+cast(@local_FromDate as nvarchar(20))+''', 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(20))+''', 102)'
	if(@local_punchTypeValue='Break In')
		begin
			set @sqlTempProcessedData1=@sqlTempProcessedData1+ ' and clk_InpunchType=''Break In'''
		end
	if(@local_punchTypeValue='Shift In')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+' and clk_InpunchType=''Shift In'''
		end
	if(@local_punchTypeValue='In')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''In'''
		end
	if(@local_punchTypeValue='Lunch In')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''Lunch In'''
		end
	if(@local_punchTypeValue='Out Duty')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''out Duty'''
		end
	if(@local_punchTypeValue='Official Out')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''Official Out'''
		end
	if(@local_punchTypeValue='Break Out')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Break Out'''
		end	
	if(@local_punchTypeValue='Shift Out')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Shift Out'''
		end	
	if(@local_punchTypeValue='Out')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Out'''
		end	
	if(@local_punchTypeValue='Lunch Out')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Lunch Out'''
		end	
	if(@local_punchTypeValue='in Duty')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''in Duty'''
		end	
	if(@local_punchTypeValue='official In')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Official In'''
		end
	Execute(@sqlTempProcessedData1)	
	if(@local_punchTypeValue in('Break In','Shift In','In','Lunch In','Official Out','Out Duty'))
		begin
			update #TempClockDetails set Clk_OutDate=null,Clk_OutDeviceId=null,Clk_OutTime=null,Clk_OutPunchType=null
		end
	else if(@local_punchTypeValue in('Break Out','Shift Out','Out','Lunch Out','Official In','In Duty'))
		begin
			update #TempClockDetails set Clk_InDate=null,Clk_InDeviceId=null,Clk_InTime=null,Clk_InPunchType=null
		end	



		/**************Organization Level ////Hariharan.J 2024-09-12 ***********/

		declare @Count int=0, @loop int=1,@SQLStr nvarchar(MAX)=''
	create table #Emptest (
		EmployeeId nvarchar(20),
		LevelId int,
		Level1Name nvarchar(200),
		Level1Details nvarchar(200),
		Level2Name nvarchar(200),
		Level2Details nvarchar(200),
		Level3Name nvarchar(200),
		Level3Details nvarchar(200),
		Level4Name nvarchar(200),
		Level4Details nvarchar(200),
		Level5Name nvarchar(200),
		Level5Details nvarchar(200)
	)
	select @Count=count(*) from #EMPLEVEL
	while(@Count>=@loop)
		begin
			Set @SQLStr=''
			declare @EmpID nvarchar(20),@LoopLevelID bigint
			Select @EmpID=EMPLOYEE_CODE_ID,@LoopLevelID=LEVELID from #EMPLEVEL where id=@loop
			select @SQLStr=dbo.Func_TA_LoadSpace(@EmpID,@LoopLevelID,'#Emptest')
			execute(@SQLStr)
			Set @loop=@loop+1
		end

		--Select * from #Emptest

	/*******************************************************************/




	--select * from #TempClockDetails 
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,''
	from TA_Tbl_ProcessedData 
	inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	Declare @SelectSQL As Varchar(max)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = ' '        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS ''Employee ID'', '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '   
		Set @SelectSQL = @SelectSQL + ''' '' + ED.Employee_MiddleName + '   
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', 
		Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,Level4Name,Level4Details,Level5Name,Level5Details,'      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',ED.Gender,case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ''Date'','      
		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as ''In Reader ID'',case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as ''In Punch Type'',
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS ''In Date'',
		Convert(varchar(10),CD.Clk_InTime,108) as ''In Time'' ,	
		'      
		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_OutDeviceId=''788'' or CD.Clk_OutDeviceId=''787''  then ''-'' else 
		OTer.Terminal_Name end as ''Out Reader ID'',
		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as ''Out Punch Type'',
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS ''Out Date'', 
		Convert(varchar(10),CD.Clk_OutTime,108) as ''Out Time'',ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,	
		case when CD.PunchType_Remarks!='''' then PunchType_Remarks else Clk_Remarks end Remarks,
		[Late Entry (mins)]='''',[Early Exit (Mins)]='''',Duration='''',[Worked Hours]='''',[Overtime]=''''
		FROM TA_Tbl_Employee ED '  
	end
	else
	begin
	    Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS CardNo, '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '   
		Set @SelectSQL = @SelectSQL + ''' '' + ED.Employee_MiddleName + '  
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', 
		Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,Level4Name,Level4Details,Level5Name,Level5Details,'      
		--
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
		Set @SelectSQL = @SelectSQL + 'CD.Clk_InDeviceId as InReaderID,	
		case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as InTerminalName,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS InDate,
		Convert(varchar(10),CD.Clk_InTime,108) as InTime ,	
		case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as Clk_InPunchType,'      
		Set @SelectSQL = @SelectSQL + 'CD.Clk_OutDeviceId as OutReaderID,
		case when CD.Clk_OutDeviceId=''788'' then ''-'' else 
		OTer.Terminal_Name end as OutTerminalName,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS OutDate, 
		Convert(varchar(10),CD.Clk_OutTime,108) as OutTime,	
		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as Clk_OutPunchType,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ClockDate,ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,ED.Gender 
		,case when CD.PunchType_Remarks!='''' then PunchType_Remarks else Clk_Remarks end Remarks
		FROM TA_Tbl_Employee ED '  
	end
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @SelectSQL = @SelectSQL + ' Inner join #Emptest ET on ED.employee_code_id=ET.EmployeeId '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID '  
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID '       
	Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) '
	if(@local_Gender<>'Both')
		begin
			set @SelectSQL = @SelectSQL + ' and ED.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)='PM' and substring(@local_InTime,7,8)='AM')
		begin
			Set @SelectSQL = @SelectSQL + 'And Clk_Date>='''+@local_FromDate+''' and Clk_Date<=dateadd(d,1,'''+@local_ToDate+''')
							and clk_intime>='''+@local_InTime+''' or clk_outtime<='''+@local_OutTime+''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + 'And (CD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_intime between '''+@local_InTime+''' and '''+@local_OutTime+''''
			Set @SelectSQL = @SelectSQL + 'or CD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_Outtime between '''+@local_InTime+''' and '''+@local_OutTime+''')'
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Set @SelectSQL = @SelectSQL + ' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc'      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempClockDetails 
	drop table #TempProcessedData
END



--ALTER PROCEDURE [dbo].[Proc_TA_RptMovementsEntry]      
--(
--	@EmployeeID VarChar(50), 
--	@LevelID VarChar(8000),  
--	@FromDate VarChar(50), 
--	@ToDate VarChar(50),
--	@EmployeeName varchar(50),
--	@shift int,
--	@employeeCategory int,
--	@employeeType int,
--	@UserGroupName varchar(250),
--	@GradeLevel varchar(20)	,
--	@EmpSwipeCard varchar(20),
--	@ParentId int,
--	@DesignationID int,
--	@Gender varchar(10),
--	@InTime VARCHAR(50),
--	@OutTime VARCHAR(20),
--	@punchTypeValue varchar(20),
--	@EmpAutoId bigint,
--	@ExportType int 
--)      
--AS      
--BEGIN
--	SET NOCOUNT ON;

----	DECLARE @InputDate NVARCHAR(50) = @FromDate
----	DECLARE @InputDates NVARCHAR(50) = @ToDate	
----	DECLARE @DateInDateTime DATETIME
----	DECLARE @DateInDateTimes DATETIME

------ Convert the input string to datetime
----	SET @DateInDateTime = CONVERT(DATETIME, REPLACE(@InputDate, '/', ' ') , 106)
----	SET @DateInDateTimes = CONVERT(DATETIME, REPLACE(@InputDates, '/', ' ') , 106)
------ Convert the datetime to the desired format
----	Set @FromDate= CONVERT(NVARCHAR(10), @DateInDateTime, 111)
----	Set @ToDate= CONVERT(NVARCHAR(10), @DateInDateTimes, 111)
----	print @FromDate
----	Print @ToDate

--	DECLARE @local_EmployeeID VarChar(50)
--	DECLARE @local_LevelID VarChar(8000)
--	DECLARE @local_FromDate VarChar(50) 
--	DECLARE @local_ToDate VarChar(50)
--	DECLARE @local_EmployeeName varchar(50)
--	DECLARE @local_shift int
--	DECLARE @local_employeeCategory int
--	DECLARE @local_employeeType int
--	DECLARE @local_UserGroupName varchar(250)
--	DECLARE @local_GradeLevel varchar(20)
--	DECLARE @local_EmpSwipeCard varchar(20)
--	DECLARE @local_ParentId int
--	DECLARE @local_DesignationID int
--	DECLARE @local_Gender varchar(10)
--	DECLARE @local_InTime VARCHAR(50)
--	DECLARE @local_OutTime VARCHAR(20)
--	DECLARE @local_punchTypeValue varchar(20)
--	DECLARE @local_EmpAutoId bigint
--	DECLARE @local_ExportType int
	
--	set @local_EmployeeID=@EmployeeID
--	set @local_LevelID=@LevelID
--	set @local_FromDate=CONVERT(Datetime, @FromDate,111)
--	set @local_ToDate=CONVERT(Datetime,@ToDate,111)
--	set @local_EmployeeName=@EmployeeName
--	set @local_shift=@shift
--	set @local_employeeCategory=@employeeCategory
--	set @local_employeeType=@employeeType
--	set @local_UserGroupName=@UserGroupName
--	set @local_GradeLevel=@GradeLevel
--	set @local_EmpSwipeCard=@EmpSwipeCard
--	set @local_ParentId=@ParentId
--	set @local_DesignationID=@DesignationID
--	set @local_Gender=@Gender
--	set @local_InTime=@InTime
--	set @local_OutTime=@OutTime
--	set @local_punchTypeValue=@punchTypeValue
--	set @local_EmpAutoId=@EmpAutoId
--	set @local_ExportType=@ExportType	
	
	
--	DECLARE @dateFormat as int
--	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
--	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--	create table #LevelRights(LevelId int)
--	create table #EmployeeIds(EmpAutoId int)
--	declare @isReportingto as int
--	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
--    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
--    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
--	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
--	CREATE TABLE #TempClockDetails
--	(
--		[Clk_Id] int,
--		[Clk_CompId] varchar(10) ,
--		[Clk_EmpId] nvarchar(20) ,
--		[Clk_InDeviceId] nvarchar(20) ,
--		[Clk_InDate] datetime,
--		[Clk_InTime] datetime,
--		[Clk_InPunchType] nvarchar(25) ,
--		[Clk_OutDeviceId] nvarchar(20) ,
--		[Clk_OutDate] datetime,
--		[Clk_OutTime] datetime,
--		[Clk_OutPunchType] nvarchar(25) ,
--		[Clk_Process] nvarchar(1) ,
--		[Clk_Remarks] nvarchar(255) ,
--		[Clk_User] nvarchar(20) ,
--		[Clk_Date] datetime,
--		[Clk_Status] char(1) ,
--		[IsVoid] bit,
--		PunchType_Remarks nvarchar(max)
--	)
--	Declare @sqlEmpLevel nvarchar(4000)
--	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
--		begin
--			create table #EmployeeID(EmployeeID varchar(25))
--			insert into #EmployeeID
--			select * from SplitupEmployeeCode(@local_EmployeeID)
--		end
--	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
--		begin
--			create table #EmployeeName(EmployeeID varchar(25))
--			insert into #EmployeeName
--			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
--		end
--	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
--	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
--	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
--	set @sqlEmpLevel=
--	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
--	(
--		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
--		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
--		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
--		where SwipeCardNo is not null and emp.Isdeleted=0 '
--	if(@local_Gender<>'Both')
--		begin
--			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
--		end
--	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
--	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
--	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
--	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'
--	If Not (@local_EmployeeID = '')  
--		Begin  
--			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
--		End
--	If Not (@local_EmployeeName = '')  
--		Begin  
--			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
--		End	
--	Execute(@sqlEmpLevel)
--	Declare @sqlEmpDesi nvarchar(4000)
--	Declare @sqlTempProcessedData1 varchar(8000)
--	set @sqlTempProcessedData1=
--		'insert into #TempClockDetails
--		select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
--		[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid],PunchType_Remarks
--		from TA_Tbl_ClockDetails Inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ClockDetails.clk_empid
--		where ta_tbl_clockdetails.IsVoid=0 and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,'''+cast(@local_FromDate as nvarchar(20))+''', 102) 
--			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(20))+''', 102)'
--	if(@local_punchTypeValue='Break In')
--		begin
--			set @sqlTempProcessedData1=@sqlTempProcessedData1+ ' and clk_InpunchType=''Break In'''
--		end
--	if(@local_punchTypeValue='Shift In')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+' and clk_InpunchType=''Shift In'''
--		end
--	if(@local_punchTypeValue='In')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''In'''
--		end
--	if(@local_punchTypeValue='Lunch In')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''Lunch In'''
--		end
--	if(@local_punchTypeValue='Out Duty')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''out Duty'''
--		end
--	if(@local_punchTypeValue='Official Out')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_InpunchType=''Official Out'''
--		end
--	if(@local_punchTypeValue='Break Out')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Break Out'''
--		end	
--	if(@local_punchTypeValue='Shift Out')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Shift Out'''
--		end	
--	if(@local_punchTypeValue='Out')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Out'''
--		end	
--	if(@local_punchTypeValue='Lunch Out')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Lunch Out'''
--		end	
--	if(@local_punchTypeValue='in Duty')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''in Duty'''
--		end	
--	if(@local_punchTypeValue='official In')
--		begin
--			set @sqlTempProcessedData1= @sqlTempProcessedData1+ ' and clk_OutpunchType=''Official In'''
--		end
--	Execute(@sqlTempProcessedData1)	
--	if(@local_punchTypeValue in('Break In','Shift In','In','Lunch In','Official Out','Out Duty'))
--		begin
--			update #TempClockDetails set Clk_OutDate=null,Clk_OutDeviceId=null,Clk_OutTime=null,Clk_OutPunchType=null
--		end
--	else if(@local_punchTypeValue in('Break Out','Shift Out','Out','Lunch Out','Official In','In Duty'))
--		begin
--			update #TempClockDetails set Clk_InDate=null,Clk_InDeviceId=null,Clk_InTime=null,Clk_InPunchType=null
--		end	
--	--select * from #TempClockDetails 
--	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int)
--	insert into #TempProcessedData 
--	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,''
--	from TA_Tbl_ProcessedData 
--	inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
--	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
--	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
--	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
--	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
--	(
--		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
--		(
--			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
--			from #TempProcessedData where Shift_Id=-1 	
--		)
--		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
--	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
--	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
--	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
--	(
--		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
--		(
--			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
--			from #TempProcessedData where PrevShift_ID=-1 	
--		)
--		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
--	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
--	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
--	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
--	Declare @SelectSQL As Varchar(max)      
--	Set @EmployeeName = @local_EmployeeName      
--	Set @SelectSQL = ' '        
--	if(@local_ExportType=1)
--	begin
--		Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS ''Employee ID'', '      
--		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
--		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
--		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
--		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',ED.Gender,case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ''Date'','      
--		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as ''In Reader ID'',case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as ''In Punch Type'',
--		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS ''In Date'',
--		Convert(varchar(10),CD.Clk_InTime,108) as ''In Time'' ,	
--		'      
--		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_OutDeviceId=''788'' or CD.Clk_OutDeviceId=''787''  then ''-'' else 
--		OTer.Terminal_Name end as ''Out Reader ID'',
--		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as ''Out Punch Type'',
--		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS ''Out Date'', 
--		Convert(varchar(10),CD.Clk_OutTime,108) as ''Out Time'',ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,	
--		case when CD.PunchType_Remarks!='''' then PunchType_Remarks else Clk_Remarks end Remarks,
--		[Late Entry (mins)]='''',[Early Exit (Mins)]='''',Duration='''',[Worked Hours]='''',[Overtime]=''''
--		FROM TA_Tbl_Employee ED '  
--	end
--	else
--	begin
--	    Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS CardNo, '      
--		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
--		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
--		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
--		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
--		Set @SelectSQL = @SelectSQL + 'CD.Clk_InDeviceId as InReaderID,	
--		case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as InTerminalName,
--		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS InDate,
--		Convert(varchar(10),CD.Clk_InTime,108) as InTime ,	
--		case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as Clk_InPunchType,'      
--		Set @SelectSQL = @SelectSQL + 'CD.Clk_OutDeviceId as OutReaderID,
--		case when CD.Clk_OutDeviceId=''788'' then ''-'' else 
--		OTer.Terminal_Name end as OutTerminalName,
--		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS OutDate, 
--		Convert(varchar(10),CD.Clk_OutTime,108) as OutTime,	
--		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as Clk_OutPunchType,
--		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
--		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
--		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ClockDate,ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,ED.Gender 
--		,case when CD.PunchType_Remarks!='''' then PunchType_Remarks else Clk_Remarks end Remarks,
--		[Late Entry (mins)]='''',[Early Exit (Mins)]='''',Duration='''',[Worked Hours]='''',[Overtime]=''''
--		FROM TA_Tbl_Employee ED '  
--	end
--	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
--	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
--	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
--	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
--	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
--	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
--	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
--	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
--	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
--	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID '  
--	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID '       
--	Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and 
--	((ED.employee_status=1)
--	or
--	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
--	 ) '
--	if(@local_Gender<>'Both')
--		begin
--			set @SelectSQL = @SelectSQL + ' and ED.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
--		end
--	if(@local_UserGroupName<>'SuperAdmin')
--		begin
--			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
--		end
--	if(substring(@local_InTime,7,8)='PM' and substring(@local_InTime,7,8)='AM')
--		begin
--			Set @SelectSQL = @SelectSQL + 'And Clk_Date>='''+@local_FromDate+''' and Clk_Date<=dateadd(d,1,'''+@local_ToDate+''')
--							and clk_intime>='''+@local_InTime+''' or clk_outtime<='''+@local_OutTime+''''
--		end
--	else
--		begin
--			Set @SelectSQL = @SelectSQL + 'And (CD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_intime between '''+@local_InTime+''' and '''+@local_OutTime+''''
--			Set @SelectSQL = @SelectSQL + 'or CD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_Outtime between '''+@local_InTime+''' and '''+@local_OutTime+''')'
--		end 
--	if(@local_shift<>0)
--		begin
--			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
--		end
--	if(@isReportingto > 0)
--            BEGIN
--               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
--            END
--	Set @SelectSQL = @SelectSQL + ' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc'      
--	Exec (@SelectSQL)
--	--Drop the Temporary tables
--	drop table #EmpLevel
--	drop table #EmpDesignation
--	drop table #EmpType
--	drop table #EmpCategory
--	drop table #LevelRights  	
--	drop table #TempClockDetails 
--	drop table #TempProcessedData
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
--	Author:		R.Manikandan
--	Create date: 17-02-2014
--	Description:	To get the first and last punch details from clock details
--	Proc_TA_RptMovementsEntry_FirstAndLast '','1','11/01/2016','11/24/2016','',0,0,0,'SuperAdmin','0','',0,0,'Both','07:01 Am','11:59 PM',0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]
	-- Add the parameters for the stored procedure here
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@EmpAutoId bigint,
	@ExportType int 		
)
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	CREATE TABLE #TempClockDetails
	(	
		[Clk_EmpId] nvarchar(20) ,		
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25) ,		
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,	
		[Clk_Date] datetime,
		[Clk_InDeviceId] nvarchar(20),
		[Clk_OutDeviceId] nvarchar(20),
		[Clk_InDate] datetime,
		[Clk_OutDate] datetime	
	)
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].#TempClockDetails 
	(
		[Clk_EmpId],		
		[Clk_InTime],
		[Clk_InPunchType],				
		[Clk_OutTime],
		[Clk_OutPunchType],
		[Clk_Date],
		[Clk_InDeviceId],
		[Clk_OutDeviceId],
		[Clk_InDate],
		[Clk_OutDate]
		ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_swipecard] ON [dbo].[#EmpLevel] 
	(
		swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_swipecard ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		EmployeeId,designationid ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel = @sqlEmpLevel +' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #TempPunchtypes
	(		
		id int identity(1,1),
		clk_CardId nvarchar(25),
		clk_InDeviceId nvarchar(25),
		Clk_InPunchType nvarchar(15),
		clk_InDate datetime ,
		clk_intime datetime,
		clk_Date datetime,
		Clk_OutDeviceId nvarchar(25),
		Clk_OutPunchType nvarchar(15),
		Clk_OutDate datetime,
		Clk_OutTime datetime,
		Shiftid int,
		PMorAm bit
	)
	CREATE NONCLUSTERED INDEX IDX_Clk_InPunchType_Clk_OutPunchType
	ON [dbo].[#TempPunchtypes] ([Clk_InPunchType],[Clk_OutPunchType])
	INCLUDE ([clk_CardId],[clk_InDeviceId],[clk_intime],[clk_Date],[Clk_OutDeviceId],[Clk_OutTime])
	CREATE NONCLUSTERED INDEX IDX_clk_CardId_Clk_InPunchType_Clk_OutPunchType
	ON [dbo].[#TempPunchtypes] ([clk_CardId],[Clk_InPunchType],[Clk_OutPunchType])
	INCLUDE ([clk_InDeviceId],[clk_intime],[clk_Date],[Clk_OutDeviceId],[Clk_OutTime])
	insert into #TempPunchtypes(clk_CardId,clk_Date,Shiftid,clk_intime)
	select TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,InTime
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id	
	where ((TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102)) 
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)))and(InTime is not null or OutTime is not null)	
	Create table #tempNightShift_CurrentdateInpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	Create table #tempNightShift_CurrentdateOutpunches(clk_outtime datetime,clk_empid nvarchar(30),clk_date datetime)
	insert into #tempNightShift_CurrentdateInpunches
	select	CAST(CONVERT(CHAR(17),C.clk_intime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date=C.Clk_InDate)	
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	insert into #tempNightShift_CurrentdateOutpunches
	select	CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date=C.Clk_OutDate)	
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	--select * from #tempNightShift_CurrentdateInpunches
	--select * from #tempNightShift_CurrentdateOutpunches
	update #TempPunchtypes set clk_intime=
				case when T.clk_intime IS not null then 
								case when a.intime<T.clk_intime then a.intime 
									 else T.clk_intime 
								end 
					 else a.intime end
				,Clk_OutTime= case when T.clk_intime IS not null then a.outtime
									end 
					 from #TempPunchtypes T inner join 
	(		
			select	case when min(I.clk_Intime) IS not null then 
								case	when min(I.clk_Intime)<min(O.clk_outtime)then min(I.clk_Intime)
										else min(O.clk_outtime)
								end 
						 else min(O.clk_outtime)
					end as intime,
					case when max(O.clk_outtime) IS not null then 
								case	when Max(O.clk_outtime)<max(I.clk_Intime)then max(I.clk_Intime)
										else max(O.clk_outtime)
								end 
						 else max(I.clk_Intime)
					end as outtime
			,O.clk_date,O.clk_empid from #tempNightShift_CurrentdateOutpunches O
			Left outer join #tempNightShift_CurrentdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by O.clk_date,O.clk_empid 
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	Create table #tempNightShift_NextdateInpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	Create table #tempNightShift_NextdateOutpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	insert into #tempNightShift_NextdateInpunches
	select	C.clk_intime,C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date!=C.Clk_InDate)
	--and T.PMorAm=1
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	insert into #tempNightShift_NextdateOutpunches
	select	CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date!=C.Clk_OutDate)
	--and T.PMorAm=1
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))		
	update #TempPunchtypes set [Clk_OutTime]=case when T.clk_intime IS not null then a.Outime end,
	clk_intime=case when T.clk_intime IS null then a.Outime else T.clk_intime  end from #TempPunchtypes T inner join 
	(		
			select	case when MAX(I.clk_Intime) IS not null then 
								case	when MAX(I.clk_Intime)<MAX(O.clk_Intime)then MAX(O.clk_Intime)
										else MAX(I.clk_Intime)
								end 
						 else MAX(O.clk_Intime)
					end as Outime	
			,O.clk_date,O.clk_empid from #tempNightShift_NextdateOutpunches O
			Left outer join #tempNightShift_NextdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by O.clk_date,O.clk_empid 
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	update #TempPunchtypes set [Clk_OutTime]=a.Outime from #TempPunchtypes T inner join 
	(		
			select	case when MAX(I.clk_Intime) IS not null then 
								case	when MAX(I.clk_Intime)<MAX(O.clk_Intime)then MAX(O.clk_Intime)
										else MAX(I.clk_Intime)
								end 
						 else MAX(O.clk_Intime)
					end as Outime	
			,I.clk_date,I.clk_empid from #tempNightShift_NextdateOutpunches O
			right outer join #tempNightShift_NextdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by I.clk_date,I.clk_empid
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	update #TempPunchtypes set clk_InDeviceId=a.clk_InDeviceId,Clk_InPunchType=a.clk_InPunch
	from #TempPunchtypes T inner join 
	(		
		select	case when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)   then C.Clk_InPunchType 
					 when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime)  then C.Clk_OutPunchType
					 end as clk_InPunch,
				case when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InDeviceId 
					 when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutDeviceId
					 end as clk_InDeviceId,				
				C.Clk_EmpId,C.Clk_Date
		from TA_Tbl_ClockDetails C	
		inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
		and (T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime) or T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime))
		and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
		and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date	
	update #TempPunchtypes set Clk_OutDeviceId=a.clk_OutDeviceId,Clk_OutPunchType=a.clk_OutPunch
	from #TempPunchtypes T inner join 
	(		
		select	case when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InDeviceId 
					 when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutDeviceId
					 end as clk_OutDeviceId,
				case when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InPunchType 
					 when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutPunchType
					 end as clk_OutPunch,
				C.Clk_EmpId,C.Clk_Date
		from TA_Tbl_ClockDetails C	
		inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
		and (T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime) or T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime))
		and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
		and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int)
	CREATE NONCLUSTERED INDEX IDX_Employee_Code_Id_Date
	ON [dbo].[#TempProcessedData] ([Employee_Code_Id],[Date])
	INCLUDE ([Shift_ID],[PrevShiftType])
	CREATE NONCLUSTERED INDEX IDX_PrevShift_ID_PrevShiftType
	ON [dbo].[#TempProcessedData] (PrevShift_ID,PrevShiftType)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,''
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END	
	Declare @SelectSQL As Varchar(8000)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = ' '        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + '	SELECT ED.employee_code_id AS ''Employee ID'', '      
		Set @SelectSQL = @SelectSQL + '	ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',ED.Gender,case when '+cast(@dateFormat as varchar(100))+'=106 then			
									REPLACE(CONVERT(VARCHAR, CD.Clk_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, CD.Clk_Date, '+cast(@dateFormat as varchar(100))+') end as Date,ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,'      
		Set @SelectSQL = @SelectSQL + '	case when CD.Clk_InDeviceId=''787'' then ''-'' else  CD.Clk_InDeviceId end as ''In Reader ID'',	
		Convert(varchar(10),CD.Clk_InTime,108)
		as InTime,
		case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) 
		then case	when CD.Clk_InPunchType=''Shift In'' then ''F_In'' 
					when CD.Clk_InPunchType=''Shift Out'' then ''F_Out'' 
					else ''F_In'' 
			end
		else CD.Clk_InPunchType end as Clk_InPunchType,'      
		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_OutDeviceId=''788'' then ''-'' else  CD.Clk_OutDeviceId end	as ''Out Reader ID'',
			Convert(varchar(10),CD.Clk_OutTime,108)
		as OutTime,	
		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then 
			case	when CD.Clk_OutPunchType=''Shift In'' then ''F_In'' 
					when CD.Clk_OutPunchType=''Shift Out'' then ''F_Out'' 
					else ''F_Out'' 
			end
		else CD.Clk_OutPunchType end as Clk_OutPunchType FROM TA_Tbl_Employee ED '   
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + '	SELECT ED.employee_code_id AS CardNo, '      
		Set @SelectSQL = @SelectSQL + '	ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
		Set @SelectSQL = @SelectSQL + '	case when CD.Clk_InDeviceId=''787'' then ''-'' else  CD.Clk_InDeviceId end as InReaderID,	
		ITer.Terminal_Name as InTerminalName,	
		Convert(varchar(10),CD.Clk_InTime,108)
		as InTime,
		case when (((CD.Clk_InPunchType = ''I'') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) 
		then case	when CD.Clk_InPunchType=''Shift In'' then ''F_In'' 
					when CD.Clk_InPunchType=''Shift Out'' then ''F_Out'' 
					else ''F_In'' 
			end
		else CD.Clk_InPunchType end as Clk_InPunchType,'      
		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_OutDeviceId=''788'' then ''-'' else  CD.Clk_OutDeviceId end	as OutReaderID,OTer.Terminal_Name as OutTerminalName,
			Convert(varchar(10),CD.Clk_OutTime,108)
		as OutTime,	
		case when (((CD.Clk_OutPunchType = ''O'') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then 
			case	when CD.Clk_OutPunchType=''Shift In'' then ''F_In'' 
					when CD.Clk_OutPunchType=''Shift Out'' then ''F_Out'' 
					else ''F_Out'' 
			end
		else CD.Clk_OutPunchType end as Clk_OutPunchType,									
										case when '+cast(@dateFormat as varchar(100))+'=106 then			
									REPLACE(CONVERT(VARCHAR, CD.Clk_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, CD.Clk_Date, '+cast(@dateFormat as varchar(100))+') end as ClockDate,									
										ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,ED.Gender,
										PD.Shift_ID FROM TA_Tbl_Employee ED '   
	end
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempPunchtypes CD ON ED.SwipeCardNo = CD.clk_CardId'
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.clk_CardId and PD.Date=CD.Clk_Date'   
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID '  
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID '       
	Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and clk_inpunchtype is not null and clk_outpunchtype is not null and 
									((ED.employee_status=1)
									or
									(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
									)
								  '	
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Set @SelectSQL = @SelectSQL + ' Order By CD.clk_cardid,CD.clk_date'      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails 
	drop table #TempProcessedData   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_NotMatched]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
	Modified By		:	A.K.T.MOORTHI
	Modified Date	:	09-Oct-2013
	Description		:	Dispaly In/Out Punch Type For 'F_In' And 'F_Out' When Emplopyee Shift IS Free Scan Shift Type.(Reg Bug No : 0019304)
	Modified By		:	K.Gopinath
	Modified Date	:	18-Dec-2013 & 11-Jan-2014
	Description		:	SQL Query Optimazation & Emp name filtering
*/
-- Proc_TA_RptMovementsEntry 'emp1','1','01/01/2013','07/22/2013','',0,0,0,'SuperAdmin','0','',0,0,'Both','00:01 Am','12:59 PM'
-- [Proc_TA_RptMovementsEntry_NotMatched] '','1','11/01/2016','11/24/2016','',0,0,0,'SuperAdmin','0','',0,0,'Both','07:01 Am','11:59 PM',0,1
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_NotMatched]      
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@EmpAutoId bigint,
	@ExportType int
)      
AS      
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	--Get current date time format.
	DECLARE @dateFormat as int
	select @dateFormat = DateFormat from dbo.Func_TA_GetDateTimeFormat()
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,[Clk_CompId] varchar(10) ,[Clk_EmpId] nvarchar(20) ,
		[Clk_InDeviceId] nvarchar(20) ,[Clk_InDate] datetime,
		[Clk_InTime] datetime,[Clk_InPunchType] nvarchar(25) ,[Clk_OutDeviceId] nvarchar(20) ,
		[Clk_OutDate] datetime,[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,[Clk_Process] nvarchar(1) ,
		[Clk_Remarks] nvarchar(255) ,[Clk_User] nvarchar(20) ,
		[Clk_Date] datetime,[Clk_Status] char(1) ,[IsVoid] bit
	)
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].#TempClockDetails 
	(
		[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],	[Clk_InTime] ,	[Clk_InPunchType],
		[Clk_OutDeviceId],	[Clk_OutDate],	[Clk_OutTime],	[Clk_OutPunchType],[Clk_Date] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_levelid ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_swipecard ON [dbo].[#EmpLevel] 
	(
		swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_DesignationId ON [dbo].[#EmpDesignation] 
	(
		EmployeeId,DesignationId ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end	
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end	
	set @sqlEmpLevel=@sqlEmpLevel+' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)	
	set @sqlTempProcessedData1=
	'insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails
	where ta_tbl_clockdetails.IsVoid=0
	and (ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,'''+cast(@local_FromDate as nvarchar(20))+''', 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(20))+''', 102))and (clk_Indate is null or  clk_outdate is null)'
	Execute(@sqlTempProcessedData1)	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime)
	CREATE NONCLUSTERED INDEX IDX_Employee_Code_Id
	ON [dbo].[#TempProcessedData] ([Employee_Code_Id])
	INCLUDE ([Shift_ID],[Date])
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date 
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	Declare @SelectSQL As Varchar(8000)      	
	Set @SelectSQL = ' '        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS ''Employee ID'', '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',ED.Gender,case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ''Date'',ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,'      
		Set @SelectSQL = @SelectSQL + 'case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as ''In Reader ID'',case when (((CD.Clk_InPunchType = ''I'') OR (SH.ShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as ''In Punch Type'',case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS ''In Date'',Convert(varchar(10),CD.Clk_InTime,108) as InTime ,'      
		Set @SelectSQL = @SelectSQL + ' case when CD.Clk_OutDeviceId=''788'' then ''-'' else 
		OTer.Terminal_Name end as ''Out Reader ID'',case when (((CD.Clk_OutPunchType = ''O'') OR (SH.ShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as ''Out Punch Type'',
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS ''Out Date'', Convert(varchar(10),CD.Clk_OutTime,108) as ''Out Time''
		 FROM TA_Tbl_Employee ED '      
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS CardNo, '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
		Set @SelectSQL = @SelectSQL + 'CD.Clk_InDeviceId as InReaderID,
		case when CD.Clk_InDeviceId=''787'' then ''-'' else ITer.Terminal_Name end as InTerminalName,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_InDate, '+CONVERT(varchar,@dateFormat)+') end AS InDate,
		Convert(varchar(10),CD.Clk_InTime,108) as InTime ,case when (((CD.Clk_InPunchType = ''I'') OR (SH.ShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''F_In'' else CD.Clk_InPunchType end as Clk_InPunchType,'      
		Set @SelectSQL = @SelectSQL + 'CD.Clk_OutDeviceId as OutReaderID,
		case when CD.Clk_OutDeviceId=''788'' then ''-'' else 
		OTer.Terminal_Name end as OutTerminalName,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_OutDate, '+CONVERT(varchar,@dateFormat)+') end AS OutDate, 
		Convert(varchar(10),CD.Clk_OutTime,108) as OutTime,
		case when (((CD.Clk_OutPunchType = ''O'') OR (SH.ShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''F_Out'' else CD.Clk_OutPunchType end as Clk_OutPunchType,
		case when cast('+CONVERT(varchar,@dateFormat) +'as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
		else CONVERT(VARCHAR, Clk_Date, '+CONVERT(varchar,@dateFormat)+') end AS ClockDate,
		ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,ED.Gender FROM TA_Tbl_Employee ED '   
	end
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID '  
	Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID 
	LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID '       
	Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) '	
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)='PM' and substring(@local_OutTime,7,8)='AM')
		begin
			Set @SelectSQL = @SelectSQL + 'And clk_indate>='''+@local_FromDate+''' and clk_outdate<=dateadd(d,1,'''+@local_ToDate+''')
							and clk_intime>='''+@local_InTime+''' or clk_outtime<='''+@local_OutTime+''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + 'And (CD.Clk_InDate between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_intime between '''+@local_InTime+''' and '''+@local_OutTime+''''
			Set @SelectSQL = @SelectSQL + 'or CD.Clk_OutDate between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_Outtime between '''+@local_InTime+''' and '''+@local_OutTime+''')'
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  PD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
		end       
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Set @SelectSQL = @SelectSQL + ' Order By ED.employee_code_id,CD.Clk_Date,Clk_Id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc'      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempClockDetails 
	drop table #TempProcessedData   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptMovementsEntryWithMatchedPunches '787','0,1','2014/09/01','2014/10/01','',0,0,0,'SuperAdmin','0','',0,0,'Both','07:01 Am','11:59 PM',2,1,1
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@Type int,
	@EmpAutoId bigint,
	@ExportType int
)	
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_Type int
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_Type=@Type
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 '
	if(@local_Gender<>'Both')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
		end
	set @sqlEmpLevel = @sqlEmpLevel +' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'
	If Not (@local_EmployeeID = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@local_EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int,lateInMins int,EarlyExitMin int)
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	)ON [PRIMARY]
	Create table #TempOutPunches
	(
		[tempId] int identity(1,1),
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_OutPunchType] [nvarchar](25) NULL,
		[Clk_Date] [datetime] NULL,
		[Clk_OutDate] [datetime] NULL,
		[Clk_OutDeviceId] [nvarchar](20) NULL
	)
	Create table #TempMatchedPunches
	(		
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_InDeviceId] [nvarchar](20) NULL,
		[Clk_InDate] [datetime] NULL,
		[Clk_InTime] [datetime] NULL,
		[Clk_InPunchType] [nvarchar](25) NULL,		
		[Clk_OutDeviceId] [nvarchar](20) NULL,
		[Clk_OutDate] [datetime] NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_OutPunchType] [nvarchar](25) NULL,
		[Clk_Date] [datetime] NULL,
		[TempIdFromOutPunches] int default 0,
		OrderBy int
	)
	if(@Type!=4)
		begin
			insert into #TempMatchedPunches(Clk_EmpId,Clk_InTime,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,OrderBy)
			select Clk_EmpId,min(Clk_InDate+' '+ Clk_InTime),Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,
			case when Clk_InPunchType='In' then 1 else 2 end from TA_Tbl_ClockDetails 
			inner join #EmpLevel on Clk_EmpId=SwipeCard
			where ta_tbl_clockdetails.IsVoid=0
			and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
			and Clk_InPunchType in('In','Shift In')
			--and Clk_EmpId='787'
			group by Clk_EmpId,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId
		end
	insert into #TempMatchedPunches(Clk_EmpId,Clk_InTime,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,OrderBy)
	select Clk_EmpId,min(Clk_OutDate+' '+Clk_OutTime),Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId,3 from TA_Tbl_ClockDetails 
	inner join #EmpLevel on Clk_EmpId=SwipeCard
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	and Clk_OutPunchType in('Lunch Out')
	--and Clk_EmpId='787'
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId
	if(@Type!=4)
		begin
			insert into #TempOutPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId)
			select Clk_EmpId,max(Clk_OutDate+' '+Clk_OutTime),Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId from TA_Tbl_ClockDetails 
			inner join #EmpLevel on Clk_EmpId=SwipeCard
			where ta_tbl_clockdetails.IsVoid=0
			and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
			and Clk_OutPunchType in('Out','Shift Out')
			--and Clk_EmpId='787'
			group by Clk_EmpId,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId
		end
	insert into #TempOutPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId)
	select Clk_EmpId,max(Clk_InDate+' '+Clk_InTime),Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId from TA_Tbl_ClockDetails 
	inner join #EmpLevel on Clk_EmpId=SwipeCard
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	and Clk_InPunchType in('Lunch In')
	--and Clk_EmpId='787'
	group by Clk_EmpId,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId 
	if(@Type!=4)
		begin
			update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType='In' then OP.Clk_OutTime end,
			Clk_OutPunchType=case when MP.Clk_InPunchType='In' then OP.Clk_OutPunchType end, 
			TempIdFromOutPunches=case when MP.Clk_InPunchType='In' then tempId else TempIdFromOutPunches end,
			[Clk_OutDeviceId]=case when MP.Clk_InPunchType='In' then OP.Clk_OutDeviceId end,
			Clk_OutDate=case when MP.Clk_InPunchType='In' then OP.Clk_OutDate end
			from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
			where OP.Clk_OutPunchType='Out'
			update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType='Shift In' then OP.Clk_OutTime end, 
			Clk_OutPunchType=case when MP.Clk_InPunchType='Shift In' then OP.Clk_OutPunchType end,
			TempIdFromOutPunches=case when MP.Clk_InPunchType='Shift In' then tempId else TempIdFromOutPunches end,
			[Clk_OutDeviceId]=case when MP.Clk_InPunchType='Shift In' then OP.Clk_OutDeviceId end,
			Clk_OutDate=case when MP.Clk_InPunchType='Shift In' then OP.Clk_OutDate end
			from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
			where OP.Clk_OutPunchType='Shift Out'
		end
	update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType='Lunch Out' then OP.Clk_OutTime else MP.Clk_OutTime end,
	Clk_OutPunchType=case when MP.Clk_InPunchType='Lunch Out' then OP.Clk_OutPunchType else MP.Clk_OutPunchType end ,
	TempIdFromOutPunches=case when MP.Clk_InPunchType='Lunch Out' then tempId else TempIdFromOutPunches end,
	[Clk_OutDeviceId]=case when MP.Clk_InPunchType='Lunch Out' then OP.Clk_OutDeviceId else MP.Clk_OutDeviceId end,
	Clk_OutDate=case when MP.Clk_InPunchType='Lunch Out' then OP.Clk_OutDate else MP.Clk_OutDate end
	from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
	where OP.Clk_OutPunchType='Lunch In' and OP.Clk_OutPunchType is not null
	insert into #TempMatchedPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,TempIdFromOutPunches)
	select Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,0
	from #TempOutPunches OP where tempId not in(
	select isnull(TempIdFromOutPunches,0) from #TempOutPunches OP inner join #TempMatchedPunches MP on MP.Clk_EmpId=OP.Clk_EmpId
	and MP.Clk_Date=OP.Clk_Date
	)
	insert into #TempMatchedPunches
	select Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date,0,4
	from ta_tbl_MatchedPunches
	where clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	--and Clk_EmpId='787'
	DECLARE @dateFormat as int
	SELECT @dateFormat = DateFormat FROM dbo.Func_TA_GetDateTimeFormat()
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,'',LateInMins,EarlyOutMins
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	Declare @SelectSQL As Varchar(8000)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = ' '        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + 'SELECT ED.Employee_code_id as ''Employee ID'', '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',ED.Gender,'      
		Set @SelectSQL = @SelectSQL + '				
		case when	'+cast(@dateFormat as varchar(100))+'=106 then
						REPLACE(CONVERT(VARCHAR, Clk_Date,106),'' '',''-'')
				else	convert(varchar(20),Clk_Date,'+convert(varchar(5),@dateFormat)+') 
			end as ''Date'',ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName,		
		case	when (((PD.Clk_InPunchType = ''I'') OR (TPD.PrevShiftType = 1)) and (PD.Clk_InTime IS NOT NULL)) then ''F_In'' 			
				else PD.Clk_InPunchType end as ''In Punch Type'',
		case when [Clk_InDate] IS null then '''' else 	
			case when	'+cast(@dateFormat as varchar(100))+'=106 then
						REPLACE(CONVERT(VARCHAR, Clk_InDate,106),'' '',''-'')
				else	convert(varchar(20),Clk_InDate,'+convert(varchar(5),@dateFormat)+') 
			end			
		end as ''In Date'',
		convert(varchar(20),[Clk_InTime],108) ''In Time'' , 
		case	when (((PD.Clk_OutPunchType = ''O'') OR (TPD.PrevShiftType = 1)) and (PD.Clk_OutTime IS NOT NULL)) then ''F_Out'' 			
				else pD.Clk_OutPunchType end as ''Out Punch Type'','	
		Set @SelectSQL = @SelectSQL + '	
		case when [Clk_OutDate]  IS null then '''' else 
					case	when	'+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Clk_OutDate,106),'' '',''-'')
							else	convert(varchar(20),[Clk_OutDate],'+convert(varchar(5),@dateFormat)+')
					end
		end ''Out Date'',	
		convert(varchar(20),[Clk_OutTime],108) ''Out Time''
		FROM TA_Tbl_Employee ED '      
		set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '	
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempMatchedPunches PD ON PD.[Clk_EmpId] = ED.SwipeCardNo'   
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData TPD ON TPD.Employee_Code_Id = PD.Clk_EmpId and TPD.Date=PD.Clk_Date'   
		Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = TPD.Shift_ID '  
		Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and 
		((ED.employee_status=1)
		or
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),PD.Clk_Date,102))
		 ) and Clk_InPunchType is not null and Clk_OutPunchType is not null '
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + 'SELECT ED.Employee_code_id as CardNo, '      
		Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
		Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', '      
		Set @SelectSQL = @SelectSQL + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS Designation, '      
		set @SelectSQL = @SelectSQL + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'','      
		Set @SelectSQL = @SelectSQL + '
		case when [Clk_InDate] IS null then '''' else 	
			case when	'+cast(@dateFormat as varchar(100))+'=106 then
						REPLACE(CONVERT(VARCHAR, Clk_InDate,106),'' '',''-'')
				else	convert(varchar(20),Clk_InDate,'+convert(varchar(5),@dateFormat)+') 
			end			
		end as InDate,	
		convert(varchar(20),[Clk_InTime],108)InTime ,	
		case	when (((PD.Clk_InPunchType = ''I'') OR (TPD.PrevShiftType = 1)) and (PD.Clk_InTime IS NOT NULL)) then ''F_In'' 			
				else PD.Clk_InPunchType end as Clk_InPunchType,'	
		Set @SelectSQL = @SelectSQL + '	
		case when [Clk_OutDate]  IS null then '''' else 
					case	when	'+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Clk_OutDate,106),'' '',''-'')
							else	convert(varchar(20),[Clk_OutDate],'+convert(varchar(5),@dateFormat)+')
					end
		end OutDate,	
		convert(varchar(20),[Clk_OutTime],108) OutTime,	
		case	when (((PD.Clk_OutPunchType = ''O'') OR (TPD.PrevShiftType = 1)) and (PD.Clk_OutTime IS NOT NULL)) then ''F_Out'' 			
				else pD.Clk_OutPunchType end as Clk_OutPunchType,			
		case when	'+cast(@dateFormat as varchar(100))+'=106 then
						REPLACE(CONVERT(VARCHAR, Clk_Date,106),'' '',''-'')
				else	convert(varchar(20),Clk_Date,'+convert(varchar(5),@dateFormat)+') 
			end as ClockDate,ED.Gender, 		 
		TPD.lateInMins as InReaderID,'''' as InTerminalName,EarlyExitMin as OutReaderID,'''' as OutTerminalName,
		ISNULL(SH.Shift_ShortName,''Off'') as Shift_ShortName
		FROM TA_Tbl_Employee ED '      
		set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
		set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id '
		set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id '	
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempMatchedPunches PD ON PD.[Clk_EmpId] = ED.SwipeCardNo'   
		Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempProcessedData TPD ON TPD.Employee_Code_Id = PD.Clk_EmpId and TPD.Date=PD.Clk_Date'   
		Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = TPD.Shift_ID '  
		Set @SelectSQL = @SelectSQL + ' Where ED.IsDeleted = ''0'' and ED.report_exclude=0 and 
		((ED.employee_status=1)
		or
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),PD.Clk_Date,102))
		 ) and Clk_InPunchType is not null and Clk_OutPunchType is not null '
	end
	if(@local_UserGroupName<>'SuperAdmin')
		begin
			SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)='PM' and substring(@local_OutTime,7,8)='AM')
		begin
			Set @SelectSQL = @SelectSQL + 'And Clk_Date>='''+@local_FromDate+''' and Clk_Date<=dateadd(d,1,'''+@local_ToDate+''')
							and clk_intime>='''+@local_InTime+''' or clk_outtime<='''+@local_OutTime+''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + 'And (PD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_intime between '''+@local_FromDate+space(1)+ @local_InTime+''' and '''+@local_ToDate+space(1)+@local_OutTime+''''
			Set @SelectSQL = @SelectSQL + 'or PD.Clk_Date between ''' + @local_FromDate + ''' And ''' + @local_ToDate + ''' and clk_Outtime between '''+@local_FromDate+space(1)+@local_InTime+''' and '''+@local_ToDate+space(1)+@local_OutTime+''')'
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  ' And  TPD.Shift_Id = ' +  cast(@local_shift  as nvarchar(20))   
		end       
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	Set @SelectSQL = @SelectSQL + ' order by Clk_EmpId,clk_date,OrderBy'
	Exec (@SelectSQL)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	 
	drop table #TempProcessedData   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMyCalendar]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    
Proc_TA_RptMyCalendar 'IndividualUsers',33

*/
CREATE PROCEDURE [dbo].[Proc_TA_RptMyCalendar]
(   @USERGROUPNAME VARCHAR(250), 
	@EmpAutoId bigint
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	DECLARE @FROMDAT DATETIME
	DECLARE @TODAT DATETIME
	Declare @yearEnd Datetime
	Declare @EmployeeCode_id nvarchar(50)	
	select @EmployeeCode_id =Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId and Isdeleted=0 and Employee_Status=1
	DECLARE @PARENTID INT
	SET @PARENTID = 0
	if( (select FromDate from ta_tbl_yearsetting where Isactive=1) is null)  
	begin  
		set @FROMDAT='01/01/1900'  
		set @TODAT='01/01/1900'      
	end  
	else  
	begin  
		select @TODAT= GETDATE(),@FROMDAT =FromDate from ta_tbl_yearsetting where Isactive=1  
		if (@ParentId =0 )  
		begin  
			select @TODAT= dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate)   
			from ta_tbl_yearsetting where Isactive=1   
		end  
		else
		begin  
		 --if successive year is not defined means, leave application throws unwanted error message.To avoid that, we added below conditon  
			 if exists(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@ParentId)  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=@ParentId),ToDate) from ta_tbl_yearsetting where Isactive=1  
			 end  
			 else  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=-1),ToDate) from ta_tbl_yearsetting where Isactive=1  
			end  
		end  
	end  
	--set @FROMDAT='20180317'
	--set @TODAT='2018031'
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(max),
		FNATTENDANCECODE NVARCHAR(max),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS FLOAT,
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,0) AS LEVELID  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @TODAT,@EmployeeCode_id,0
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 '
	if(@EmpAutoId > 0)
	BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + ' and (EMP.Employee_ID =' + CAST(@EmpAutoId AS NVARCHAR(8)) + ') '  
	END		
	SET @SQLEMPLEVEL=@SQLEMPLEVEL+' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	EXECUTE(@SQLEMPLEVEL)	
	
	SET @SQLTEMPPROCESSEDDATA=	'INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID ' 
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0'		
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	
	SET @SQLTEMPPROCESSEDDATA1=
	'INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	#TEMPEMPLOYEE.EMPAUTOID,
			TA_TBL_PROCESSEDDATA.DATE,
			TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID,
			TA_TBL_PROCESSEDDATA.INTIME,
			TA_TBL_PROCESSEDDATA.OUTTIME,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.HRSWORK,
			TA_TBL_PROCESSEDDATA.WORKHRS,
			TA_TBL_PROCESSEDDATA.STATUS,
			TA_TBL_PROCESSEDDATA.ATTENDANCE,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''Holiday'' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''Holiday'' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.ANATTENDANCECODE end,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''Holiday'' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''Holiday'' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.FNATTENDANCECODE end,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.PROCESS_REC_ID,
			S.SHIFT_STARTTIME,
			CAST(S.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			TA_TBL_PROCESSEDDATA.NORMOT,
			TA_TBL_PROCESSEDDATA.OFFOT,
			TA_TBL_PROCESSEDDATA.HOLOT,
			OTMINS,
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS
	FROM TA_TBL_PROCESSEDDATA INNER JOIN #TEMPEMPLOYEE ON #TEMPEMPLOYEE.EMPSWIPECARDNO=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102))' 
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(
		FIRSTSESSION VARCHAR(500),SECONDSESSION VARCHAR(500),
		EMPLOYEE_ID VARCHAR(25),EMPNAME VARCHAR(500),BRANCHNAME VARCHAR(500),DESIGNATION VARCHAR(250),
		DATE DATETIME,INTIME VARCHAR(30),OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),SUPPOSEDWORKHOURS VARCHAR(30),STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),LATEIN NVARCHAR(10),OVERTIME VARCHAR(20),
		NORMOTMIN INT,OFFOTMIN INT,HOLOTMIN INT,NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),HOLOT NVARCHAR(20),LATEINMIN INT,EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,TOTSUPWORKHRS INT,OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,LUNCHINTIME NVARCHAR(20),LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CategoryName 	NVARCHAR(100),
		WeekDay_WorkHrs NVARCHAR(100),
		WeekNumber int,ExceptionMins BIGINT
	)
	Declare @ExceptionMins bigint
	--due to this line, we got date time conversion error and calendar is not loading. So commented on 21-Apr-2020 08:20 Pm
	--Got this in abraj client place
	--select top 1 @ExceptionMins=DATEDIFF(MI, '00:00', ISNULL(MaxWorkPlaceInHours, '00:10')) from TA_Tbl_ShiftSettings 
	set @ExceptionMins=0
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT PD.FNATTENDANCECODE AS FIRSTSESSION, PD.ANATTENDANCECODE AS SECONDSESSION,E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
	WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
	ELSE PD.SUPPOSEDWORKHOURS END ''SUPPOSEDWORKHOURS'',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED'  
	SET @SQLQUERY = @SQLQUERY + ' ,(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
						 WHEN PD.SHIFT_ID=-1 THEN ''-''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''00:00''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.OFFOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.HOLOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 ELSE ''00:00'' END OVERTIME,
	CASE ISNULL(NORMOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''NORMOTMINS'',
	CASE ISNULL(OFFOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''WEEKOFFOTMINS'',
	CASE ISNULL(HOLOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''HOLIDAYOTMINS'',
	PD.NORMOT AS HRSOT,PD.OFFOT,PD.HOLOT,LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' ELSE OVERTIMESTATUS END,NIGHTORMORN,''00:00'',''00:00'',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CategoryName,WeekDay_WorkHrs,
	DATEPART(week,date),'''+convert(varchar,@ExceptionMins)+''''
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
	SET @SQLQUERY = @SQLQUERY + ' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId '
		SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, ''' + CAST(@FROMDAT AS NVARCHAR(11)) + ''', 102) AND PD.DATE <= CONVERT(DATETIME, ''' + CAST(@TODAT AS NVARCHAR(11)) + ''', 102)))'    
		if(@EmpAutoId > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (e.Employee_ID =' + CAST(@EmpAutoId AS NVARCHAR(8)) + ') '  
		END
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)		
	
	--Select * From  #TEMPMONTHLYATTENDANCE

	UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=CASE WHEN (FIRSTSESSION='PRESENT' OR FIRSTSESSION='*PRESENT' OR FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY' OR FIRSTSESSION='WEEKLY OFF' OR FIRSTSESSION='*WEEKLY OFF') AND INNOTATION='M' THEN  FIRSTSESSION
	ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE
	WHEN (SECONDSESSION='PRESENT' OR SECONDSESSION = '*PRESENT' OR SECONDSESSION ='HOLIDAY' OR SECONDSESSION ='*HOLIDAY' OR SECONDSESSION ='WEEKLY OFF' OR SECONDSESSION ='*WEEKLY OFF')  AND OUTNOTATION='M' THEN  SECONDSESSION
	ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE	
	
	--UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=
	--CASE WHEN (FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY') 
	--THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	--ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	
	Update #TEMPMONTHLYATTENDANCE set FIRSTSESSION=case when len(Holiday_Description)>50 then substring(Holiday_Description,0,25)+'..' else Holiday_Description end from #TEMPMONTHLYATTENDANCE TM
	INNER JOIN TA_Tbl_Holiday H on TM.DATE=H.Holiday_FromDate
	WHERE (FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY')
	
	Update #TEMPMONTHLYATTENDANCE set SECONDSESSION=case when len(Holiday_Description)>50 then substring(Holiday_Description,0,25)+'..' else Holiday_Description end from #TEMPMONTHLYATTENDANCE TM
	INNER JOIN TA_Tbl_Holiday H on TM.DATE=H.Holiday_FromDate
	WHERE (SECONDSESSION='HOLIDAY' OR SECONDSESSION='*HOLIDAY')
	
	--UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE WHEN (SECONDSESSION='HOLIDAY' OR SECONDSESSION='*HOLIDAY') THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	--ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE
	
	DECLARE @DATEFORMAT AS INT
	Declare @toConfrmAngler int
	select @toConfrmAngler =pageId from ta_tbl_page where pageid=185--payroll configuration page id
	SET @DATEFORMAT = 126
	CREATE TABLE #TEMPMYCALENDAR(SINO int identity(1,1) primary key,EMPLOYEE_ID nVarchar(100),shift_Date nvarchar(50),SHIFT_SHORTNAME nvarchar(20),HRSWORK nvarchar(25),STATUS nvarchar(max),STATUS2 nvarchar(max),EXPHRS nvarchar(25),TOTALMINSWORKED int,INTIME VARCHAR(30),OUTTIME VARCHAR(30),lateInmins int default(0),earlyOutmins int default(0),shiftTimings nvarchar(30),numberofdays float)
	if(@toConfrmAngler>0)
	begin
		Create table #tempBreakHours(id int identity(1,1),ShiftDate datetime,Employee_code_id varchar(20),TotalBreakmin int)
		CREATE NONCLUSTERED INDEX [IDX_tempBreakHours] ON [DBO].#tempBreakHours(ShiftDate,Employee_code_id,TotalBreakmin) ON [PRIMARY] 
		Insert into #tempBreakHours
		select ShiftDate,Employee_Code_Id,TotalBreakmin from ta_tbl_TotalBreakHours 
		where (ShiftDate>=@FROMDAT and ShiftDate<=@TODAT) and TotalBreakmin is not null
		DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
		--select * from #TEMPMONTHLYATTENDANCE
		--select @FROMDAT,@TODAT
		INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, FIP.[Date] , SUM(PunchDifferenceMins), 
			REPLACE(REPLACE((SELECT ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')' + (CASE WHEN LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')') < 160 THEN SPACE(160 - LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')')) ELSE '' END) FROM TA_VW_FirstInPunchDifference TT WHERE TT.EmployeeCodeId = FIP.EmployeeCodeId AND TT.[Date] = FIP.[Date] FOR XML PATH('')), '&gt;', '>'), '&lt;', '<') ToolTip
		FROM TA_VW_FirstInPunchDifference FIP 		
		inner join #TEMPMONTHLYATTENDANCE TM on (TM.EMPLOYEE_ID=FIP.EmployeeCodeId) and (FIP.[Date]=TM.DATE)
		WHERE (FIP.[Date] BETWEEN @FROMDAT AND @TODAT)
		GROUP BY EmployeeCodeId, FIP.[Date]  
		HAVING SUM(PunchDifferenceMins) > 0		
		update #TEMPMONTHLYATTENDANCE set HrsWork=Case when ISNULL(TotalBreakmin,0)>0 THEN CASE WHEN LEN(CAST(((TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) ELSE  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25))) = 1 THEN '0'+ CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) ELSE CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) END Else HrsWork End
		,TotalMinsWorked=Case When (ISNULL(TotalBreakmin,0)>0) Then TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT) Else TotalMinsWorked End	
		FROM #TEMPMONTHLYATTENDANCE TM inner join #tempBreakHours TB on TM.EMPLOYEE_ID=TB.Employee_code_id and TM.DATE=TB.ShiftDate
		UPDATE #TEMPMONTHLYATTENDANCE SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE	WHEN EH.TotalHrs > TM.TotalMinsWorked THEN '00:00' 
																		ELSE (CASE	WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																					ELSE  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																			  END  + ':' + 
																			  CASE  WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																					ELSE CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																			  END
																		     ) 
																END) 
       ELSE HrsWork END),
        TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > TotalMinsWorked THEN 0 ELSE (TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TEMPMONTHLYATTENDANCE TM
		RIGHT JOIN @TempExecptionHrs EH ON TM.EMPLOYEE_ID=EH.Employee_code_id and TM.DATE=EH.Date
		insert into #TEMPMYCALENDAR SELECT EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
					REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS='Holiday' then 'Holiday' else FIRSTSESSION end,
		case when STATUS='Holiday' then 'Holiday' else SECONDSESSION end,
		case when @toConfrmAngler>0 then cast(dateadd(s,isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)) else
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0))	end,TOTALMINSWORKED,
		INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,
		--case when SHIFT_SHORTNAME='WEEKLY OFF' then 'OFF' else SHIFT_STARTTIME+' - '+SHIFT_ENDTIME end
		''
		FROM #TEMPMONTHLYATTENDANCE
		--Future Holiday details
		insert into #TEMPMYCALENDAR		
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), H.Holiday_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10), H.Holiday_ToDate, @DATEFORMAT),'','',H.Holiday_Description,H.Holiday_Description,'','','','','','','' from TA_Tbl_Holiday H
		inner join TA_Tbl_HolidayChildTable HC on H.Holiday_Id=HC.Holiday_Id
		inner join #EMPLEVEL EL on HC.LevelId=EL.LEVELID
		WHERE H.Holiday_FromDate>=GETDATE() and H.Holiday_ToDate<=@TODAT
		--Future Leave details
		insert into #TEMPMYCALENDAR

		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10), LA.Leave_ToDate, @DATEFORMAT),'','',LT.LeaveType +'-' + LA.Status,LT.LeaveType+'-' + LA.Status,'','','','','','','',LA.NumberOfDays from TA_Tbl_LeaveApplication LA
		--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
		inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
		inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
		inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
		where LA.IsDeleted=0 and (LA.Leave_FromDate>=GETDATE() and LA.Leave_ToDate<=@TODAT)

		--select * from #TEMPMYCALENDAR
		DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
		INSERT INTO @ArmisData
		SELECT a.*, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) 
		FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FROMDAT, @TODAT, @EmployeeCode_id)as a
		UPDATE #TEMPMYCALENDAR SET shiftTimings =
		convert(varchar,TotalTask)
		FROM #TEMPMYCALENDAR TAD
		INNER JOIN @ArmisData AD ON AD.Employee_Code_Id = TAD.EMPLOYEE_ID AND CAST(AD.[Date] AS DATE) = CAST(TAD.[Date] AS DATE)
	end
	else	
	begin
		
	--CREATE TABLE #TEMPMYCALENDAR(SINO int identity(1,1) primary key,EMPLOYEE_ID nVarchar(100),shift_Date nvarchar(50),SHIFT_SHORTNAME nvarchar(20),
	--HRSWORK nvarchar(25),STATUS nvarchar(max),STATUS2 nvarchar(max),EXPHRS nvarchar(25),TOTALMINSWORKED int,INTIME VARCHAR(30),OUTTIME VARCHAR(30)
	--,lateInmins int default(0),earlyOutmins int default(0),shiftTimings nvarchar(30),numberofdays float)

		insert into #TEMPMYCALENDAR (EMPLOYEE_ID,shift_Date,SHIFT_SHORTNAME,HRSWORK,STATUS,STATUS2,EXPHRS,TOTALMINSWORKED,INTIME,OUTTIME,lateInmins,earlyOutmins,shiftTimings,numberofdays)
		SELECT  EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
				REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
			ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS='Holiday' then 'Holiday' else FIRSTSESSION end,
		case when STATUS='Holiday' then 'Holiday' else SECONDSESSION end,
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)),TOTALMINSWORKED,INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,'',''
		FROM #TEMPMONTHLYATTENDANCE
		--Future Holiday details
		insert into #TEMPMYCALENDAR	(EMPLOYEE_ID,shift_Date,SHIFT_SHORTNAME,HRSWORK,STATUS,STATUS2,EXPHRS,TOTALMINSWORKED,INTIME,OUTTIME,lateInmins,earlyOutmins,shiftTimings,numberofdays)
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), H.Holiday_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,H.Holiday_ToDate), @DATEFORMAT),'','',
		case when LEN(H.Holiday_Description)>15 then SUBSTRING (H.Holiday_Description,0, 12)+'..' else H.Holiday_Description end,
		case when LEN(H.Holiday_Description)>15 then SUBSTRING (H.Holiday_Description,0, 12)+'..' else H.Holiday_Description end,'','','','','','','','' 
		from TA_Tbl_Holiday H
		inner join TA_Tbl_HolidayChildTable HC on H.Holiday_Id=HC.Holiday_Id
		inner join #EMPLEVEL EL on HC.LevelId=EL.LEVELID
		WHERE H.Holiday_FromDate>=GETDATE() and H.Holiday_ToDate<=@TODAT
		-- select * from TA_Tbl_Holiday
		--Future Leave details
		--Declare @FDate varchar(100)

		--Select @FDate=Leave_FromDate From TA_Tbl_LeaveApplication inner join #EMPLEVEL on EMPLOYEEID=Employee_Id where IsDeleted=0 and isCalanderflag=1 

	
			insert into #TEMPMYCALENDAR
			select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,LA.Leave_ToDate), @DATEFORMAT),
			'','',LT.LeaveType +'-' + LA.Status,LT.LeaveType+'-' + LA.Status,
		     '','','','','','','',LA.NumberOfDays from TA_Tbl_LeaveApplication LA
			--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
			inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
			inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
			inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
			where LA.IsDeleted=0  and LA.isCalanderflag=1 
			and (LA.Leave_FromDate>=GETDATE() and LA.Leave_ToDate<=@TODAT)
	

		-----------ONDUTY------HH----

		insert into #TEMPMYCALENDAR

		SELECT EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10),Onduty_FromDate,@DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,Onduty_ToDate),@DATEFORMAT),'','',
        'OD '+Onduty_Status,'OD '+Onduty_Status,'','','','','','','',''
         FROM TA_Tbl_OndutyEntry OD
		 inner join TA_Tbl_Employee E on OD.Onduty_EmployeeID=E.Employee_Code_Id
		 inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
		 WHERE OD.Isdeleted = 0

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


		 ----------------------Permission in My Calendar----------------------
		 insert into #TEMPMYCALENDAR
		 SELECT EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10),Permission_FromTime,@DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,Permission_ToTime),@DATEFORMAT),'','',
        'PA '+Permission_Status,'PA '+No_Of_Hours,'','','','','','','',''
         FROM TA_Tbl_Permission PA
		 inner join TA_Tbl_Employee E on PA.Employee_Id=E.Employee_Id
		 inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
		 WHERE PA.Isdeleted = 0

		
	end	


	Declare @list nvarchar(max)
	--slno,EmployeeAutoId,Date,ShiftTimings,Hrswork,Status,status2,ExceptionHours,Intime,outtime,latein,earlyout
	select @list=coalesce(@list,'')+CONVERT(varchar(max),isnull(SINO,''))+','+CONVERT(varchar(max),isnull(EMPLOYEE_ID,''))+','+CONVERT(varchar(max),isnull(shift_Date,''))+','+
	CONVERT(varchar(max),isnull(shiftTimings,'-'))+','+CONVERT(varchar(max),isnull(HRSWORK,''))+','+CONVERT(varchar(max),isnull(STATUS,''))+','+CONVERT(varchar(max),isnull(STATUS2,''))+','+CONVERT(varchar(max),isnull(EXPHRS,''))+','+CONVERT(varchar(10),isnull(INTIME,''))
	+','+CONVERT(varchar(10),isnull(OUTTIME,''))+','+CONVERT(varchar(10),isnull(lateInmins,0))+','+CONVERT(varchar(10),isnull(earlyOutmins,0))+','+Convert(varchar(10),ISNULL(numberofdays,0))+'%' from #TEMPMYCALENDAR
	select substring(@list,0,LEN(@list)) as 'MyCalendarOutput'

	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE
	DROP TABLE #TEMPMYCALENDAR	
	
END

--Select * From TA_Tbl_Permission where Employee_Id=33
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMyCalendar_backup20230606]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
    
Proc_TA_RptMyCalendar 'IndividualUsers',33

*/
Create PROCEDURE [dbo].[Proc_TA_RptMyCalendar_backup20230606]
(   @USERGROUPNAME VARCHAR(250), 
	@EmpAutoId bigint
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	DECLARE @FROMDAT DATETIME
	DECLARE @TODAT DATETIME
	Declare @yearEnd Datetime
	Declare @EmployeeCode_id nvarchar(50)	
	select @EmployeeCode_id =Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId and Isdeleted=0 and Employee_Status=1
	DECLARE @PARENTID INT
	SET @PARENTID = 0
	if( (select FromDate from ta_tbl_yearsetting where Isactive=1) is null)  
	begin  
		set @FROMDAT='01/01/1900'  
		set @TODAT='01/01/1900'      
	end  
	else  
	begin  
		select @TODAT= GETDATE(),@FROMDAT =FromDate from ta_tbl_yearsetting where Isactive=1  
		if (@ParentId =0 )  
		begin  
			select @TODAT= dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate)   
			from ta_tbl_yearsetting where Isactive=1   
		end  
		else
		begin  
		 --if successive year is not defined means, leave application throws unwanted error message.To avoid that, we added below conditon  
			 if exists(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@ParentId)  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=@ParentId),ToDate) from ta_tbl_yearsetting where Isactive=1  
			 end  
			 else  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=-1),ToDate) from ta_tbl_yearsetting where Isactive=1  
			end  
		end  
	end  
	--set @FROMDAT='20180317'
	--set @TODAT='2018031'
	--TEMPORARY TABLE'S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(max),
		FNATTENDANCECODE NVARCHAR(max),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS FLOAT,
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,0) AS LEVELID  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @TODAT,@EmployeeCode_id,0
	SET @SQLEMPLEVEL=
	'INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 '
	if(@EmpAutoId > 0)
	BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + ' and (EMP.Employee_ID =' + CAST(@EmpAutoId AS NVARCHAR(8)) + ') '  
	END		
	SET @SQLEMPLEVEL=@SQLEMPLEVEL+' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102) AND EL.LEVELID IS NOT NULL'	
	EXECUTE(@SQLEMPLEVEL)	
	
	SET @SQLTEMPPROCESSEDDATA=	'INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID ' 
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + ' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0'		
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	
	SET @SQLTEMPPROCESSEDDATA1=
	'INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	#TEMPEMPLOYEE.EMPAUTOID,
			TA_TBL_PROCESSEDDATA.DATE,
			TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID,
			TA_TBL_PROCESSEDDATA.INTIME,
			TA_TBL_PROCESSEDDATA.OUTTIME,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.HRSWORK,
			TA_TBL_PROCESSEDDATA.WORKHRS,
			TA_TBL_PROCESSEDDATA.STATUS,
			TA_TBL_PROCESSEDDATA.ATTENDANCE,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''Holiday'' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''Holiday'' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.ANATTENDANCECODE end,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''Holiday'' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''Holiday'' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.FNATTENDANCECODE end,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.PROCESS_REC_ID,
			S.SHIFT_STARTTIME,
			CAST(S.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			TA_TBL_PROCESSEDDATA.NORMOT,
			TA_TBL_PROCESSEDDATA.OFFOT,
			TA_TBL_PROCESSEDDATA.HOLOT,
			OTMINS,
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS
	FROM TA_TBL_PROCESSEDDATA INNER JOIN #TEMPEMPLOYEE ON #TEMPEMPLOYEE.EMPSWIPECARDNO=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,'''+CAST( @FROMDAT AS NVARCHAR(50))+''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,'''+CAST(@TODAT AS NVARCHAR(50))+''', 102))' 
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(
		FIRSTSESSION VARCHAR(500),SECONDSESSION VARCHAR(500),
		EMPLOYEE_ID VARCHAR(25),EMPNAME VARCHAR(500),BRANCHNAME VARCHAR(500),DESIGNATION VARCHAR(250),
		DATE DATETIME,INTIME VARCHAR(30),OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),SUPPOSEDWORKHOURS VARCHAR(30),STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),LATEIN NVARCHAR(10),OVERTIME VARCHAR(20),
		NORMOTMIN INT,OFFOTMIN INT,HOLOTMIN INT,NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),HOLOT NVARCHAR(20),LATEINMIN INT,EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,TOTSUPWORKHRS INT,OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,LUNCHINTIME NVARCHAR(20),LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CategoryName 	NVARCHAR(100),
		WeekDay_WorkHrs NVARCHAR(100),
		WeekNumber int,ExceptionMins BIGINT
	)
	Declare @ExceptionMins bigint
	--due to this line, we got date time conversion error and calendar is not loading. So commented on 21-Apr-2020 08:20 Pm
	--Got this in abraj client place
	--select top 1 @ExceptionMins=DATEDIFF(MI, '00:00', ISNULL(MaxWorkPlaceInHours, '00:10')) from TA_Tbl_ShiftSettings 
	set @ExceptionMins=0
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''    	
	SET @SQLQUERY = 'SELECT PD.FNATTENDANCECODE AS FIRSTSESSION, PD.ANATTENDANCECODE AS SECONDSESSION,E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
	WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
	ELSE PD.SUPPOSEDWORKHOURS END ''SUPPOSEDWORKHOURS'',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED'  
	SET @SQLQUERY = @SQLQUERY + ' ,(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
						 WHEN PD.SHIFT_ID=-1 THEN ''-''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''00:00''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.OFFOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.HOLOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 ELSE ''00:00'' END OVERTIME,
	CASE ISNULL(NORMOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''NORMOTMINS'',
	CASE ISNULL(OFFOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''WEEKOFFOTMINS'',
	CASE ISNULL(HOLOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OTMINS END AS ''HOLIDAYOTMINS'',
	PD.NORMOT AS HRSOT,PD.OFFOT,PD.HOLOT,LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' ELSE OVERTIMESTATUS END,NIGHTORMORN,''00:00'',''00:00'',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CategoryName,WeekDay_WorkHrs,
	DATEPART(week,date),'''+convert(varchar,@ExceptionMins)+''''
	SET @SQLQUERY = @SQLQUERY + ' FROM TA_TBL_EMPLOYEE E '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID'   
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID'     
	SET @SQLQUERY = @SQLQUERY + ' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID'  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID '  
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID '
	SET @SQLQUERY = @SQLQUERY + ' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId '
		SET @SQLQUERY = @SQLQUERY + ' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, ''' + CAST(@FROMDAT AS NVARCHAR(11)) + ''', 102) AND PD.DATE <= CONVERT(DATETIME, ''' + CAST(@TODAT AS NVARCHAR(11)) + ''', 102)))'    
		if(@EmpAutoId > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + ' and (e.Employee_ID =' + CAST(@EmpAutoId AS NVARCHAR(8)) + ') '  
		END
	SET @SQLQUERY = @SQLQUERY + ' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)'     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)		
	
	--Select * From  #TEMPMONTHLYATTENDANCE

	UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=CASE WHEN (FIRSTSESSION='PRESENT' OR FIRSTSESSION='*PRESENT' OR FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY' OR FIRSTSESSION='WEEKLY OFF' OR FIRSTSESSION='*WEEKLY OFF') AND INNOTATION='M' THEN  FIRSTSESSION
	ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE
	WHEN (SECONDSESSION='PRESENT' OR SECONDSESSION = '*PRESENT' OR SECONDSESSION ='HOLIDAY' OR SECONDSESSION ='*HOLIDAY' OR SECONDSESSION ='WEEKLY OFF' OR SECONDSESSION ='*WEEKLY OFF')  AND OUTNOTATION='M' THEN  SECONDSESSION
	ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE	
	
	--UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=
	--CASE WHEN (FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY') 
	--THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	--ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	
	Update #TEMPMONTHLYATTENDANCE set FIRSTSESSION=case when len(Holiday_Description)>50 then substring(Holiday_Description,0,25)+'..' else Holiday_Description end from #TEMPMONTHLYATTENDANCE TM
	INNER JOIN TA_Tbl_Holiday H on TM.DATE=H.Holiday_FromDate
	WHERE (FIRSTSESSION='HOLIDAY' OR FIRSTSESSION='*HOLIDAY')
	
	Update #TEMPMONTHLYATTENDANCE set SECONDSESSION=case when len(Holiday_Description)>50 then substring(Holiday_Description,0,25)+'..' else Holiday_Description end from #TEMPMONTHLYATTENDANCE TM
	INNER JOIN TA_Tbl_Holiday H on TM.DATE=H.Holiday_FromDate
	WHERE (SECONDSESSION='HOLIDAY' OR SECONDSESSION='*HOLIDAY')
	
	--UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE WHEN (SECONDSESSION='HOLIDAY' OR SECONDSESSION='*HOLIDAY') THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	--ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE
	
	DECLARE @DATEFORMAT AS INT
	Declare @toConfrmAngler int
	select @toConfrmAngler =pageId from ta_tbl_page where pageid=185--payroll configuration page id
	SET @DATEFORMAT = 126
	CREATE TABLE #TEMPMYCALENDAR(SINO int identity(1,1) primary key,EMPLOYEE_ID nVarchar(100),shift_Date nvarchar(50),SHIFT_SHORTNAME nvarchar(20),HRSWORK nvarchar(25),STATUS nvarchar(max),STATUS2 nvarchar(max),EXPHRS nvarchar(25),TOTALMINSWORKED int,INTIME VARCHAR(30),OUTTIME VARCHAR(30),lateInmins int default(0),earlyOutmins int default(0),shiftTimings nvarchar(30),numberofdays float)
	if(@toConfrmAngler>0)
	begin
		Create table #tempBreakHours(id int identity(1,1),ShiftDate datetime,Employee_code_id varchar(20),TotalBreakmin int)
		CREATE NONCLUSTERED INDEX [IDX_tempBreakHours] ON [DBO].#tempBreakHours(ShiftDate,Employee_code_id,TotalBreakmin) ON [PRIMARY] 
		Insert into #tempBreakHours
		select ShiftDate,Employee_Code_Id,TotalBreakmin from ta_tbl_TotalBreakHours 
		where (ShiftDate>=@FROMDAT and ShiftDate<=@TODAT) and TotalBreakmin is not null
		DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
		--select * from #TEMPMONTHLYATTENDANCE
		--select @FROMDAT,@TODAT
		INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, FIP.[Date] , SUM(PunchDifferenceMins), 
			REPLACE(REPLACE((SELECT ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')' + (CASE WHEN LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')') < 160 THEN SPACE(160 - LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')')) ELSE '' END) FROM TA_VW_FirstInPunchDifference TT WHERE TT.EmployeeCodeId = FIP.EmployeeCodeId AND TT.[Date] = FIP.[Date] FOR XML PATH('')), '&gt;', '>'), '&lt;', '<') ToolTip
		FROM TA_VW_FirstInPunchDifference FIP 		
		inner join #TEMPMONTHLYATTENDANCE TM on (TM.EMPLOYEE_ID=FIP.EmployeeCodeId) and (FIP.[Date]=TM.DATE)
		WHERE (FIP.[Date] BETWEEN @FROMDAT AND @TODAT)
		GROUP BY EmployeeCodeId, FIP.[Date]  
		HAVING SUM(PunchDifferenceMins) > 0		
		update #TEMPMONTHLYATTENDANCE set HrsWork=Case when ISNULL(TotalBreakmin,0)>0 THEN CASE WHEN LEN(CAST(((TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) ELSE  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25))) = 1 THEN '0'+ CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) ELSE CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) END Else HrsWork End
		,TotalMinsWorked=Case When (ISNULL(TotalBreakmin,0)>0) Then TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT) Else TotalMinsWorked End	
		FROM #TEMPMONTHLYATTENDANCE TM inner join #tempBreakHours TB on TM.EMPLOYEE_ID=TB.Employee_code_id and TM.DATE=TB.ShiftDate
		UPDATE #TEMPMONTHLYATTENDANCE SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE	WHEN EH.TotalHrs > TM.TotalMinsWorked THEN '00:00' 
																		ELSE (CASE	WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																					ELSE  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																			  END  + ':' + 
																			  CASE  WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																					ELSE CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																			  END
																		     ) 
																END) 
       ELSE HrsWork END),
        TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > TotalMinsWorked THEN 0 ELSE (TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TEMPMONTHLYATTENDANCE TM
		RIGHT JOIN @TempExecptionHrs EH ON TM.EMPLOYEE_ID=EH.Employee_code_id and TM.DATE=EH.Date
		insert into #TEMPMYCALENDAR SELECT EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
					REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS='Holiday' then 'Holiday' else FIRSTSESSION end,
		case when STATUS='Holiday' then 'Holiday' else SECONDSESSION end,
		case when @toConfrmAngler>0 then cast(dateadd(s,isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)) else
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0))	end,TOTALMINSWORKED,
		INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,
		--case when SHIFT_SHORTNAME='WEEKLY OFF' then 'OFF' else SHIFT_STARTTIME+' - '+SHIFT_ENDTIME end
		''
		FROM #TEMPMONTHLYATTENDANCE
		--Future Holiday details
		insert into #TEMPMYCALENDAR		
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), H.Holiday_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10), H.Holiday_ToDate, @DATEFORMAT),'','',H.Holiday_Description,H.Holiday_Description,'','','','','','','' from TA_Tbl_Holiday H
		inner join TA_Tbl_HolidayChildTable HC on H.Holiday_Id=HC.Holiday_Id
		inner join #EMPLEVEL EL on HC.LevelId=EL.LEVELID
		WHERE H.Holiday_FromDate>=GETDATE() and H.Holiday_ToDate<=@TODAT
		--Future Leave details
		insert into #TEMPMYCALENDAR
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10), LA.Leave_ToDate, @DATEFORMAT),'','',LT.LeaveType +'-' + LA.Status,LT.LeaveType+'-' + LA.Status,'','','','','','','',LA.NumberOfDays from TA_Tbl_LeaveApplication LA
		--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
		inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
		inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
		inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
		where LA.IsDeleted=0 and (LA.Leave_FromDate>=GETDATE() and LA.Leave_ToDate<=@TODAT)
		--select * from #TEMPMYCALENDAR
		DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
		INSERT INTO @ArmisData
		SELECT a.*, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) 
		FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FROMDAT, @TODAT, @EmployeeCode_id)as a
		UPDATE #TEMPMYCALENDAR SET shiftTimings =
		convert(varchar,TotalTask)
		FROM #TEMPMYCALENDAR TAD
		INNER JOIN @ArmisData AD ON AD.Employee_Code_Id = TAD.EMPLOYEE_ID AND CAST(AD.[Date] AS DATE) = CAST(TAD.[Date] AS DATE)
	end
	else	
	begin
		
	--CREATE TABLE #TEMPMYCALENDAR(SINO int identity(1,1) primary key,EMPLOYEE_ID nVarchar(100),shift_Date nvarchar(50),SHIFT_SHORTNAME nvarchar(20),
	--HRSWORK nvarchar(25),STATUS nvarchar(max),STATUS2 nvarchar(max),EXPHRS nvarchar(25),TOTALMINSWORKED int,INTIME VARCHAR(30),OUTTIME VARCHAR(30)
	--,lateInmins int default(0),earlyOutmins int default(0),shiftTimings nvarchar(30),numberofdays float)

		insert into #TEMPMYCALENDAR (EMPLOYEE_ID,shift_Date,SHIFT_SHORTNAME,HRSWORK,STATUS,STATUS2,EXPHRS,TOTALMINSWORKED,INTIME,OUTTIME,lateInmins,earlyOutmins,shiftTimings,numberofdays)
		SELECT  EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
				REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
			ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS='Holiday' then 'Holiday' else FIRSTSESSION end,
		case when STATUS='Holiday' then 'Holiday' else SECONDSESSION end,
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)),TOTALMINSWORKED,INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,'',''
		FROM #TEMPMONTHLYATTENDANCE
		--Future Holiday details
		insert into #TEMPMYCALENDAR	(EMPLOYEE_ID,shift_Date,SHIFT_SHORTNAME,HRSWORK,STATUS,STATUS2,EXPHRS,TOTALMINSWORKED,INTIME,OUTTIME,lateInmins,earlyOutmins,shiftTimings,numberofdays)
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), H.Holiday_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,H.Holiday_ToDate), @DATEFORMAT),'','',
		case when LEN(H.Holiday_Description)>15 then SUBSTRING (H.Holiday_Description,0, 12)+'..' else H.Holiday_Description end,
		case when LEN(H.Holiday_Description)>15 then SUBSTRING (H.Holiday_Description,0, 12)+'..' else H.Holiday_Description end,'','','','','','','','' 
		from TA_Tbl_Holiday H
		inner join TA_Tbl_HolidayChildTable HC on H.Holiday_Id=HC.Holiday_Id
		inner join #EMPLEVEL EL on HC.LevelId=EL.LEVELID
		WHERE H.Holiday_FromDate>=GETDATE() and H.Holiday_ToDate<=@TODAT
		-- select * from TA_Tbl_Holiday
		--Future Leave details
		Declare @FDate varchar(100)

		Select @FDate=Leave_FromDate From TA_Tbl_LeaveApplication inner join #EMPLEVEL on EMPLOYEEID=Employee_Id where IsDeleted=0 and isCalanderflag=1 

		if(@FDate>GETDATE())
		begin
			insert into #TEMPMYCALENDAR
			select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,LA.Leave_ToDate), @DATEFORMAT),'','',LT.LeaveType +'-' + LA.Status,LT.LeaveType+'-' + LA.Status,'','','','','','','',LA.NumberOfDays from TA_Tbl_LeaveApplication LA
			--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
			inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
			inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
			inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
			where LA.IsDeleted=0  and LA.isCalanderflag=1 
		End
		Else
		Begin
			
			insert into #TEMPMYCALENDAR
			select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT)+'#'+CONVERT(VARCHAR(10),dateadd(d,1,LA.Leave_ToDate), @DATEFORMAT),'','',LT.LeaveType +'-' + LA.Status,LT.LeaveType+'-' + LA.Status,'','','','','','','',LA.NumberOfDays from TA_Tbl_LeaveApplication LA
			--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
			inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
			inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
			inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
			where LA.IsDeleted=0  and LA.isCalanderflag=1 
			and (LA.Leave_FromDate>=GETDATE() and LA.Leave_ToDate<=@TODAT)
		End
		
	end	
	Declare @list nvarchar(max)
	--slno,EmployeeAutoId,Date,ShiftTimings,Hrswork,Status,status2,ExceptionHours,Intime,outtime,latein,earlyout
	select @list=coalesce(@list,'')+CONVERT(varchar(max),isnull(SINO,''))+','+CONVERT(varchar(max),isnull(EMPLOYEE_ID,''))+','+CONVERT(varchar(max),isnull(shift_Date,''))+','+
	CONVERT(varchar(max),isnull(shiftTimings,'-'))+','+CONVERT(varchar(max),isnull(HRSWORK,''))+','+CONVERT(varchar(max),isnull(STATUS,''))+','+CONVERT(varchar(max),isnull(STATUS2,''))+','+CONVERT(varchar(max),isnull(EXPHRS,''))+','+CONVERT(varchar(10),isnull(INTIME,''))
	+','+CONVERT(varchar(10),isnull(OUTTIME,''))+','+CONVERT(varchar(10),isnull(lateInmins,0))+','+CONVERT(varchar(10),isnull(earlyOutmins,0))+','+Convert(varchar(10),ISNULL(numberofdays,0))+'%' from #TEMPMYCALENDAR
	select substring(@list,0,LEN(@list)) as 'MyCalendarOutput'
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE
	DROP TABLE #TEMPMYCALENDAR	 	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOnDutyEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*   
Procedure Name : Proc_TA_RptOnDutyEntry    
Description : select OnDuty entry details
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : K.Gopinath
Created On : 01-Feb-2014  
Modified for BUg no.21817 on 12Aug14 by GOpinath
Proc_TA_RptOnDutyEntry '','','02/01/2016','12/19/2020','',0,0,'SuperAdmin','','','',0,0,'Both',0
*/  


CREATE PROCEDURE [dbo].[Proc_TA_RptOnDutyEntry] 
(
	@employeeName nvarchar(max),
	@employeeId nvarchar(max),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)
AS  
BEGIN	
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery = ''
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDate,@EmployeeId	
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	SET @TimeFormat=(Select TimeFormat from Func_TA_GetDateTimeFormat())
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	
	SELECT	distinct dbo.TA_Tbl_Employee.Employee_Code_Id as Onduty_Employee_Id,
			ISNULL(TA_Tbl_Employee.Employee_FirstName, ' ') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, ' ') AS Employee_Name,
			replace(dbo.Ta_Tbl_levelDetails.name,'&amp;','&') as name,
			TA_Tbl_Title.TitleName,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate, @dateFormat)
			end  AS Onduty_EntryDate, 
			TA_Tbl_Employee.Gender,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate, @dateFormat)
			end AS Onduty_FromDate, 
			TA_Tbl_OndutyEntry.Onduty_FromTime,
			case when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate,@dateFormat),' ','-') 
				 else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate, @dateFormat)
			end AS Onduty_ToDate, 
			TA_Tbl_OndutyEntry.Onduty_ToTime,
			replace(TA_Tbl_OndutyEntry.Onduty_Reason,'&amp;','&') as Onduty_Reason,
			TA_Tbl_OndutyEntry.Onduty_Status,
			
			TA_Tbl_OndutyEntry.Onduty_ID,
			Case When TA_Tbl_OndutyEntry.Onduty_Status='Pending' then '-'
			 Else E1.Employee_FirstName 
			 End As Approved_BY, 
			 Case when @dateFormat=106 then 
			 REPLACE(CONVERT(VARCHAR,TA_Tbl_OnDutyConversation.Timestamp,@dateFormat),' ','-')
			 else CONVERT(VARCHAR,TA_Tbl_OnDutyConversation.Timestamp,@dateFormat)
			 End  As Approved_Date
			 --End + case when @TimeFormat='hh:mm' then 
			 -- SPACE(1)+SUBSTRING(CONVERT(varchar(20),DATEADD (minute,0,convert(datetime,TA_Tbl_OnDutyConversation.TimeStamp,0)), 114),0,6)
			 -- else Case when LEN(replace(substring(Convert(varchar(20),TA_Tbl_OnDutyConversation.TimeStamp),13,2),' ',''))=1 then ' 0'+replace(substring(CONVERT(varchar(20),TA_Tbl_OnDutyConversation.TimeStamp),12,6),' ','')
				--	else substring(Convert(varchar(20),TA_Tbl_OnDutyConversation.Timestamp),12,6)end
				--	+' ' + substring(CONVERT(varchar(20),TA_Tbl_OnDutyConversation.TimeStamp),18,2)
				--end
			--TA_Tbl_OnDutyConversation.TimeStamp As Approved_Date
	FROM TA_Tbl_Employee 
	INNER JOIN TA_Tbl_OndutyEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_OndutyEntry.Onduty_EmployeeID 
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id  
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id  
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId
	Left join TA_Tbl_Employee E1 on E1.Employee_Id=TA_Tbl_OndutyEntry.Emp_Id
	Left join TA_Tbl_OnDutyConversation on TA_Tbl_OnDutyConversation.Emp_Id=TA_Tbl_OndutyEntry.Emp_Id and TA_Tbl_OnDutyConversation.OnDutyApplicationId=TA_Tbl_OndutyEntry.Onduty_ID	
	WHERE 
	(
		(TA_Tbl_Employee.Employee_Status = 1) 
		or 
		(
			TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)>= convert(varchar(11),TA_Tbl_OndutyEntry.Onduty_EntryDate,102)
		)
	)
	AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) AND
	(isnull(@EmployeeName,'')='' or TA_Tbl_Employee.Employee_Code_Id in(select EmployeeID from #EmployeeName))
	and(isnull(@Gender,'Both')='Both' or TA_Tbl_Employee.Gender=@Gender)
	and(isnull(@UserGroupName,'Superadmin')='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)and
	(isnull(@isReportingto,0)=0 or TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds))and
	(ISNULL(@Status,'All')='All' or @Status='' or TA_Tbl_OndutyEntry.Onduty_Status = @Status)and
	(((CONVERT(DATETIME, @fromdate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate) or 
	(CONVERT(DATETIME, @toDate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate)) or 
	(TA_Tbl_OndutyEntry.Onduty_FromDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102)) or 
	(TA_Tbl_OndutyEntry.Onduty_ToDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102))) 
	order by TA_Tbl_Employee.Employee_Code_Id,Onduty_FromDate
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOnDutyEntryForEmail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*   
Procedure Name : Proc_TA_RptOnDutyEntry    
Description : select OnDuty entry details
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : K.Gopinath
Created On : 01-Feb-2014  
Modified for BUg no.21817 on 12Aug14 by GOpinath
Proc_TA_RptOnDutyEntryForEmail '','','04/11/2022','04/11/2022','',0,0,'SuperAdmin','','','',0,0,'Both',3
*/  


CREATE PROCEDURE [dbo].[Proc_TA_RptOnDutyEntryForEmail] 
(
	@employeeName nvarchar(max),
	@employeeId nvarchar(max),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)
AS  
BEGIN	
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery = ''
	select @UserGroupName=ug.groupName from TA_Tbl_Employee e
	inner join TA_Tbl_Usergroup ug on e.UserGroup_Id=ug.groupId
	where e.Employee_Id=@EmpAutoID
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDate,@EmployeeId	
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	delete from #EmployeeIds where EmpAutoId=@EmpAutoID
	
	SELECT	distinct dbo.TA_Tbl_Employee.Employee_Code_Id as Onduty_Employee_Id,
			ISNULL(TA_Tbl_Employee.Employee_FirstName, ' ') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, ' ') AS Employee_Name,
			replace(dbo.Ta_Tbl_levelDetails.name,'&amp;','&') as name,
			TA_Tbl_Title.TitleName,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate,106),' ','-') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate, 106)
			end  AS Onduty_EntryDate, 
			TA_Tbl_Employee.Gender,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate,106),' ','-') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate, 106)
			end AS Onduty_FromDate, 
			TA_Tbl_OndutyEntry.Onduty_FromTime,
			case when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate,106),' ','-') 
				 else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate, 106)
			end AS Onduty_ToDate, 
			TA_Tbl_OndutyEntry.Onduty_ToTime,
			replace(TA_Tbl_OndutyEntry.Onduty_Reason,'&amp;','&') as Onduty_Reason,
			TA_Tbl_OndutyEntry.Onduty_Status,
			
			TA_Tbl_OndutyEntry.Onduty_ID 
	FROM TA_Tbl_Employee 
	INNER JOIN TA_Tbl_OndutyEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_OndutyEntry.Onduty_EmployeeID 
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id  
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id  
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId  	
	WHERE 
	(
		(TA_Tbl_Employee.Employee_Status = 1) 
		or 
		(
			TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)>= convert(varchar(11),TA_Tbl_OndutyEntry.Onduty_EntryDate,102)
		)
	)
	AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) AND
	(isnull(@EmployeeName,'')='' or TA_Tbl_Employee.Employee_Code_Id in(select EmployeeID from #EmployeeName))
	and(isnull(@Gender,'Both')='Both' or TA_Tbl_Employee.Gender=@Gender)
	and(isnull(@UserGroupName,'Superadmin')='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)and
	(isnull(@isReportingto,0)=0 or TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds))and
	(TA_Tbl_OndutyEntry.Onduty_Status in('Forwarded','Pending'))and
	(((CONVERT(DATETIME, @fromdate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate) or 
	(CONVERT(DATETIME, @toDate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate)) or 
	(TA_Tbl_OndutyEntry.Onduty_FromDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102)) or 
	(TA_Tbl_OndutyEntry.Onduty_ToDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102))) 
	order by TA_Tbl_Employee.Employee_Code_Id,Onduty_FromDate
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOrgSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptOrgSettings] 
AS
BEGIN
	select id,ParentID,Name from ta_tbl_leveldetails where isdeleted=0 order by parentid,Name
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOvertime_MusterRoll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author      : Manikandan.rr
-- Create date : <02-Nov-2021 10:16 am>
-- Description : <Get the Overtime and work hours details separately>
/*

exec [Proc_TA_RptOvertime_MusterRoll] @EmployeeId='2',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',@UserGroupName='SuperAdmin',@GradeLevel='0',@EmpSwipeCard='',@ParentId=0,@FromDate1='01/Apr/2020',@ToDate1='30/apr/2020',@DesignationID=0,@Gender='Both',@EmpAutoID=0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptOvertime_MusterRoll] 	
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),  
	@LevelID varchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
    @FromDate1 varchar(50),
    @ToDate1 varchar(50),
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeId varchar(max)
	DECLARE @local_EmployeeName varchar(max)
	DECLARE @local_LevelID varchar(1000)
	DECLARE @local_employeeCategory nvarchar(50)
	DECLARE @local_employeeType nvarchar(50)
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
    DECLARE @local_FromDate1 varchar(50)
    DECLARE @local_ToDate1 varchar(50)
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoID int
	
	set @local_EmployeeId=@EmployeeId
	set @local_EmployeeName=@EmployeeName
	set @local_LevelID=@LevelID
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
    set @local_FromDate1=@FromDate1
    set @local_ToDate1=@ToDate1
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoID=@EmpAutoID
		
	Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	set @Fromdate2 = @local_FromDate1
	set @Diff = datediff(d,@local_FromDate1,@local_ToDate1) + 1
	set @Count=1
	
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))	
	create table #EmployeeIds(EmpAutoId int)	
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,
		LevelId int,date datetime,
		Otmins numeric(18,1),
		TotalDays numeric(18, 1),
		Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,
		Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,
		Designation nvarchar(250) ,
		empname nvarchar(150) ,
		Father_Name nvarchar(50),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		isManualTimeEntryFH int,
		isManualTimeEntrySH int
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(150),
		FatherName nvarchar(150) ,
		Designation nvarchar(250) ,
		Employee_Code_Id nvarchar(15),
		Present numeric(18,1),
		Absent numeric(18,1),
		Leave numeric(18,1),
		Holiday numeric(18,1)default(0.0),
		TotalOT numeric(18,1),
		CountDays  numeric(18,1) default(0.0),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		F_Day1 nvarchar(100) DEFAULT '',
		F_Day2 nvarchar(100) DEFAULT '',
		F_Day3 nvarchar(100) DEFAULT '',
		F_Day4 nvarchar(100) DEFAULT '',
		F_Day5 nvarchar(100) DEFAULT '',
		F_Day6 nvarchar(100) DEFAULT '',
		F_Day7 nvarchar(100) DEFAULT '',
		F_Day8 nvarchar(100) DEFAULT '',
		F_Day9 nvarchar(100) DEFAULT '',
		F_Day10 nvarchar(100) DEFAULT '',
		F_Day11 nvarchar(100) DEFAULT '',
		F_Day12 nvarchar(100) DEFAULT '',
		F_Day13 nvarchar(100) DEFAULT '',
		F_Day14 nvarchar(100) DEFAULT '',
		F_Day15 nvarchar(100) DEFAULT '',
		F_Day16 nvarchar(100) DEFAULT '',
		F_Day17 nvarchar(100) DEFAULT '',
		F_Day18 nvarchar(100) DEFAULT '',
		F_Day19 nvarchar(100) DEFAULT '',
		F_Day20 nvarchar(100) DEFAULT '',
		F_Day21 nvarchar(100) DEFAULT '',
		F_Day22 nvarchar(100) DEFAULT '',
		F_Day23 nvarchar(100) DEFAULT '',
		F_Day24 nvarchar(100) DEFAULT '',
		F_Day25 nvarchar(100) DEFAULT '',
		F_Day26 nvarchar(100) DEFAULT '',
		F_Day27 nvarchar(100) DEFAULT '',
		F_Day28 nvarchar(100) DEFAULT '',
		F_Day29 nvarchar(100) DEFAULT '',
		F_Day30 nvarchar(100) DEFAULT '',
		F_Day31 nvarchar(100) DEFAULT '',
		isManualTimeEntryFH int,
		isManualTimeEntrySH int
	)
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		OtMins float,
		TotalDays numeric(18, 1),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		earlyoutmins varchar(20),
		LateInmins varchar(20),
		HrsWork varchar(20),
		ShiftId int,
		Shift_FirstHalf_EndTime nvarchar(20),
		Shift_SecondHalf_StartTime nvarchar(20),
		BreakOutTime varchar(10),
		BreakInTime varchar(10)
	)	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	insert into #TempHeader(id) values(1)
	if(@isReportingto > 0)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	end
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId	
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@local_GradeLevel
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate1,@local_EmployeeId,@local_DesignationID	
	
	if(@local_employeeType > 0)
	BEGIN
		INSERT INTO #EmpType exec [Proc_TA_EmpType] @local_ToDate1,@local_EmployeeId,@local_employeeType
	END
	if(@local_employeeCategory > 0)
	BEGIN
		INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate1,@local_EmployeeId,@local_employeeCategory
	END
	
	if(@local_EmployeeId is not null and @local_EmployeeId <> '')
	begin
		create table #EmployeeID(EmployeeID varchar(25))
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@local_EmployeeId)
	end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '')
	begin
		create table #EmployeeName(EmployeeID varchar(25))
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,',')
	end	
	Declare @sqlEmpLevel nvarchar(4000)		
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId '
	If Not (@local_EmployeeId = '')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id '
	End
	If Not (@local_EmployeeName = '')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id '
	End
	SET @sqlEmpLevel = @sqlEmpLevel + ' where emp.Isdeleted=0 '
	IF(@local_Gender<>'Both')
	BEGIN
		SET @sqlEmpLevel = @sqlEmpLevel + ' and emp.Gender = ''' + cast(@local_Gender as nvarchar(8)) + ''' '
	END	
	set @sqlEmpLevel=@sqlEmpLevel+' group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	execute(@sqlEmpLevel)	
	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1='insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee e
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id'	
	SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' where SwipeCardNo is not null and e.Isdeleted=0'			
	EXECUTE(@sqlTempProcessedData1)	
	
	SELECT SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee e
	inner join #TempEmployee on #TempEmployee.EmpAutoId=e.Employee_Id
	where inactivedate is not null and Employee_Status=0
	
	DECLARE @sqlTempProcessedData varchar(8000)
	SET @sqlTempProcessedData=		
	'insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''',''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,'''+cast(@local_FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102)'
	Execute(@sqlTempProcessedData)
	
	set @sqlTempProcessedData1=		
	'insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,PD.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''',''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,'''+cast(@local_FromDate1 as nvarchar(50))+''', 102) and Date <=CONVERT(DATETIME,'''+cast(@local_ToDate1 as nvarchar(50))+''', 102)
	and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)'
	Execute(@sqlTempProcessedData1)
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	Set @local_EmployeeName = isnull(@EmployeeName,'') + '%'
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery2=''
	set @sqlQuery1 =''
	set @sqlQuery ='Insert into #EmpInOutDetails 
					select	TA_Tbl_Employee.Employee_code_id,
							#EmpLevel.LevelId,
							#TempProcessedData.date, 
							#TempProcessedData.OtMins,
							#TempProcessedData.TotalDays,
							Attendance1 = '''',
							Attendance2 ='''',
							Attendance	=
										case when #TempProcessedData.HrsWork<>''00:00'' then cast(isnull(#TempProcessedData.HrsWork,'''') as nvarchar) else '''' end
										+''#''+ case when OtMins is null or OtMins='''' or OtMins=0 then ''-'' else dbo.ConvertMinsToHours(case when OtMins is null or OtMins='''' or OtMins=0 then 0 else OtMins end)end,
							#TempProcessedData.employee_code_id, 
							Replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as Designation,
							TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''') as empname, 
							ta_tbl_employee.Father_Name,
							TA_Tbl_Title.TitleId,
							TA_Tbl_Grade.Grade_Level,
							0,
							case when OtMins is null or OtMins='''' or OtMins=0 then 0 else otmins end,
							case when #TempProcessedData.HrsWork<>''00:00'' then dbo.ConvertHoursToMinites(cast(isnull(#TempProcessedData.HrsWork,0) as nvarchar)) else 0 end
							FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId
							Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id
							INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId
							INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
	if(@local_employeeCategory>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #EmpCategory TEC on TA_Tbl_Employee.Employee_Id = TEC .EmployeeId
										INNER JOIN TA_Tbl_Category c on TEC.CategoryId = c.CategoryId'
	END
	if(@local_employeeType>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN #EmpType TET on TA_Tbl_Employee.Employee_Id = TET.EmployeeId
										INNER JOIN TA_Tbl_Type T on TET.TypeId = TA_Tbl_Type.TypeId'	
	END
	set @sqlQuery1 = @sqlQuery1 + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '	
	set @sqlQuery1 = @sqlQuery1 + ' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )'  
	if(@local_UserGroupName<>'SuperAdmin')
	begin	
		SET @sqlQuery2 = @sqlQuery2 + '	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)'
	end	
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery2 = @sqlQuery2 + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
	END
	set @sqlQuery2 = @sqlQuery2 + ' order by #TempProcessedData.Employee_code_id'  
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2)
	
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails	
	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@local_FromDate1
	while(@Count <=31)
	BEGIN
		SET @SQLTemp = @SQLTemp + ' update #TempHeader set Day'+cast(@Count as varchar(10)) + '=' + cast(datepart(d,@FromDate3)as varchar(10)) + 'where id=1'
		exec(@SQLTemp)
		set @SQLTemp=''
		if(@Count <=@Diff)
		BEGIN
			SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(20)) + ' = #EmpInOutDetails.Attendance, '
			SET @SQLFN1 = @SQLFN1 + ' isManualTimeEntryFH=isnull(#AllEmpInOutDetails.isManualTimeEntryFH,0)+isnull(#EmpInOutDetails.isManualTimeEntryFH,0),'
			SET @SQLFN1 = @SQLFN1 + ' isManualTimeEntrySH =isnull(#AllEmpInOutDetails.isManualTimeEntrySH,0) +isnull(#EmpInOutDetails.isManualTimeEntrySH,0) ' 
			SET @SQLFN1 = @SQLFN1 + ' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	'
			SET @SQLFN1 = @SQLFN1 + ' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, ''' + @FromDate3 + ''' , 102) '
			EXEC(@SQLFN1)
			SET @SQLFN1=''									
			IF NOT EXISTS(SELECT DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
			BEGIN							
				SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
				EXEC(@SQLFN1)																			
			END
		END
		ELSE
		BEGIN
			SET @SQLFN1 = @SQLFN1 + ' update #AllEmpInOutDetails set F_Day'+ cast(@Count as varchar(10)) + ' = ''-'''
			EXEC(@SQLFN1)
		END
		SET @FromDate3=dateadd(d,1,@FromDate3)
		SET @Count=@Count +1
	END	 
	
	select
	ROW_NUMBER()over(order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name) SlNo,
	Employee_Code_Id,
	Name,
	Designation, 
	EF_Day1=substring(F_Day1,0,charindex('#',F_Day1)),
	EF_Day2=substring(F_Day2,0,charindex('#',F_Day2)),
	EF_Day3=substring(F_Day3,0,charindex('#',F_Day3)),
	EF_Day4=substring(F_Day4,0,charindex('#',F_Day4)),
	EF_Day5=substring(F_Day5,0,charindex('#',F_Day5)),
	EF_Day6=substring(F_Day6,0,charindex('#',F_Day6)),
	EF_Day7=substring(F_Day7,0,charindex('#',F_Day7)),
	EF_Day8=substring(F_Day8,0,charindex('#',F_Day8)),
	EF_Day9=substring(F_Day9,0,charindex('#',F_Day9)),
	EF_Day10=substring(F_Day10,0,charindex('#',F_Day10)),
	EF_Day11=substring(F_Day11,0,charindex('#',F_Day11)),
	EF_Day12=substring(F_Day12,0,charindex('#',F_Day12)),
	EF_Day13=substring(F_Day13,0,charindex('#',F_Day13)),
	EF_Day14=substring(F_Day14,0,charindex('#',F_Day14)),
	EF_Day15=substring(F_Day15,0,charindex('#',F_Day15)),
	EF_Day16=substring(F_Day16,0,charindex('#',F_Day16)),
	EF_Day17=substring(F_Day17,0,charindex('#',F_Day17)),
	EF_Day18=substring(F_Day18,0,charindex('#',F_Day18)),
	EF_Day19=substring(F_Day19,0,charindex('#',F_Day19)),
	EF_Day20=substring(F_Day20,0,charindex('#',F_Day20)),
	EF_Day21=substring(F_Day21,0,charindex('#',F_Day21)),
	EF_Day22=substring(F_Day22,0,charindex('#',F_Day22)),
	EF_Day23=substring(F_Day23,0,charindex('#',F_Day23)),
	EF_Day24=substring(F_Day24,0,charindex('#',F_Day24)),
	EF_Day25=substring(F_Day25,0,charindex('#',F_Day25)),
	EF_Day26=substring(F_Day26,0,charindex('#',F_Day26)),
	EF_Day27=substring(F_Day27,0,charindex('#',F_Day27)),
	EF_Day28=substring(F_Day28,0,charindex('#',F_Day28)),
	EF_Day29=substring(F_Day29,0,charindex('#',F_Day29)),
	EF_Day30=substring(F_Day30,0,charindex('#',F_Day30)),
	EF_Day31=substring(F_Day31,0,charindex('#',F_Day31)),
	TotalWH=dbo.ConvertMinsToHours(isManualTimeEntrySH)
	from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	
	select
	ROW_NUMBER()over(order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name) SlNo,
	Employee_Code_Id,
	Name,
	Designation,	
	EF_Day1=substring(F_Day1,charindex('#',F_Day1)+1,LEN(F_Day1)),
	EF_Day2=substring(F_Day2,charindex('#',F_Day2)+1,LEN(F_Day2)),
	EF_Day3=substring(F_Day3,charindex('#',F_Day3)+1,LEN(F_Day3)),
	EF_Day4=substring(F_Day4,charindex('#',F_Day4)+1,LEN(F_Day4)),
	EF_Day5=substring(F_Day5,charindex('#',F_Day5)+1,LEN(F_Day5)),
	EF_Day6=substring(F_Day6,charindex('#',F_Day6)+1,LEN(F_Day6)),
	EF_Day7=substring(F_Day7,charindex('#',F_Day7)+1,LEN(F_Day7)),
	EF_Day8=substring(F_Day8,charindex('#',F_Day8)+1,LEN(F_Day8)),
	EF_Day9=substring(F_Day9,charindex('#',F_Day9)+1,LEN(F_Day9)),
	EF_Day10=substring(F_Day10,charindex('#',F_Day10)+1,LEN(F_Day10)),
	EF_Day11=substring(F_Day11,charindex('#',F_Day11)+1,LEN(F_Day11)),
	EF_Day12=substring(F_Day12,charindex('#',F_Day12)+1,LEN(F_Day12)),
	EF_Day13=substring(F_Day13,charindex('#',F_Day13)+1,LEN(F_Day13)),
	EF_Day14=substring(F_Day14,charindex('#',F_Day14)+1,LEN(F_Day14)),
	EF_Day15=substring(F_Day15,charindex('#',F_Day15)+1,LEN(F_Day15)),
	EF_Day16=substring(F_Day16,charindex('#',F_Day16)+1,LEN(F_Day16)),
	EF_Day17=substring(F_Day17,charindex('#',F_Day17)+1,LEN(F_Day17)),
	EF_Day18=substring(F_Day18,charindex('#',F_Day18)+1,LEN(F_Day18)),
	EF_Day19=substring(F_Day19,charindex('#',F_Day19)+1,LEN(F_Day19)),
	EF_Day20=substring(F_Day20,charindex('#',F_Day20)+1,LEN(F_Day20)),
	EF_Day21=substring(F_Day21,charindex('#',F_Day21)+1,LEN(F_Day21)),
	EF_Day22=substring(F_Day22,charindex('#',F_Day22)+1,LEN(F_Day22)),
	EF_Day23=substring(F_Day23,charindex('#',F_Day23)+1,LEN(F_Day23)),
	EF_Day24=substring(F_Day24,charindex('#',F_Day24)+1,LEN(F_Day24)),
	EF_Day25=substring(F_Day25,charindex('#',F_Day25)+1,LEN(F_Day25)),
	EF_Day26=substring(F_Day26,charindex('#',F_Day26)+1,LEN(F_Day26)),
	EF_Day27=substring(F_Day27,charindex('#',F_Day27)+1,LEN(F_Day27)),
	EF_Day28=substring(F_Day28,charindex('#',F_Day28)+1,LEN(F_Day28)),
	EF_Day29=substring(F_Day29,charindex('#',F_Day29)+1,LEN(F_Day29)),
	EF_Day30=substring(F_Day30,charindex('#',F_Day30)+1,LEN(F_Day30)),
	EF_Day31=substring(F_Day31,charindex('#',F_Day31)+1,LEN(F_Day31)),
	TotalOT=dbo.ConvertMinsToHours(isManualTimeEntryFH)
	from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
		
	select * from #TempHeader	
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee	
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from ta_tbl_leveldetails where parentid=0
-- proc_OtCalculation '03/01/2011','03/1/2011','','','','','','','SuperAdmin','','','',323,0,'Both'
CREATE PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountDetails] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @Amount numeric(18,2),
    @EmpAutoID int
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--select * from #LevelRights
CREATE TABLE #TempProcessedData
(
	[Process_Rec_ID] bigint,
	[Employee_Code_Id] nvarchar(20),
	[Date] datetime,
	[Shift_Id] int,
	[InTime] nvarchar(25),
	[OutTime] nvarchar(25),
	[HrsWork] nvarchar(10),
	[HrsOT] nvarchar(10),
	[NormOT] nvarchar(10),
	[OffOT] nvarchar(10),
	[HolOT] nvarchar(10),
	[EarlyOut] nvarchar(10),
	[LateIn] nvarchar(10),
	[Attendance] nvarchar(20),
	[WorkHrs] nvarchar(10),
	[HrsLess] nvarchar(10),
	[HrsExtra] nvarchar(10),
	[LateInMins] float,
	[EarlyOutMins] float,
	[ExtraMins] float,
	[OtMins] float,
	[OvertimeStatus] nvarchar(50),
	[TotalDays] numeric(18, 1),
	[LeaveCode] nvarchar(20),
	[LateEntryReason] nvarchar(260),
	[EarlyOutReason] nvarchar(260),
	[ProcessFlag] bit,
	[Status] nvarchar(50),
	[FNAttendanceCode] nvarchar(15),
	[ANAttendanceCode] nvarchar(15)
)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
insert into #TempProcessedData
select PD.Process_Rec_ID,PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.InTime,PD.OutTime,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.OffOT,PD.HolOT,PD.EarlyOut,
PD.LateIn,PD.Attendance,PD.WorkHrs,PD.HrsLess,PD.HrsExtra,PD.LateInMins,PD.EarlyOutMins,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.TotalDays,
PD.LeaveCode,PD.LateEntryReason,PD.EarlyOutReason,PD.ProcessFlag,PD.Status,PD.FNAttendanceCode,PD.ANAttendanceCode
from TA_Tbl_ProcessedData as PD 
--inner join ta_tbl_employee e on e.SwipeCardNo=PD.Employee_Code_Id
--inner join #EmpLevel el on el.employeeid=e.employee_id
where
Employee_Code_Id in (
select SwipeCardNo from ta_tbl_employee e
inner join #EmpLevel el on el.employeeid=e.employee_id
) and
(PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)) and PD.OTMins<>0
--select * from #TempProcessedData where OtMins <>0
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''
	set @sqlQuery = @sqlQuery + ' select * from ('
	set @sqlQuery = @sqlQuery + 'select TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,'
	set @sqlQuery = @sqlQuery + 'ISNULL(ta_tbl_shift.Shift_ShortName,''Off'') as ShiftName, #TempProcessedData.OtMins,CASE ISNULL(NormOt,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''NormOTMins'',CASE ISNULL(OffOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''WeekOffOTMins'',CASE ISNULL(HolOT,''00:00'') WHEN ''00:00'' THEN 0 ELSE OtMins END as ''HolidayOTMins'','
	set @sqlQuery = @sqlQuery + ' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT,#TempProcessedData.OffOT,#TempProcessedData.HolOT, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'')  AS [Level Name],ISNULL(#TempProcessedData.OverTimeStatus,''Pending'') as OverTimeStatus,0 as SelectedRecords,Ta_Tbl_Employee.SwipeCardNo,replace(Ta_tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender, 0 as Amount from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo'
	set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'	 
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on  #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.employeeid=TA_Tbl_Employee.Employee_Id '
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
	--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
	--set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	--set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' where #TempProcessedData.OtMins <> 0 '
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end
	if(@shift<>0) 
	begin
		set @sqlQuery = @sqlQuery + ' And #TempProcessedData.Shift_Id=' + cast (@shift as nvarchar(50))  
	end 
	set @sqlQuery = @sqlQuery + ' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1'
	if not(@EmployeeName='')
	begin
		--set @sqlQuery = @sqlQuery + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
				set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +' and #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	If Not (@EmpSwipeCard = '')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	 End 
	if not (@empId='')
	begin
		set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
	end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end	
	 if(@Gender<>'Both')
		begin
		   set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@isReportingto > 0)
        BEGIN
         set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
        END
	if not(@status='' or @status='All')
	begin
	 	IF(@status = 'Pending')
			BEGIN
				set @sqlQuery = @sqlQuery + ' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = ''' + @status + ''')'
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + ' AND #TempProcessedData.OvertimeStatus = ''' + @status + ''''
			END
    end 
	set @sqlQuery = @sqlQuery + ' ) OverTime order by OverTime.Employee_Code_Id , OverTime.Date'
	exec (@sqlQuery)
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountSummary] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
    -- Insert statements for procedure here
	CREATE TABLE #TempDetails(SNo int,OrganizationLevel varchar(100),WeekDayOT decimal,
	WeeklyOffOT decimal,HolidayOT decimal,Amount numeric(18,2))      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)      
   VALUES(1,'EIT01',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(2,'EIT02',10,2,3,200.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(3,'EIT03',10,2,3,100.00)      
  INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)         
   VALUES(4,'EIT04',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(5,'EIT05',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)     
   VALUES(6,'EIT06',10,2,3,200.00)      
  INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)   
   VALUES(7,'EIT07',10,2,3,200.00)      
   --DECLARE @QUERY NVARCHAR(MAX)      
   --set @QUERY =''      
   SELECT * FROM #TempDetails      
   --EXEC(@QUERY)      
   --  select @QUERY       
  drop  table #TempDetails 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayroll]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.manikandan>
-- Create date: <04-Jul-2019 11:21 am>
-- Description:	<Get the payroll details as per the client given format>
-- Proc_TA_RptPayroll '2019/05/01','2019/05/30','','','SuperAdmin','0',0,0,'Both',0,0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptPayroll]
	@fromDat datetime,  
	@ToDat datetime,  
	@empId NVARCHAR(max),   
	@EmployeeName NVARCHAR(max),
	@UserGroupName NVARCHAR(250),  
	@GradeLevel NVARCHAR(20)  ,  
	@ParentId int,  
	@DesignationID int,  
	@Gender NVARCHAR(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON
	CREATE TABLE #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),
		[Employee Id] NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		[Norm OT Hrs] numeric(8,1),
		[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),
		Others numeric(8,1),
		Total_Spec_NormOT1 int,
		[Sick Leave] numeric(8,1)
	)
	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	DECLARE @isReportingto AS INT
	
	CREATE TABLE #EmployeeIds(EmpAutoId int)
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
	CREATE TABLE #EmpAttendanceDetails
	(
		EmployeeID  NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		NormalOTHrs numeric(8,1),
		WeekOffOTHrs numeric(8,1),
		HolidayOTHours numeric(8,1),
		Leave Numeric(8,1),
		Total_Spec_NormOT1 int,
		[Sick Leave] numeric(8,1)
	)
	CREATE TABLE #LevelRights(LevelId int)
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id NVARCHAR(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		Total_Spec_NormOT1 int,
		OtMins int
	)
	CREATE TABLE #TempEmployeeForProcessedData(EmpAutoId bigint,EmpSwipeCardNo NVARCHAR(20),EmployeeCodeId  NVARCHAR(50), EmployeeName nvarchar(200) ,Gender NVARCHAR(20)) 
	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
	--To split up the comma separated values
	if(@empId is not null and @empId <> '')
		begin
			create table #EmployeeID(EmployeeID NVARCHAR(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID NVARCHAR(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@empId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)	
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo=
	'insert into #TempEmployeeForProcessedData 
	select e.Employee_ID,e.SwipeCardNo, e.employee_code_id,isnull(Employee_FirstName,'''') + SPACE(1) + isnull(Employee_LastName,''''),e.Gender
	from TA_Tbl_Employee  e
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '	
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 '
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' and (e.Employee_Status = 1  or  e.Employee_Status = 0 )'
	if(@UserGroupName<>'SuperAdmin')  
		begin  
			set @sqlCommonSwipeCardNo=@sqlCommonSwipeCardNo+' AND TA_Tbl_Grade.Grade_Level >=''' + cast(@GradeLevel as nvarchar(8)) + ''' '
		end  
	if(@Gender<>'Both')  
		begin  
			set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
		end   
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	execute(@sqlCommonSwipeCardNo)	
	insert into #TempProcessedData 
	select	#TempEmployeeForProcessedData.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			case when PD.OvertimeStatus='Approved' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) end,
			PD.OtMins
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #TempEmployeeForProcessedData on #TempEmployeeForProcessedData.EmpSwipeCardNo=PD.Employee_Code_Id  
	INNER JOIN TA_Tbl_Employee E on E.SwipeCardNo=#TempEmployeeForProcessedData.EmpSwipeCardNo
	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
	WHERE (PD.date >= CONVERT(DATETIME,@fromDat, 102)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
	INSERT INTO #TempDetailedAttendance([Employee Id],[Employee Name]) 
	SELECT DISTINCT EmployeeCodeId,EmployeeName FROM #TempEmployeeForProcessedData	
	
	INSERT INTO #EmpAttendanceDetails 
	SELECT TPD.Employee_code_Id,  
			Present= 
			sum
			(
				CASE	WHEN FNAttendanceCode='Present'	 AND ANAttendanceCode='Present'	THEN 1.0
						WHEN FNAttendanceCode='Holiday'  AND  ANAttendanceCode='Holiday'	THEN 1.0
						WHEN FNAttendanceCode='Present'  AND  ANAttendanceCode!='Present' THEN 0.5
						WHEN FNAttendanceCode!='Present' AND  ANAttendanceCode='Present' THEN 0.5
						WHEN FNAttendanceCode='Comp Off' AND  ANAttendanceCode='Comp Off'THEN 1.0
						WHEN FNAttendanceCode='BL' AND  ANAttendanceCode='BL'			THEN 1.0
						ELSE 0.0
				END
			),
			Absent=
			sum
			(
				CASE	WHEN FNAttendanceCode='Absent'	AND  ANAttendanceCode='Absent'	THEN 1.0 
						WHEN FNAttendanceCode='Absent'	AND  ANAttendanceCode!='Absent'	THEN 0.5
						WHEN FNAttendanceCode!='Absent' AND  ANAttendanceCode='Absent'	THEN 0.5
						WHEN FNAttendanceCode IS NULL AND  ANAttendanceCode IS NULL		THEN 1 
						ELSE 0.0
				END
			), 
			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,'00:00')='00:00'	THEN 0 ELSE OtMins END),
			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,'00:00')='00:00'	THEN 0 ELSE OtMins END), 
			'Leave'=SUM(CASE WHEN FNAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END) + 
					SUM(CASE WHEN ANAttendanceCode not in('Absent','Present','Holiday','Weekly Off') THEN 0.5 else 0 END), 
			isnull(SUM(TPD.Total_Spec_NormOT1),0),
			sum
			(
				CASE	WHEN FNAttendanceCode='SL'	 AND ANAttendanceCode='SL'	THEN 1.0
						WHEN FNAttendanceCode='SL'  AND  ANAttendanceCode!='SL' THEN 0.5
						WHEN FNAttendanceCode!='SL' AND  ANAttendanceCode='SL' THEN 0.5
						ELSE 0.0
				END
			)			
			from #TempProcessedData  TPD
			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
			Inner join #TempDetailedAttendance TDA on TDA.[Employee Id]=TPD.Employee_Code_Id			
			group by TPD.Employee_Code_ID
			
				
	update #TempDetailedAttendance set Present = TEAD.Present,
	Absent = TEAD.Absent,  
	[Norm OT Hrs]		= TEAD.NormalOTHrs,
	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
	Total_Spec_NormOT1	=TEAD.Total_Spec_NormOT1,
	[Sick Leave]=TEAD.[Sick Leave]
	from #EmpAttendanceDetails TEAD 
	inner join #TempDetailedAttendance on TEAD.EmployeeID=#TempDetailedAttendance.[Employee Id]
	
	--Inserts the Others details in the temporary table  
	--declare @SqlOthers NVARCHAR(4000)  
	--create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
	--Insert into #Others 
	--select Employee_Code_Id ,	
	--sum
	--(
	--	CASE	WHEN (FNAttendanceCode='RH' or FNAttendanceCode='LOP') THEN 0.5
	--			ELSE 0 
	--	END
	--)+ 
	--sum
	--( 
	--	CASE WHEN (ANAttendanceCode='RH' or ANAttendanceCode='LOP') THEN 0.5
	--		 ELSE 0 
	--	END
	--)
	--from #TempProcessedData where Employee_Code_Id in(select [Employee Id] from #TempDetailedAttendance)
	--group by Employee_Code_ID
	
	--Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
	
	--INSERT INTO #tempLeaveTypeforOthers 
	--SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
	--LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
	--WHERE TLT.Leavetype is null
	
	select 	
		[Employee Id],
		--[Employee Name],		
		Present=isnull(Present,0),
		[Sick Leave]=isnull([Sick Leave],0),
		--Absent=ISNULL(Absent,0),		
		[Daytime OT Hours]=dbo.ConvertMinsToHours([Norm OT Hrs]),
		[Nighttime OT Hours]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
		[Holiday OT Hours]=dbo.ConvertMinsToHours([WeekOff OT Hrs]+[Holiday OT Hrs]),		
		'' Remarks
	from #TempDetailedAttendance	
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpAttendanceDetails  
	--drop table #Others  
	--drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployeeForProcessedData  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayrollgrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth S>
-- Create date: <Create Date,,17-Dec-2022>
-- Description:	<Description,,Payroll Grid Report>
-- =============================================

/*	
Select * From TA_Tbl_ProcessedData

 Proc_TA_RptPayrollgrid @EmployeeId='E015',@EmployeeName='',@LevelID='10',@employeeCategory=N'0',@employeeType=N'0',
 @UserGroupName='superadmin',@GradeLevel='0',@EmpSwipeCard='',@ParentId=0,@Fromdate1='2023/02/01',@Todate1='2023/02/28',@DesignationID=0,@Gender='Both',@EmpAutoID=0

*/

--Select * From TA_T

CREATE PROCEDURE [dbo].[Proc_TA_RptPayrollgrid]
	-- Add the parameters for the stored procedure here
	@EmployeeId NVARCHAR(50),
	@EmployeeName NVARCHAR(50),
	@LevelID NVARCHAR(1000),
	@employeeCategory NVARCHAR(50),
	@employeeType NVARCHAR(50),
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20),
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50),
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@EmpAutoID INT
AS
BEGIN
SET NOCOUNT ON;
	--Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	
	DECLARE @Basic_DA bigint
	set @Basic_DA = 1
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,companyId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		EmployeeAutoId int,Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20),Gender varchar(20),Company_Id int,CTC bigint,BasicSalary bigint,DA bigint,HRA nvarchar(20),CA nvarchar(20),MA nvarchar(20),CEA nvarchar(20),Tax nvarchar(20),
		PFESI int,WD int
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(500),FatherName NVARCHAR(500),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),Present NUMERIC(18,1),EmployeeAutoID int,
		Absent NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20),Gender nvarchar(20),CTC bigint,BasicSalary bigint,DA bigint,HRA bigint,CA bigint,MA bigint,CEA bigint,TDS_BasicExcemptionLimit bigint,Tds_PolicyId int, Tds_deductionAmount bigint,
		PF bigint,ESI bigint,LoanCount int,LoanDueAmount bigint,TDSAmount bigint,Professional_Tax bigint, TotalAdditions bigint, TotalDeduction bigint, EarnedAmount bigint
	)

	Declare @DAClaculation as Table(Employee_ID varchar(20),DA_Value bigint)

	--Assign Variable into some values
	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=@Fromdate1,@loca_Todate1=@Todate1,@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
    IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN
		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	
	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
    INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
    --For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel  SELECT Elevel.EmployeeId,EL.levelId,(Select [dbo].[Func_TA_GetParentIds](EL.LevelId)),Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 




	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0
    
	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)
	
	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	

	Select * from TA_Tbl_Employee


	INSERT INTO #EmpInOutDetails 
	SELECT  E.Employee_Id,E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar,
			E.Gender as Gender,
		    Company_Id=el.companyId, 
			E.Emp_Ctc,
			E.Basic_Salary,
			E.DA,
			E.HRA,
			E.CA,
			E.MedicalAlllowance,
			E.CEDAllowance,
			E.Tax_Policy,
			E.PF_Policy,
			null
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	INNER JOIN #EmpLevel el on el.SwipeCard=TPD.Employee_Code_Id 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))



    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    

    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	--Salary Based on the Present Days Calculation

	Declare @BasicSalaryTbl as Table (EmpId int,TotalDays int,DaySalary bigint,CurrentMonthSalary bigint)
	Declare @TmpBasicSalary as Table (Emp_Id int,dailywages bigint)

	Declare @CalanderDays int

	--Select @CalanderDays=Co From #EmpInOutDetails

	Insert into @BasicSalaryTbl (EmpId,TotalDays)
	Select EmployeeAutoId,Sum(TotalDays) From #EmpInOutDetails where AttendanceFN!='Off' and AttendanceAN!='off' and AttendanceAN!='**o' and AttendanceFN!='**o' group by EmployeeAutoId 

	

	Update @BasicSalaryTbl set DaySalary=Ed.BasicSalary/bs.TotalDays From @BasicSalaryTbl bs inner Join #EmpInOutDetails ED on ED.EmployeeAutoId =bs.EmpId 

	insert into @TmpBasicSalary
    Select EmpId,(PD*DaySalary)From @BasicSalaryTbl inner Join #EmpInOutDetails on EmployeeAutoId=EmpId 
	
	Declare @FinalBs as Table (Emp Int,CS bigint)
	insert into @FinalBs
	Select Emp_Id,Sum(dailywages) From @TmpBasicSalary group By Emp_Id



	Update @BasicSalaryTbl set CurrentMonthSalary= CS From @BasicSalaryTbl Inner Join @FinalBs  on Emp = EmpId

	--Insert into @BasicSalary Select Employee_Code_id,() From #EmpInOutDetails ED inner
	
	--Select * From @BasicSalaryTbl

	Update #EmpInOutDetails set BasicSalary=CurrentMonthSalary From @BasicSalaryTbl inner Join #EmpInOutDetails on EmployeeAutoId =EmpId

	Insert Into @DAClaculation Select Employee_code_id,(Ed.BasicSalary * pc.D_Allowance)/100   From #EmpInOutDetails ED Inner join TA_Tbl_PayrollConfigSetting pc on  pc.companyId=ED.Company_Id 

	INSERT INTO #AllEmpInOutDetails 
	(Employee_Code_Id,EmployeeAutoID,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar,Gender,CTC,BasicSalary,EarnedAmount,DA,HRA,CA,MA,CEA,TDS_BasicExcemptionLimit,Tds_PolicyId,PF,ESI,TDSAmount,Professional_Tax,LoanDueAmount)
	SELECT DISTINCT ED.Employee_code_id,EmployeeAutoId,empname,Designation,ED.Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar,ED.Gender,ED.CTC,Emp.Basic_Salary,BasicSalary,DA.DA_Value,
	Case when ED.BasicSalary!=0 then (Case when ED.HRA=1 then ((ED.BasicSalary+DA.DA_Value) * pc.HRA_Metro)/100 Else ((ED.BasicSalary+DA.DA_Value) * pc.HRA_NonMetro )/100 End) Else 0 End, 
	Case when ED.BasicSalary!=0 then (Case when CA.Con_Type='Percentage'then ((ED.BasicSalary+DA.DA_Value) * CA.conPercentage)/100 Else CA.conAmount End) Else 0 End,
	Case when ED.BasicSalary!=0 then (Case when pc.isMedicalflag=1 then pc.MedicalAmount Else ((ED.BasicSalary+DA.DA_Value) * pc.MedicalPercent)/100 END) Else 0 End,
	Case when ED.BasicSalary!=0 then (Case when pc.isCEAflag=1 then pc.CEAAmount Else ((ED.BasicSalary+DA.DA_Value) * pc.CEAPercentage)/100 END) Else 0 End,
	pc.LessTaxDeduction,ED.Tax,
	Case when ED.BasicSalary!=0 then (Case when PE.PF_Employer!=0 then ((ED.BasicSalary+DA.DA_Value) * PE.PF_Employer)/100 + ((ED.BasicSalary+DA.DA_Value)*PE.PF_Employee)/100 Else ((ED.BasicSalary+DA.DA_Value) *PE.PF_Employee)/100 End) Else 0 End as pF,
	Case when ED.BasicSalary!=0 then (Case when PE.PF_Employer!=0 then ((ED.BasicSalary+DA.DA_Value) *PE.ESI_Employer)/100 + ((ED.BasicSalary+DA.DA_Value)*PE.ESI_Employee)/100 Else ((ED.BasicSalary+DA.DA_Value) * Convert(bigint,PE.ESI_Employee))/100 End) Else 0 End as ESI,
	[dbo].[Func_TA_TaxCalculate](ED.Employee_Code_Id,ED.Tax,Emp.Basic_Salary),[dbo].[Func_TA_ProfessionalTaxCalculate](ED.Employee_code_id,ED.Tax,ED.BasicSalary),0
	FROM #EmpInOutDetails ED Left Join TA_Tbl_PayrollConfigSetting pc on pc.companyId=ED.Company_Id
	Left Join TA_Tbl_ConveyanceAllowance CA on CA.C_Id=ED.CA
	Left Join TA_Tbl_PF_ESIDetails PE on ED.PFESI=PE.PFESI_Id 
	Left Join @DAClaculation DA on DA.Employee_ID=ED.Employee_code_id
	Left Join @BasicSalaryTbl bs on bs.EmpId=Ed.EmployeeAutoId
	Left Join TA_Tbl_Employee Emp on emp.Employee_Id=ED.EmployeeAutoId
	

	-- Loan Amount Update -- 
	Declare @CurrentDate varchar(20)

	Set @CurrentDate=(SELECT LEFT(DATENAME(MONTH,@Fromdate1),3) + '/' + RIGHT('00' + CAST(YEAR(@Fromdate1) AS VARCHAR),4))

	Declare @LoanTable Table (id int identity(1,1),EmployeeCode varchar(20),DueAmount bigint,LoansCount int )

	Insert into @LoanTable 
	Select Employee_Code_Id,Sum(Monthly_DeductAmount),COUNT(Employee_Code_Id) From #AllEmpInOutDetails  Left Join TA_Tbl_LoanEntryDetails on Employee_Id=EmployeeAutoID

	Where EmployeeAutoID=Employee_Id and ISLoanClose=0 and  isdeleted=0 and Deduction_StartMonth>=@CurrentDate Group By Employee_Code_Id 

	Update #AllEmpInOutDetails set LoanDueAmount=DueAmount,LoanCount=LoansCount From #AllEmpInOutDetails inner Join @LoanTable on EmployeeCode=Employee_Code_Id 



	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance

	UPDATE #AllEmpInOutDetails set PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1, PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	
	
	-- Total Addititons and deduction total calculation -- 

	Update #AllEmpInOutDetails set TotalAdditions=(IsNull(EarnedAmount,0) + IsNull(DA,0) + IsNull(HRA,0) + IsNull(CA,0) + Isnull(MA,0) + IsNull(CEA,0)),TotalDeduction=(IsNull(PF,0) + Isnull(ESI,0) + IsNull(TDSAmount,0) + IsNull(Professional_Tax,0) + ISNull(LoanDueAmount,0))  From #AllEmpInOutDetails 

	SELECT	Employee_Code_Id,
			Name as EmployeeName,
			Designation,			
			Gender,
			TOTD as Calender_Days,
			PD as Present_Days,
			AD as Absent_Days,
			LD as Leave_Days,
			WOD as Weekly_OFF_Days,
			HD as Holiday_Days,
			LOPD as LossofPay_Days,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			CTC as CostToCompany,
			BasicSalary,
			EarnedAmount,
			DA as Dearness_Allowance,
			HRA as HouseRent_Allowance,
			CA as Conveyance_Allowance,
			MA as Medical_Allowance,
			CEA as Children_Education_Allowance,
			Tds_PolicyId,
			PF as ProvidentFund,
			ESI,LoanCount,LoanDueAmount,
		    TDSAmount,Professional_Tax,TotalAdditions,TotalDeduction,
			Case when EarnedAmount=0 OR (TotalAdditions-TotalDeduction)<0 then 0 Else (TotalAdditions-TotalDeduction) End as NetSalary,0 As OA
	FROM #AllEmpInOutDetails A ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),Name


	Declare @FilterMonth nvarchar(20)
	Declare @FilterYear nvarchar(20)
	set @FilterYear=(Select Year(@Fromdate1))

	set @FilterMonth= (SELECT DATENAME(MONTH,@Fromdate1)) 

	Select ps.EmployeeName,ps.Employee_Code_Id,ps.Designation,ps.Gender,ps.PayslipMonth,ps.Calender_Days,ps.Present_Days,ps.Absent_Days,ps.Leave_Days,ps.Weekly_OFF_Days,ps.Holiday_Days,ps.LossofPay_Days,ps.TotalOTHrs,ps.CostToCompany,ps.BasicSalary,ps.EarnedAmount,ps.Dearness_Allowance,ps.HouseRent_Allowance,ps.Conveyance_Allowance,ps.Medical_Allowance,ps.Children_Education_Allowance,
	ps.Tds_PolicyId,ps.ProvidentFund,ps.ESI,ps.LoanCount,ps.LoanDueAmount,ps.TDSAmount,ps.Professional_Tax,ps.TotalAdditions,ps.TotalDeduction,ps.NetSalary,ps.OA,ps.PayslipYear From #AllEmpInOutDetails AE inner Join TA_Tbl_PaySlip ps on ps.Employee_Code_Id=AE.Employee_Code_Id where ps.PayslipMonth=@FilterMonth and ps.PayslipYear=@FilterYear
	
	-- Select * From TA_Tbl_PaySlip

	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayrollgrid_back20221219]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth S>
-- Create date: <Create Date,,17-Dec-2022>
-- Description:	<Description,,Payroll Grid Report>
-- =============================================
/*	
Select * From TA_Tbl_Employee

 Proc_TA_RptPayrollgrid @EmployeeId='',@EmployeeName='',@LevelID='0,1',@employeeCategory=N'0',@employeeType=N'0',
 @UserGroupName='superadmin',@GradeLevel='1',@EmpSwipeCard='',@ParentId=0,@Fromdate1='2022/11/01',@Todate1='2022/11/30',@DesignationID=0,@Gender='Both',@EmpAutoID=1

*/

Create PROCEDURE [dbo].[Proc_TA_RptPayrollgrid_back20221219]
	-- Add the parameters for the stored procedure here
	@EmployeeId NVARCHAR(50),
	@EmployeeName NVARCHAR(50),  
	@LevelID NVARCHAR(1000), 	 
	@employeeCategory NVARCHAR(50),
	@employeeType NVARCHAR(50)	,
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20)	,
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@Fromdate1 NVARCHAR(50),
    @Todate1 NVARCHAR(50),
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@EmpAutoID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Creating Variables AND Temporary Tables for calculation
	DECLARE @loca_EmployeeId NVARCHAR(50)
	DECLARE @loca_EmployeeName NVARCHAR(50)
	DECLARE @loca_LevelID NVARCHAR(1000)
	DECLARE @loca_employeeCategory NVARCHAR(50)
	DECLARE @loca_employeeType NVARCHAR(50)
	DECLARE @loca_UserGroupName NVARCHAR(250)
	DECLARE @loca_GradeLevel NVARCHAR(20)
	DECLARE @loca_EmpSwipeCard NVARCHAR(20)
	DECLARE @loca_ParentId INT
	DECLARE @loca_Fromdate1 NVARCHAR(50)
    DECLARE @loca_Todate1 NVARCHAR(50)
	DECLARE @loca_DesignationID INT
	DECLARE @loca_Gender NVARCHAR(10)
	DECLARE @loca_EmpAutoID INT
	DECLARE @Fromdate2 DATETIME
	DECLARE @Count INT
	DECLARE @Diff INT
	DECLARE @isReportingto INT	

	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))	
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempHeader(id INT,Day1 INT,Day2 INT,Day3 INT,Day4 INT,Day5 INT,Day6 INT,Day7 INT,Day8 INT,Day9 INT,Day10 INT,Day11 INT,Day12 INT,Day13 INT,Day14 INT,Day15 INT,Day16 INT,Day17 INT,Day18 INT,Day19 INT,Day20 INT,Day21 INT,Day22 INT,Day23 INT,Day24 INT,Day25 INT,Day26 INT,Day27 INT,Day28 INT,Day29 INT,Day30 INT,Day31 INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))	
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime NVARCHAR(25),OutTime NVARCHAR(25),Attendance NVARCHAR(20),fnattendanceCode NVARCHAR(20),
		anattendanceCode NVARCHAR(20),Shift_Id INT,LevelId bigint,OtMins float,TotalDays NUMERIC(18,1),earlyoutmins float,LateInmins float,HrsWork NVARCHAR(10),ShiftId INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20),NightOrMorn INT,InNotation char(1),OutNotation char(1)
	)	
	CREATE TABLE #EmpInOutDetails
	(
		Employee_code_id NVARCHAR(15),LevelId INT,date DATETIME,Otmins NUMERIC(18,1),TotalDays NUMERIC(18, 1),
		AttendanceFN NVARCHAR(25),AttendanceAN NVARCHAR(25),employee_code_id1 NVARCHAR(15),Designation NVARCHAR(250),empname NVARCHAR(150),
		Father_Name NVARCHAR(50),DesignationId INT,Grade_Level INT,OrderBy INT,Shift_FirstHalf_StartTime NVARCHAR(20),Shift_FirstHalf_EndTime NVARCHAR(20),Shift_SecondHalf_StartTime NVARCHAR(20),Shift_SecondHalf_EndTime NVARCHAR(20)
		,NightOrMorn INT,InNotation char(1),OutNotation char(1)	,
		PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20),PresentDays Numeric(18,1),AbsentDays Numeric(18,1)
	)
	CREATE TABLE #AllEmpInOutDetails
	(
		Name NVARCHAR(50),FatherName NVARCHAR(50),Designation NVARCHAR(250),Employee_Code_Id NVARCHAR(15),PresentDays NUMERIC(18,1),
		AbsentDays NUMERIC(18,1),Leave NVARCHAR(10) DEFAULT(0),Holiday NUMERIC(18,1),TotalOT NUMERIC(18,1),DesignationID INT,Grade_Level INT,OrderBy INT,CLAvailed decimal(18,2) DEFAULT(0),
		F_Day1 NVARCHAR(100) DEFAULT '-',F_Day2 NVARCHAR(100) DEFAULT '-',F_Day3 NVARCHAR(100) DEFAULT '-',F_Day4 NVARCHAR(100) DEFAULT '-',F_Day5 NVARCHAR(100) DEFAULT '-',F_Day6 NVARCHAR(100) DEFAULT '-',F_Day7 NVARCHAR(100) DEFAULT '-',F_Day8 NVARCHAR(100) DEFAULT '-',F_Day9 NVARCHAR(100) DEFAULT '-',F_Day10 NVARCHAR(100) DEFAULT '-',F_Day11 NVARCHAR(100) DEFAULT '-',F_Day12 NVARCHAR(100) DEFAULT '-',F_Day13 NVARCHAR(100) DEFAULT '-',F_Day14 NVARCHAR(100) DEFAULT '-',F_Day15 NVARCHAR(100) DEFAULT '-',F_Day16 NVARCHAR(100) DEFAULT '-',F_Day17 NVARCHAR(100) DEFAULT '-',F_Day18 NVARCHAR(100) DEFAULT '-',F_Day19 NVARCHAR(100) DEFAULT '-',F_Day20 NVARCHAR(100) DEFAULT '-',F_Day21 NVARCHAR(100) DEFAULT '-',F_Day22 NVARCHAR(100) DEFAULT '-',F_Day23 NVARCHAR(100) DEFAULT '-',F_Day24 NVARCHAR(100) DEFAULT '-',F_Day25 NVARCHAR(100) DEFAULT '-',F_Day26 NVARCHAR(100) DEFAULT '-',F_Day27 NVARCHAR(100) DEFAULT '-',F_Day28 NVARCHAR(100) DEFAULT '-',F_Day29 NVARCHAR(100) DEFAULT '-',F_Day30 NVARCHAR(100) DEFAULT '-',F_Day31 NVARCHAR(100) DEFAULT '-',
	    A_Day1 NVARCHAR(100) DEFAULT '-',A_Day2 NVARCHAR(100) DEFAULT '-',A_Day3 NVARCHAR(100) DEFAULT '-',A_Day4 NVARCHAR(100) DEFAULT '-',A_Day5 NVARCHAR(100) DEFAULT '-',A_Day6 NVARCHAR(100) DEFAULT '-',A_Day7 NVARCHAR(100) DEFAULT '-',A_Day8 NVARCHAR(100) DEFAULT '-',A_Day9 NVARCHAR(100) DEFAULT '-',A_Day10 NVARCHAR(100) DEFAULT '-',A_Day11 NVARCHAR(100) DEFAULT '-',A_Day12 NVARCHAR(100) DEFAULT '-',A_Day13 NVARCHAR(100) DEFAULT '-',A_Day14 NVARCHAR(100) DEFAULT '-',A_Day15 NVARCHAR(100) DEFAULT '-',A_Day16 NVARCHAR(100) DEFAULT '-',A_Day17 NVARCHAR(100) DEFAULT '-',A_Day18 NVARCHAR(100) DEFAULT '-',A_Day19 NVARCHAR(100) DEFAULT '-',A_Day20 NVARCHAR(100) DEFAULT '-',A_Day21 NVARCHAR(100) DEFAULT '-',A_Day22 NVARCHAR(100) DEFAULT '-',A_Day23 NVARCHAR(100) DEFAULT '-',A_Day24 NVARCHAR(100) DEFAULT '-',A_Day25 NVARCHAR(100) DEFAULT '-',A_Day26 NVARCHAR(100) DEFAULT '-',A_Day27 NVARCHAR(100) DEFAULT '-',A_Day28 NVARCHAR(100) DEFAULT '-',A_Day29 NVARCHAR(100) DEFAULT '-',A_Day30 NVARCHAR(100) DEFAULT '-',A_Day31 NVARCHAR(100) DEFAULT '-',	
	    PD DECIMAL(18,1) DEFAULT(0),AD DECIMAL(18,1) DEFAULT(0),WOD DECIMAL(18,1) DEFAULT(0),HD DECIMAL(18,1) DEFAULT(0),LD DECIMAL(18,1) DEFAULT(0),LOPD DECIMAL(18,1) DEFAULT(0),TOTD INT DEFAULT(0),
		Aadhar varchar(20)  
	)

	--CREATE TABLE #AllAttendanceDetails(
	--	Employee_ID int,PresentDay int,AbsentDay int
	--)

	-- Assign Variable into Local values

	

	SELECT @loca_EmployeeId=@EmployeeId,@loca_EmployeeName=@EmployeeName,@loca_LevelID=@LevelID,@loca_employeeCategory=@employeeCategory
	,@loca_employeeType=@employeeType,@loca_UserGroupName=@UserGroupName,@loca_GradeLevel=@GradeLevel,@loca_EmpSwipeCard=@EmpSwipeCard,
	@loca_ParentId=@ParentId,@loca_Fromdate1=@Fromdate1,@loca_Todate1=@Todate1,@loca_DesignationID=@DesignationID,@loca_Gender=@Gender,
	@loca_EmpAutoID=@EmpAutoID,@Fromdate2 = @loca_Fromdate1,@Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1,@Count=1
	
	SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@loca_UserGroupName
	
	IF(@loca_EmployeeId IS  NOT NULL AND @loca_EmployeeId!='')
    BEGIN

		INSERT INTO #EmployeeID	  SELECT * FROM SplitupEmployeeCode(@loca_EmployeeId)	

	END
	IF(@loca_EmployeeName IS NOT NULL AND @loca_EmployeeName!='')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] FROM dbo.[SplitUpEmployeeName](@loca_EmployeeName,',')
	END
	INSERT INTO	#EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    INSERT INTO #EmployeeIds  SELECT reportingEmpID FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	
	--For updating headers, inserted dummy value
	INSERT INTO #TempHeader(id) VALUES(1)
	INSERT INTO #LevelRights  SELECT ParentChildId FROM [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	INSERT INTO #EmpLevel     SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  FROM 
	(
		SELECT MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo FROM TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID EID on EID.EmployeeID=emp.Employee_Code_Id
		LEFT OUTER JOIN #EmployeeName EName on EName.EmployeeID=emp.Employee_Code_Id
		WHERE SwipeCardNo IS NOT NULL AND emp.Isdeleted=0
		AND (CAST (@loca_Gender as NVARCHAR(8)) = 'Both' or emp.Gender = CAST (@loca_Gender as NVARCHAR(8)))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate AND EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST (@loca_Todate1 as NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL 


	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation EXEC Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 	
	INSERT INTO #EmpType EXEC[Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	INSERT INTO #EmpCategory EXEC[Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	SELECT SwipeCardNo,inActiveDate into #InActiveEmployees FROM ta_tbl_employee WHERE inactivedate IS NOT NULL AND Employee_Status=0

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id 
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	INNER JOIN #InActiveEmployees IA on (EL.SwipeCard=IA.SwipeCardNo AND pd.Date<=IA.inactivedate)
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)

	INSERT INTO #TempProcessedData
	SELECT EL.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,
	pd.Shift_Id,'',pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,
	S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #EmpLevel EL on EL.SwipeCard=PD.Employee_Code_Id
	INNER JOIN #EmpCategory EC on EC.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpType ET on ET.EmployeeId=EL.EmployeeId
	INNER JOIN #EmpDesignation ED on ED.EmployeeId=EL.EmployeeId
	Left Outer JOIN TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id
	WHERE (PD.Date >=@loca_Fromdate1 AND PD.Date <= @loca_Todate1)
	AND EL.SwipeCard not in(SELECT DISTINCT swipecardno FROM #InActiveEmployees)


	UPDATE #TempProcessedData SET NightOrMorn= CASE WHEN SUBSTRING(S.Shift_StartTime,7,8)!='PM' AND SUBSTRING(S.Shift_Endtime,7,8)!='AM' then 0 
													ELSE 1 END 
	FROM #TempProcessedData PD INNER JOIN TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	INSERT INTO #EmpInOutDetails 
	SELECT	E.Employee_code_id,
			'',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	
			CASE	WHEN TPD.FNAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(FNAttendanceCode) + ''
					WHEN TPD.FNAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.FNAttendanceCode='Present'		THEN CASE	WHEN (TPD.LateInmins <> '0' )					THEN '*P'  ELSE 'P'	  END
					WHEN TPD.FNAttendanceCode='Weekly Off'	THEN CASE	WHEN (InTime IS NOT NULL  AND Intime<> '00:00')	THEN '**o' ELSE 'Off' END
					WHEN TPD.FNAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**H' ELSE 'H'	  END
					WHEN TPD.FNAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')		THEN '**R' ELSE 'RH'  END
					WHEN TPD.FNAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.FNAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.FNAttendanceCode='EL'			THEN 'EL'
			END,
			AttendanceAN = 
			CASE	WHEN TPD.ANAttendanceCode NOT IN('Absent','Present','Weekly Off','Comp Off','Holiday','RH','CL','EL') then '' + lower(ANAttendanceCode) + ''
					WHEN TPD.ANAttendanceCode='Absent'		THEN 'A'
					WHEN TPD.ANAttendanceCode='Present'		THEN CASE	WHEN (TPD.earlyoutmins <> '0' )				  THEN '*P'		ELSE 'P'	END
					WHEN TPD.ANAttendanceCode='Weekly Off'	THEN CASE	WHEN (Outtime IS NOT NULL  AND Outtime<> '00:00')THEN '**o'	ELSE 'Off'	END
					WHEN TPD.ANAttendanceCode='Holiday'		THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**H'	ELSE 'H'	END
					WHEN TPD.ANAttendanceCode='RH'			THEN CASE	WHEN (Intime<> '00:00' or OutTime<>'00:00')   THEN '**R'	ELSE 'RH'	END
					WHEN TPD.ANAttendanceCode='Comp Off'	THEN 'CO'
					WHEN TPD.ANAttendanceCode='CL'			THEN 'CL'
					WHEN TPD.ANAttendanceCode='EL'			THEN 'EL'
			END,
			TPD.employee_code_id, 
			REPLACE(T.TitleName,'&amp;','&') as Designation,
			E.Employee_FirstName + SPACE(1) + ISNULL(E.Employee_MiddleName,'') + SPACE(1) + ISNULL(E.employee_lastname,''), 
			E.Father_Name,
			T.TitleId,
			G.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation,
			CASE WHEN TPD.fnattendanceCode='Present'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Present'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Absent'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Absent'	THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Weekly Off' THEN 0.5 ELSE 0 END,			
			CASE WHEN TPD.fnattendanceCode='Holiday'	THEN 0.5 WHEN TPD.fnattendanceCode='RH'	THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='Holiday' THEN 0.5 WHEN TPD.anattendanceCode='RH' THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode NOT IN('Absent','Present','Weekly Off','Holiday','RH','LOP') THEN 0.5 ELSE 0 END,
			CASE WHEN TPD.fnattendanceCode='LOP'		THEN 0.5 ELSE 0 END + CASE WHEN TPD.anattendanceCode='LOP' THEN 0.5 ELSE 0 END,
			0,
			E.CustomField1 as Aadhar,
			PresentDays=0,AbsentDays=0
	FROM  #TempProcessedData TPD  
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id  
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId  
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID 
	WHERE (E.Isdeleted=0 AND E.report_exclude=0)
	AND (ISNULL(@isReportingto,0) = 0 or E.Employee_ID IN (SELECT * FROM #EmployeeIds))

	-- Update Present & Absent Days Count

	Select emp.Employee_Code_Id,SUM(CASE WHEN result.Attendance = 'Present' THEN 1 ELSE 0 END) as PresentDays,SUM(CASE WHEN result.Attendance = 'Absent' THEN 1 ELSE 0 END)as AbsentDays into #AllAttendanceDetails from TA_Tbl_Employee emp left join TA_Tbl_ProcessedData result on emp.Employee_Code_Id = result.Employee_Code_Id where result.Shift_Id!=-1 and result.Date<=@loca_Todate1 and result.Date>=@loca_Fromdate1 group by emp.Employee_Code_Id
	

    Update #EmpInOutDetails Set PresentDays=At.PresentDays,AbsentDays=At.AbsentDays From #EmpInOutDetails empData Inner join #AllAttendanceDetails At  on At.Employee_Code_Id=empData.Employee_Code_Id

	---Updating OD Notation 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  'FN', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, 'AN', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ManualTimeEntry MD ON (IOD.Employee_code_id=MD.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	AND (MD.ManualTimeEntry_InDate>=@loca_Fromdate1 AND MD.ManualTimeEntry_OutDate<=@loca_Todate1)
	AND MD.IsOnDuty=1 AND MD.Isdeleted=0
    
    UPDATE #EmpInOutDetails SET AttendanceFN= CASE	WHEN I.AttendanceFN = 'A' THEN I.AttendanceFN
													WHEN (I.AttendanceFN ='P' OR I.AttendanceFN ='*P' OR I.AttendanceFN ='H' OR I.AttendanceFN ='**H' OR I.AttendanceFN ='Off' OR I.AttendanceFN ='**O') AND InNotation='M' then AttendanceFN+'#' 
													ELSE AttendanceFN 
											  END,
	AttendanceAN= CASE	WHEN  I.AttendanceAN = 'A' THEN I.AttendanceAN
						WHEN (I.AttendanceAN='P' OR I.AttendanceAN='*P' OR I.AttendanceAN='H' OR I.AttendanceAN='**H' OR I.AttendanceAN='Off' OR I.AttendanceAN='**O') AND OutNotation='M' then AttendanceAN+'#' else AttendanceAN END
	FROM #EmpInOutDetails I WHERE (InNotation='M' or OutNotation='M')
	
	INSERT INTO #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy,Aadhar,PresentDays,AbsentDays)
	SELECT DISTINCT Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy,Aadhar,PresentDays,AbsentDays FROM #EmpInOutDetails 
	
	DECLARE @LeaveTypeID INT
	SELECT @LeaveTypeID =LeaveType_Id FROM TA_tbl_LeaveType WHERE LeaveType='CL'
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'')
	begin
		create TABLE #LeaveCount(Employee_code_Id NVARCHAR(15),LeaveCount NUMERIC(18,1),LeaveCountFraction NVARCHAR(10))
		
		INSERT INTO #LeaveCount 
		SELECT e.employee_code_id,ISNULL(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'' as LeaveCountFraction 
		FROM ta_tbl_leaveapplication la INNER JOIN ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		WHERE ((la.Leave_FromDate between @loca_Fromdate1 AND @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 AND @loca_Todate1))
		AND la.Status = 'Approved' AND la.LeaveType_Id=@LeaveTypeID AND la.IsDeleted=0 	
		group by e.employee_code_id
		
		UPDATE #LeaveCount SET LeaveCountFraction=ISNULL(LeaveCount,0)- Floor(ISNULL(LeaveCount,0))	
		UPDATE #LeaveCount SET LeaveCountFraction=ltrim(CAST ((case CAST (Floor(LeaveCount) as NVARCHAR(10)) WHEN '0' then '' else CAST (Floor(LeaveCount) as NVARCHAR(10)) END) as NVARCHAR(10)) + ' ' +
				case LeaveCountFraction WHEN '0.5' then '1/2' else ''END )	
		UPDATE #AllEmpInOutDetails SET Leave =ISNULL(#LeaveCount.LeaveCountFraction,0) FROM #LeaveCount
		INNER JOIN #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	END
	--select @loca_Fromdate1,@loca_Todate1
	--Calculating Total Days of each attendance
	UPDATE #AllEmpInOutDetails set  PD=a.PD,AD=a.AD,WOD=a.WOD,HD=a.HD,LD=a.LD,LOPD=a.LOPD,TOTD=a.TOTD,TotalOT=a.TotalOT FROM #AllEmpInOutDetails INNER JOIN
	(
		select employee_code_id1,PD=SUM(isnull(ED.PD,0)),AD=SUM(isnull(ED.AD,0)),WOD=SUM(isnull(ED.WOD,0)),HD=SUM(isnull(ED.HD,0)),LD=SUM(isnull(ED.LD,0)),LOPD=SUM(isnull(ED.LOPD,0)),
		TOTD=DATEDIFF(d,@loca_Fromdate1,DATEADD(d,1,@loca_Todate1)),
		TotalOT=SUM(Otmins)
		from #EmpInOutDetails ED group by employee_code_id1
	)a on a.employee_code_id1=#AllEmpInOutDetails.Employee_Code_Id
	

	Select * From #AllEmpInOutDetails

	SET @Count=1
	DECLARE @SQLUS NVARCHAR(max)
	DECLARE @SQLHeader NVARCHAR(max)
	WHILE(@Count <=31)
	BEGIN
		--Creating Table Header
		SET @SQLHeader=''
		SET @SQLUS=''
		SET @SQLHeader = @SQLHeader + ' UPDATE #TempHeader SET Day'+CAST(@Count as NVARCHAR(10)) + '=' + CAST (datepart(d,@loca_Fromdate1)as NVARCHAR(10)) + 'WHERE id=1'	
		EXEC(@SQLHeader)
		--Updating data of particular date.
		IF(@Count <=@Diff)
		BEGIN			
			SET @SQLUS = @SQLUS + ' UPDATE AD SET F_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceFN,A_Day'+ CAST (@Count as NVARCHAR(10)) + ' = ED.AttendanceAN'
			SET @SQLUS = @SQLUS + ' FROM  #EmpInOutDetails ED INNER JOIN #AllEmpInOutDetails AD on AD.Employee_code_id=	ED.Employee_code_id AND ED.date =   CONVERT(DATETIME, ''' + @loca_Fromdate1 + ''' , 102)'
			EXEC(@SQLUS)
		END		
		SET @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
		SET @Count=@Count +1
	END
    --for CLAvailed 
	UPDATE #AllEmpInOutDetails SET  CLAvailed= ISNULL(A.LeaveAvailed,'0.0')
	FROM #AllEmpInOutDetails TDA INNER JOIN 
	(
			SELECT (sum(CASE fnattendanceCode WHEN 'CL' THEN 0.5 Else 0 END) + sum(CASE anattendanceCode WHEN 'CL' THEN 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			FROM TA_tbl_ProcessedData pd INNER JOIN TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner JOIN #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			WHERE (Date between TA_tbl_YearSetting.FromDate AND @loca_Todate1) AND (FNAttendanceCode='CL' or ANAttendanceCode='CL')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--- if the value is less than 0, update the value as 0
	UPDATE #AllEmpInOutDetails SET CLAvailed=0.0 WHERE ISNULL(CLAvailed,0)<0
	UPDATE #AllEmpInOutDetails SET PD=0.0 WHERE ISNULL(PD,0)<0
	UPDATE #AllEmpInOutDetails SET AD=0.0 WHERE ISNULL(AD,0)<0
	UPDATE #AllEmpInOutDetails SET WOD=0.0 WHERE ISNULL(WOD,0)<0
	UPDATE #AllEmpInOutDetails SET HD=0.0 WHERE ISNULL(HD,0)<0
	UPDATE #AllEmpInOutDetails SET LD=0.0 WHERE ISNULL(LD,0)<0
	UPDATE #AllEmpInOutDetails SET LOPD=0.0 WHERE ISNULL(LOPD,0)<0	
	
	SELECT	Employee_Code_Id,
			Name,
			Designation,			
			CLAvailed,
			FatherName,
			TOTD,
			PresentDays,
			AbsentDays,
			Leave,		
			Holiday,
			TotalOT,
			DesignationID,
			Grade_Level,
			OrderBy,
			PD,
			AD,
			WOD,
			HD,
			LD,
			LOPD,
			TotalOTHrs=dbo.ConvertMinsToHours(TotalOT),
			
			Aadhar	
	FROM #AllEmpInOutDetails A ORDER BY A.Grade_Level,CAST(ISNULL(A.Orderby,100000)as INT),Name
	
	--SELECT * FROM #TempHeader
	
	DROP TABLE #employeeid
	DROP TABLE #employeename
	DROP TABLE #empcategory
	DROP TABLE #emptype
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpInOutDetails
	DROP TABLE #AllEmpInOutDetails
	DROP TABLE #TempProcessedData
	DROP TABLE #AllAttendanceDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  Senthil  
-- Create date: 21-Apr-08  
-- Description: payslip Report  
-- Proc_TA_RptPayslip '24','151','',0,0,'0,1,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120','SuperAdmin','0'  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip]  
 @MonthClosureID as nvarchar(5),  
 @EmployeeId nvarchar(100),   
 @EmployeeName nvarchar(50),  
 @EmpCategory int,  
 @EmpType int,  
 @LevelID nvarchar(1000),
 @UserGroupName varchar(250),
 @GradeLevel varchar(20)			    
AS  
BEGIN  
 Declare @ToDate as DateTime  
 set @ToDate = (select MonthClosure_EndDate from ta_tbl_monthclosure where MonthClosure_ID=@MonthClosureID)  
 declare @sqlQuery as varchar(8000) 
 declare @sqlQuery1 as varchar(8000)
 set @sqlQuery=''
 set @sqlQuery1=''
 set @sqlQuery = 'select TA_Tbl_Title.TitleName,TA_Tbl_PayrollProcessDetails.PayrollProcess_Id, TA_Tbl_PayrollProcessDetails.MonthClosure_Id, TA_Tbl_MonthClosure.MonthClosure_Month, TA_Tbl_MonthClosure.MonthClosure_Year, Ta_Tbl_Employee.Employee_Code_ID,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as EmployeeName,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_levelDetails.name, TA_Tbl_PayrollProcessDetails.DA, '   
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.MonthlyWages,TA_Tbl_PayrollProcessDetails.WorkingDays,'  
 --set @sqlQuery = @sqlQuery + ' cast((TA_Tbl_PayrollProcessDetails.MonthlyWages/TA_Tbl_PayrollProcessDetails.WorkingDays)* (isnull(TA_Tbl_PayrollProcessDetails.PresentDays,0) + isnull(TA_Tbl_PayrollProcessDetails.PaidHolidays,0)) as int) as EmpWages,TA_Tbl_PayrollProcessDetails.WorkingDays,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.AbsentDays, TA_Tbl_PayrollProcessDetails.PaidHolidays, '  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.PresentDays as WorkedDays, TA_Tbl_PayrollProcessDetails.Wages,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,'  
    --set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.NormOT as OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.Incentive,TA_Tbl_PayrollProcessDetails.GrossWages,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.PF, TA_Tbl_PayrollProcessDetails.ESI,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.Mess,TA_Tbl_PayrollProcessDetails.OtherDeductions,'  
 set @sqlQuery = @sqlQuery + ' isnull(TA_Tbl_PayrollProcessDetails.Mess,0) + isnull(TA_Tbl_PayrollProcessDetails.OtherDeductions,0) + isnull(TA_Tbl_PayrollProcessDetails.PF,0) + isnull(TA_Tbl_PayrollProcessDetails.ESI,0) as TotalDeduction,'  
 set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.NetWages,'  
 set @sqlQuery = @sqlQuery + ' RoundUp = Case (Cast(TA_Tbl_PayrollProcessDetails.NetWages as int)%10) when 0 Then TA_Tbl_PayrollProcessDetails.NetWages Else (TA_Tbl_PayrollProcessDetails.NetWages + (10 - (Cast (TA_Tbl_PayrollProcessDetails.NetWages as int) %10))) End'  
 set @sqlQuery = @sqlQuery + ' from Ta_Tbl_employee inner join ta_tbl_payrollprocessDetails on Ta_Tbl_Employee.SwipeCardNo=ta_tbl_payrollprocessDetails.Employee_ID'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_MonthClosure on ta_tbl_payrollprocessDetails.MonthClosure_ID = TA_Tbl_MonthClosure.MonthClosure_Id'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
 set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
 set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
 set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
--    set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_levelDetails on Ta_Tbl_Employee.LevelID = TA_Tbl_levelDetails.id'  
--  
-- set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '  
-- set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'  
-- --set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '  
-- --set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'  
 set @sqlQuery = @sqlQuery + ' where (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) and (TA_Tbl_Employee.Employee_Code_Id<>''18000000'')'  
    set @sqlQuery = @sqlQuery + ' And (ta_tbl_payrollprocessDetails.MonthClosure_ID=' + @MonthClosureID + ')'  
set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(getdate() as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
 set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(getdate() as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
 set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(getdate() as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
 set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(getdate() as nvarchar(50))  + ''', 102) order by EffectiveDate desc)' 
-- set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and  EffectiveDate <=CONVERT(DATETIME,''' + cast(@Todate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'  
if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		end
if not(@EmpCategory='' or @EmpCategory='0')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + 'and TA_Tbl_Employee.EmpCategory =''' + @EmpCategory + ''' '  
 end  
 if not(@EmpType='' or @EmpType='0')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + 'and TA_Tbl_Employee.EmpType =''' + @EmpType + ''' '  
 end  
 if not(@EmployeeName='' or @EmployeeName='0')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + 'and TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''' '  
 end   
 if not (@EmployeeId='' or @EmployeeId='0')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '  
 end
 if not (@LevelID='' or @LevelID='0')  
 begin     
  set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeLevel.LevelId IN (' + @LevelId + ')' 
 end
 exec(@sqlQuery + @sqlQuery1)   
END  
 set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_General]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author        : R.Manikandan
-- Create date   : 29-June-2015
-- Modified date :  
-- Description   : <Description,,>  
-- exec [Proc_TA_RptPayslip_General] '01/Dec/2015','31/Dec/2015','877','','0','SuperAdmin','0','',0,0,'Both',0,0,0
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip_General]
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(100),   
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
    @ParentId int,  
    @DesignationID int,  
	@Gender varchar(10),
	@employeeCategory int,  
	@employeeType int,
	@EmpAutoId BIGINT
)  
AS  
BEGIN
	SET NOCOUNT ON ;
	Declare @FromDateOld datetime
	Declare @ToDateOld datetime
	--set @FromDateOld='01/July/2015'
	--set @ToDateOld='31/July/2015'
	Declare @Difference int
	Declare @datepart int
	Declare @M int
	Set @M=0
	declare @month char(2)
	Declare @start varchar(20)
	declare @enddate varchar(20)
	select @Difference=DATEDIFF(d,@fromDat,@ToDat)/2
	while @M>=0
	begin
		select @datepart= DATEPART(d,DATEADD(d,@M,@fromDat))	
		if(@Difference=@datepart)
			begin
			set @month= DATEPART(MONTH,DATEADD(d,@M,@fromDat))
			set @month=	case	when LEN(@month)=1 then '0'+CONVERT(char(2),@month)
								else CONVERT(char(2),@month)
						end
			set @start=convert(varchar(20),DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-01'
			if(@month in(1,3,5,7,8,10,12))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-31'
				end
			else if(@month in(4,6,9,11))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-30'
				end
			else
				begin
					if(DATEPART(YEAR,@fromDat)/4=0)
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-29'
						end
					else
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-28'
						end
				end
			set @M=-2
		end
		set @M=@M+1
	end
	set @FromDateOld=CONVERT(datetime,@start+' 00:00:00.000')
	set @ToDateOld=CONVERT(datetime,@enddate+' 00:00:00.000')
	--select @FromDateOld,@ToDateOld
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '', @Query VARCHAR(MAX), @I INT = 1;
	declare @DeviationColumns VARCHAR(MAX) = '';
	declare @DeviationColumnsDisplay VARCHAR(MAX) = '';
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlCommon nvarchar(max)	
	Declare @sqlEmpDesi nvarchar(max)
	Declare @sqlTempProcessedData varchar(max)	
	Declare @sqlCommonSwipeCardNo nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)	
	Declare @sqlEmpCategory nvarchar(max)
	Declare @sqlEmpType nvarchar(max)	
	set @sqlCommon=''
	--Creates the tepmoraray tables.
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200) ,  
		[EmployeeId] varchar(50),  	
		Present numeric(8,1),
		LeaveDays numeric(8,1),
		LopDays numeric(8,1),
		LateEntryNoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		sat_WorkHrs decimal(18,1),
		MonToSat_WorkHrs decimal(18,1),
		LessHoursWorked numeric(8,1),
		LateInMins int,
		TotalHrsEnteredInArmis numeric(8,1),
		TotalDefinedWorkHrs numeric(8,1),
		DaysNeedToDeduct_Late decimal(18,2) default(0.0),
		DaysNeedToDeduct_Armis decimal(18,2) default(0.0),
		DaysNeedToDeduct_Working decimal(18,2) default(0.0),
		TotalMinutesWorked int
	)	 	
    create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20),sat_WorkHrs decimal(18,1),MonToSat_WorkHrs decimal(18,1))
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  	
	create table #EmpGrade(Grade_Id int) 
    create table #EmpAttendanceDetails
    (	EmployeeID  varchar(50),
		Present numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateInMins numeric(8,1),		
		LopDays numeric(8,1),
		LeaveDays numeric(8,1),
		NoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		TotalDefinedWorkHrsInMins int default(0),
		weeknumber int,
		TotalMinutesWorked int
	)      
    create table #TempProcessedData
    (
		Employee_Code_Id varchar(20),
		NumberOfPresentDays decimal(18,1),
		LateInMins int,
		TotalLeaveDays decimal(18,1),
		OtherLeaveDays decimal(18,1),
		OverAllDeviations varchar(20),
		NumberofDaysWorked as (NumberOfPresentDays+TotalLeaveDays-OtherLeaveDays),
		DeviationHoursFormat_Week1 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week2 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week3 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week4 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week5 varchar(30) default('TC:00:00 A:00:00')
	)   		
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID);
	--INSERT INTO @TempExecptionHrs
	--	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	--	WHERE [Date] BETWEEN @fromDat AND @ToDat
	--GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @fromDat, @ToDat)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @fromDat) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @fromDat)) != 'Sunday' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT	@WeekName = 'Week' + CAST(@I AS VARCHAR(10)),
			@DeviationColumns=@DeviationColumns+'+convert(int,isnull(DeviationHours_' + @WeekName+',0))', 
			@DeviationColumnsDisplay=@DeviationColumnsDisplay+',DeviationHoursFormat_' + @WeekName ,
			@TableColumns = @TableColumns + ', TargetWorkHours_' + @WeekName + ' VARCHAR(10), ActualWorkHours_' + @WeekName + ' VARCHAR(10), ArmisWorkHours_' + @WeekName + ' VARCHAR(10), [Leave_Permision_' + @WeekName + '] VARCHAR(10), 
	DeviationHours_' + @WeekName + ' VARCHAR(30),DeviationHoursFormat_'+@WeekName+' varchar(30)default(''TC:00:00 A:00:00'')',@I = @I + 1 FROM WeekName
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]([Grade_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[EmployeeId],[LevelId] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[EmployeeId],[DesignationId] ASC)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[EmployeeId],[CategoryId])ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[EmployeeId],[TypeId]) ON [PRIMARY]  
	--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
	SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
	INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDat AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
	SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
	SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
	INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
	INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType 
	SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
	SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
	INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
	INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
	AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
	SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
	SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
	INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102)
	GROUP BY EmployeeId) EmpCategory
	INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
	AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
	INSERT INTO #EmpPay
	SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
	SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
	INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
	AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FinalAttendanceSummary')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC('CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50),Sat_WorkHrs	numeric(18,1)' + @TableColumns + ')')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = 'Week' + CAST(@I AS VARCHAR(10))		
		SELECT 
		@fromDat = Tbl1.WeekDates,
		@ToDat = Tbl2.WeekDates FROM (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
		INNER JOIN (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
		WHERE Tbl1.Id = @I				
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10),WeekDay_WorkHrs decimal(18,1))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int,
		Sat_WorkHrs	numeric(18,1)
		)
		--Commented for local database
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
		SET @SQLQuery = 'SELECT * FROM 
		[ProjectManagementV3July16].[dbo].[Fn_GetProgressReport](''' + CAST(@fromDat AS VARCHAR(20)) + ''',''' + CAST(@ToDat AS VARCHAR(20)) + '''' + (CASE WHEN @empId = '' OR @empId IS NULL THEN ', NULL)' ELSE ', ' + @empId + ')' END)
		--Commented for local database
		INSERT INTO @ArmisTable
		EXEC(@SQLQuery)			
		--select * from @ArmisTable
		SET @SQLQuery = 'SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END,'
		SET @SQLQuery = @SQLQuery + ' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''') +  SPACE(1) + ISNULL(E.Employee_LastName, '''') + ''$'' + REPLACE(LD.Name, ''&amp;'', ''&''), REPLACE(LD.Name, ''&amp;'', ''&''),'
		SET @SQLQuery = @SQLQuery + ' REPLACE(T.TitleName, ''&amp;'', ''&''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''-''), ISNULL(PD.OutTime, ''-''),'
		SET @SQLQuery = @SQLQuery + ' ISNULL(PD.HrsWork, ''-''), ((SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 4, 2))),'
		SET @SQLQuery = @SQLQuery + ' (S.Shift_ShortName + '' ('' + S.Shift_StartTime + '' - ''  + S.Shift_EndTime + '')''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''-''),'
		SET @SQLQuery = @SQLQuery + ' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' (CASE WHEN (ISNULL(PD.BreakIn, '''') = '''' OR ISNULL(PD.BreakOut, '''') = '''') AND PD.BreakHours <> ''00:00'' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')),ISNULL(SS.MaxWorkPlaceInHours, ''00:10''), NULL
		,C.WeekDay_WorkHrs*60.0 FROM Ta_Tbl_Employee E'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id'    
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId'   
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId '
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId '
		set @SQLQuery = @SQLQuery + ' where 
		(
			(e.Employee_Status = 1) 
			or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102))
		) 	
		AND (e.Isdeleted = 0) AND (e.report_exclude = 0)'
		SET @SQLQuery = @SQLQuery + ' AND ((PD.date >= CONVERT(DATETIME, ''' + CAST(@fromDat AS NVARCHAR(11)) + ''', 102) 
		AND PD.Date <= CONVERT(DATETIME, ''' + CAST(@ToDat AS NVARCHAR(11)) + ''', 102)))'
		IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel + ''
		END
		IF NOT(@EmployeeName = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_FirstName + '' '' + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName +'%' AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@empId='')  
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_Code_Id = ''' + CAST(@empId AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmpSwipeCard = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND E.SwipeCardNo = ''' + @EmpSwipeCard + ''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		If (@Gender <> 'Both')  
		Begin  
			Set @SQLQuery = @SQLQuery + ' And E.Gender = ''' + @Gender + ''' '  
		End
		SET @SQLQuery = @SQLQuery + ' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)'   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		--select * from #TempAttendanceDetails 
		--UPDATE #TempAttendanceDetails SET
		--HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		--TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		--FROM #TempAttendanceDetails AD
		--RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDat) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
		WHERE #TempAttendanceDetails.Day = 'Saturday' AND #TempAttendanceDetails.Date = @ThirdSat
		INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.CategoryName,
			TA.DefinedWorkHours,
			TA.DefinedWorkHours - SUM(
		(((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
		ELSE 
		0.0
		END
		) * 8,
		SUM(CAST(TA.TotalMinsWorked AS INT)),
		0,
		SUM(
		(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
		WHEN C.Sat_WorkHrs = 2 THEN 
		(CASE 
		WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
		WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
		0.0 END)
		ELSE 
		(CASE
		WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
		WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
		0.0 END
		)
		END
		) * 8,
		0,
		CAST(MAX(TA.[Date]) AS DATE),
		0,0
		FROM #TempAttendanceDetails TA
		INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != 'Sunday'
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
		UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
		UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
		--Commented for local database
		UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
		INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id		
		UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
		--select 
		--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
		CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
		(ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
						(
							substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX('.',convert(varchar(10),ArmisWorkHours)))*60
							+
							substring(convert(varchar(10),ArmisWorkHours),CHARINDEX('.',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
							+ 
							[Leave_Permision] *60
							+ 
							(DefinedWorkHours - TargetWorkHours)*60
						)
					)
		ELSE 0 
		END,
		Sat_WorkHrs=C.Sat_WorkHrs
		FROM #TempAttendanceSummary TAS
		INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
		INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId where E.Isdeleted = 0 AND E.report_exclude = 0
--select * from #TempAttendanceSummary 
		SELECT	@WeekName AS WeekName,
				Employee_Code_Id,
				EmployeeName,
				CategoryName,
				REPLACE((TargetWorkHours - [Leave_Permision]), '.', ':') AS TargetWorkHours,
				CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + ':' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
				REPLACE(ArmisWorkHours, '.', ':') AS ArmisWorkHours,
				REPLACE([Leave_Permision], '.', ':') AS [Leave_Permision],
				case	when DeviationHours>ArmisDeviationHrs then	DeviationHours																
						when ArmisDeviationHrs>DeviationHours then	ArmisDeviationHrs
						when ArmisDeviationHrs=DeviationHours then	DeviationHours
				end AS DeviationHours,
				--DeviationHours AS DeviationHours,
				Sat_WorkHrs,				
			'TC:'+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN '0' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			'A:'+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN '0' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END as DeviationHoursInFormat
		INTO #TempFinalResult FROM #TempAttendanceSummary WHERE (DeviationHours != 0 or ArmisDeviationHrs != 0 OR 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = 'UPDATE FinalAttendanceSummary SET 
		Employee_Code_Id	= TR.Employee_Code_Id,
		EmployeeName		= TR.EmployeeName,
		CategoryName		= TR.CategoryName,
		TargetWorkHours_' + @WeekName + ' = TR.TargetWorkHours,
		ActualWorkHours_' + @WeekName + ' = TR.ActualWorkHours,
		ArmisWorkHours_' + @WeekName + ' = TR.ArmisWorkHours,
		[Leave_Permision_' + @WeekName + '] = TR.[Leave_Permision],
		DeviationHours_' + @WeekName + ' = isnull(TR.DeviationHours,0),
		Sat_WorkHrs=TR.Sat_WorkHrs,
		DeviationHoursFormat_' + @WeekName + ' = TR.DeviationHoursInFormat
		 FROM FinalAttendanceSummary FAS
		INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName'
		EXEC(@SQLQuery)
		SET @SQLQuery = '
		INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName,
		Sat_WorkHrs,TargetWorkHours_' + @WeekName + ', ActualWorkHours_' + @WeekName + ', ArmisWorkHours_' + @WeekName + ', 
		[Leave_Permision_' + @WeekName + '], DeviationHours_' + @WeekName + ', DeviationHoursFormat_' + @WeekName +')
		SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName,TR.Sat_WorkHrs,TR.TargetWorkHours, TR.ActualWorkHours, 
		TR.ArmisWorkHours, TR.[Leave_Permision],isnull(TR.DeviationHours,0),TR.DeviationHoursInFormat FROM #TempFinalResult TR
		LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
		WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL'
		EXEC(@SQLQuery)
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		--Commented for local database
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	--select * from FinalAttendanceSummary
	--Getting 3rd saturday date.
	Create table #Temp(date datetime,day varchar(max),id int)
	;with cte(Date,id,week) as 
	(	
		select @FromDateOld,1 as id,DATEPART(WEEK,@FromDateOld)
		union all
		select Date+1,id+1,DATEPART(WEEK,Date+1) from cte where Date < @ToDateOld
	)
	insert into #Temp select Date,DATENAME(W,Date)Day,id from cte
	option (MAXRECURSION 0)
	Declare @ThirdSaturday datetime	
	select @ThirdSaturday=date from(select *,ROW_NUMBER()over(order by id)as row from #Temp where day='Saturday')as a where row=3
	set	@DeviationColumnsDisplay=SUBSTRING(@DeviationColumnsDisplay,2,len(@DeviationColumnsDisplay))
	--select @DeviationColumns
	--select @DeviationColumnsDisplay
	--declare @alter varchar(max)
	--set @alter='alter table #TempProcessedData add '+replace(@DeviationColumnsDisplay,',',' varchar(20),')+' varchar(20)'
	--Execute(@alter)
	set @sqlTempProcessedData1=  
	'insert into #TempProcessedData
	(Employee_Code_Id,NumberOfPresentDays,LateInMins,TotalLeaveDays,OtherLeaveDays,OverAllDeviations,'+@DeviationColumnsDisplay+')
	select	Employee_Code_Id	=	PD.Employee_Code_Id,
	NumberOfPresentDays	=	sum(CASE when PD.DATE= ''' +CONVERT(varchar(20),@ThirdSaturday) + ''' 
	and Sat_WorkHrs=2 and DATENAME(W,Date)=''Saturday'' then 
	case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
			when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
	end
	 when Sat_WorkHrs=0 and DATENAME(W,Date)=''Saturday'' then 
	 case	when FNAttendanceCode=''Present''	 and ANAttendanceCode=''Present''	 then 0.5
			when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Present''    and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Present''    then 0.5
	  end
	when Sat_WorkHrs>0 and DATENAME(W,Date)=''Saturday'' then
		case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
		end
	WHEN (FNAttendanceCode=''Present'') THEN 0.5
	else 0.0
	END)+
	sum(CASE when PD.DATE= ''' +CONVERT(varchar(20),@ThirdSaturday) + ''' and Sat_WorkHrs=2 and DATENAME(W,Date)=''Saturday'' 
	then case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
		when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
	end
		when Sat_WorkHrs=0 and DATENAME(W,Date)=''Saturday'' then case	when FNAttendanceCode=''Present''	 
		and ANAttendanceCode=''Present''	 then 0.5
		when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Present''    and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Present''    then 0.5
   end		
		when Sat_WorkHrs>0 and DATENAME(W,Date)=''Saturday'' then
		case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
		end
		WHEN (ANAttendanceCode=''Present'') THEN 0.5
		else 0.0
   END),							
		LateInMins			=	sum(isnull(LateInMins,0)),
		TotalLeaveDays		=  sum(CASE WHEN FNAttendanceCode=''CL''		THEN 0.5
										WHEN FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN 1
										WHEN FNAttendanceCode=''LOP''		THEN 0.5
										WHEN FNAttendanceCode=''Absent''	THEN 0.5
										WHEN FNAttendanceCode=''SL''		THEN 0.5
										WHEN FNAttendanceCode=''CompOff''	THEN 0.5
										else 0 
										END
										)+
								sum(CASE	WHEN ANAttendanceCode=''CL''		THEN 0.5
											WHEN ANAttendanceCode=''LOP'' and FNAttendanceCode=''Weekly Off'' THEN 1
											WHEN ANAttendanceCode=''LOP''		THEN 0.5											
											WHEN ANAttendanceCode=''Absent''	THEN 0.5
											WHEN ANAttendanceCode=''SL''		THEN 0.5
											WHEN ANAttendanceCode=''CompOff''	THEN 0.5
											else 0 
									END
									),
		OtherLeaveDays		=	sum(CASE	WHEN FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN 1
											WHEN FNAttendanceCode=''LOP''		THEN 0.5
											WHEN FNAttendanceCode=''Absent''	THEN 0.5
											else 0 
									END
									) + 
								sum(CASE	WHEN ANAttendanceCode=''LOP'' and FNAttendanceCode=''Weekly Off'' THEN 1
											WHEN ANAttendanceCode=''LOP''		THEN 0.5
											WHEN ANAttendanceCode=''Absent''	THEN 0.5
											else 0 
									END
									),
			OverAllDeviations	=	convert(int,'+@DeviationColumns+'),
			'+@DeviationColumnsDisplay+'
	from TA_Tbl_ProcessedData PD 
	inner join FinalAttendanceSummary as fat on fat.Employee_Code_Id=PD.Employee_Code_Id
    where ((PD.date >= CONVERT(DATETIME,'''+cast( @FromDateOld as nvarchar(50))+''', 102))
	AND (PD.date <= CONVERT(DATETIME,'''+cast(@ToDateOld as nvarchar(50))+''', 102)))'
	If Not (@empId = '')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' And PD.Employee_Code_Id = ''' + @empId + ''' '  
		End
	Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' group by PD.Employee_Code_Id,'+@DeviationColumnsDisplay+','+@DeviationColumns
	execute(@sqlTempProcessedData1)
	--select @FromDateOld,@ToDateOld
	--select * from TA_Tbl_ProcessedData PD where Employee_Code_Id='787'
	--and ((PD.date >= CONVERT(DATETIME,cast( @FromDateOld as nvarchar(50)), 102))
	--AND (PD.date <= CONVERT(DATETIME,cast(@ToDateOld as nvarchar(50)), 102)))
	select	PD.Employee_Code_Id,
			FS.EmployeeName,
			--Fs.CategoryName,
			NumberOfPresentDays,
			TotalLeaveDays,
			OtherLeaveDays,			
			(
				select	case	when OverAllDeviations =0 then 0
								when OverAllDeviations	between  starttime1		and		EndTime1	then Day1
								when OverAllDeviations	between  StartTime2		and		EndTime2	then Day2
								when OverAllDeviations	between  StartTime3		and		EndTime3	then Day3
								when OverAllDeviations	between  StartTime4		and		EndTime4	then Day4
								when OverAllDeviations	between  StartTime5		and		EndTime5	then Day5
								when OverAllDeviations	between  StartTime6		and		EndTime6	then Day6
								when OverAllDeviations	between  StartTime7		and		EndTime7	then Day7
								when OverAllDeviations	between  StartTime8		and		EndTime8	then Day8
								when OverAllDeviations	between  StartTime9		and		EndTime9	then Day9
								when OverAllDeviations	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Workhrs
			)+
			(
				select	case	when LateInMins =0 then 0
								when LateInMins	between  starttime1		and		EndTime1	then Day1
								when LateInMins	between  StartTime2		and		EndTime2	then Day2
								when LateInMins	between  StartTime3		and		EndTime3	then Day3
								when LateInMins	between  StartTime4		and		EndTime4	then Day4
								when LateInMins	between  StartTime5		and		EndTime5	then Day5
								when LateInMins	between  StartTime6		and		EndTime6	then Day6
								when LateInMins	between  StartTime7		and		EndTime7	then Day7
								when LateInMins	between  StartTime8		and		EndTime8	then Day8
								when LateInMins	between  StartTime9		and		EndTime9	then Day9
								when LateInMins	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Lateentry
			)AS Deviations_DeductionDays,NumberofDaysWorked,			
			CASE WHEN LEN(CAST((OverAllDeviations/60) AS VARCHAR(25)))=1 THEN '0' + CAST((OverAllDeviations/60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((OverAllDeviations%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((OverAllDeviations%60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations%60) AS VARCHAR(25)) 
			END as OverAllDeviationsHrs,
			OverAllDeviations,LateInMins as TotalLateInMins,
			CASE WHEN LEN(CAST((LateInMins/60) AS VARCHAR(25)))=1 THEN '0' + CAST((LateInMins/60) AS VARCHAR(25)) 
				 ELSE CAST((LateInMins/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((LateInMins%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((LateInMins%60) AS VARCHAR(25)) 
				 ELSE CAST((LateInMins%60) AS VARCHAR(25)) 
			END as TotalLateHrs,
			'W1:'+
			pd.DeviationHoursFormat_Week1+'#W2:'+pd.DeviationHoursFormat_Week2+'#W3:'+pd.DeviationHoursFormat_Week3
			+'#W4:'+pd.DeviationHoursFormat_Week4+'#W5:'+pd.DeviationHoursFormat_Week5+'#Tot:'+
			CASE WHEN LEN(CAST((OverAllDeviations/60) AS VARCHAR(25)))=1 THEN '0' + CAST((OverAllDeviations/60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((OverAllDeviations%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((OverAllDeviations%60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations%60) AS VARCHAR(25)) 
			END as DeviationPerWeek
	from #TempProcessedData PD
	inner join FinalAttendanceSummary FS on PD.Employee_Code_Id=FS.Employee_Code_Id
	order by convert(int,pd.Employee_Code_Id)
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	DROP TABLE #EmployeeIds
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #EmpPay		
	DROP TABLE FinalAttendanceSummary
END   
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_GeneralExport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author        : R.Manikandan
-- Create date   : 29-June-2015
-- Modified date :  
-- Description   : <Description,,>  
-- exec [Proc_TA_RptPayslip_GeneralExport] '28/Sep/2015','31/Oct/2015','','','107','SuperAdmin','0','',0,0,'Male',0,0,0
-- exec [Proc_TA_RptPayslip_GeneralExport] '01/Dec/2015','31/Dec/2015','877','','0','SuperAdmin','0','',0,0,'Both',0,0,0
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip_GeneralExport]
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(100),   
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
    @ParentId int,  
    @DesignationID int,  
	@Gender varchar(10),
	@employeeCategory int,  
	@employeeType int,
	@EmpAutoId BIGINT
)  
AS  
BEGIN
	SET NOCOUNT ON ;
	Declare @FromDateOld datetime
	Declare @ToDateOld datetime
	--set @FromDateOld='01/July/2015'
	--set @ToDateOld='31/July/2015'
	Declare @Difference int
	Declare @datepart int
	Declare @M int
	Set @M=0
	declare @month char(2)
	Declare @start varchar(20)
	declare @enddate varchar(20)
	select @Difference=DATEDIFF(d,@fromDat,@ToDat)/2
	while @M>=0
	begin
		select @datepart= DATEPART(d,DATEADD(d,@M,@fromDat))	
		if(@Difference=@datepart)
			begin
			set @month= DATEPART(MONTH,DATEADD(d,@M,@fromDat))
			set @month=	case	when LEN(@month)=1 then '0'+CONVERT(char(2),@month)
								else CONVERT(char(2),@month)
						end
			set @start=convert(varchar(20),DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-01'
			if(@month in(1,3,5,7,8,10,12))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-31'
				end
			else if(@month in(4,6,9,11))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-30'
				end
			else
				begin
					if(DATEPART(YEAR,@fromDat)/4=0)
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-29'
						end
					else
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+'-'+CONVERT(varchar(20),@month)+'-28'
						end
				end
			set @M=-2
		end
		set @M=@M+1
	end
	set @FromDateOld=CONVERT(datetime,@start+' 00:00:00.000')
	set @ToDateOld=CONVERT(datetime,@enddate+' 00:00:00.000')
	--select @FromDateOld,@ToDateOld
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '', @Query VARCHAR(MAX), @I INT = 1;
	declare @DeviationColumns VARCHAR(MAX) = '';
	declare @DeviationColumnsDisplay VARCHAR(MAX) = '';
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlCommon nvarchar(max)	
	Declare @sqlEmpDesi nvarchar(max)
	Declare @sqlTempProcessedData varchar(max)	
	Declare @sqlCommonSwipeCardNo nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)	
	Declare @sqlEmpCategory nvarchar(max)
	Declare @sqlEmpType nvarchar(max)	
	set @sqlCommon=''
	--Creates the tepmoraray tables.
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200) ,  
		[EmployeeId] varchar(50),  	
		Present numeric(8,1),
		LeaveDays numeric(8,1),
		LopDays numeric(8,1),
		LateEntryNoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		sat_WorkHrs decimal(18,1),
		MonToSat_WorkHrs decimal(18,1),
		LessHoursWorked numeric(8,1),
		LateInMins int,
		TotalHrsEnteredInArmis numeric(8,1),
		TotalDefinedWorkHrs numeric(8,1),
		DaysNeedToDeduct_Late decimal(18,2) default(0.0),
		DaysNeedToDeduct_Armis decimal(18,2) default(0.0),
		DaysNeedToDeduct_Working decimal(18,2) default(0.0),
		TotalMinutesWorked int
	)	 	
    create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20),sat_WorkHrs decimal(18,1),MonToSat_WorkHrs decimal(18,1))
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  	
	create table #EmpGrade(Grade_Id int) 
    create table #EmpAttendanceDetails
    (	EmployeeID  varchar(50),
		Present numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateInMins numeric(8,1),		
		LopDays numeric(8,1),
		LeaveDays numeric(8,1),
		NoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		TotalDefinedWorkHrsInMins int default(0),
		weeknumber int,
		TotalMinutesWorked int
	)      
    create table #TempProcessedData
    (
		Employee_Code_Id varchar(20),
		NumberOfPresentDays decimal(18,1),
		LateInMins int,
		TotalLeaveDays decimal(18,1),
		OtherLeaveDays decimal(18,1),
		OverAllDeviations varchar(20),
		NumberofDaysWorked as (NumberOfPresentDays+TotalLeaveDays-OtherLeaveDays),
		DeviationHoursFormat_Week1 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week2 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week3 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week4 varchar(30) default('TC:00:00 A:00:00'),
		DeviationHoursFormat_Week5 varchar(30) default('TC:00:00 A:00:00')
	)   		
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID);
	--INSERT INTO @TempExecptionHrs
	--	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	--	WHERE [Date] BETWEEN @fromDat AND @ToDat
	--GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @fromDat, @ToDat)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @fromDat) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @fromDat)) != 'Sunday' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT	@WeekName = 'Week' + CAST(@I AS VARCHAR(10)),
			@DeviationColumns=@DeviationColumns+'+convert(int,isnull(DeviationHours_' + @WeekName+',0))', 
			@DeviationColumnsDisplay=@DeviationColumnsDisplay+',DeviationHoursFormat_' + @WeekName ,
			@TableColumns = @TableColumns + ', TargetWorkHours_' + @WeekName + ' VARCHAR(10), ActualWorkHours_' + @WeekName + ' VARCHAR(10), ArmisWorkHours_' + @WeekName + ' VARCHAR(10), [Leave_Permision_' + @WeekName + '] VARCHAR(10), 
	DeviationHours_' + @WeekName + ' VARCHAR(30),DeviationHoursFormat_'+@WeekName+' varchar(30)default(''TC:00:00 A:00:00'')',@I = @I + 1 FROM WeekName
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]([Grade_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[EmployeeId],[LevelId] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[EmployeeId],[DesignationId] ASC)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[EmployeeId],[CategoryId])ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[EmployeeId],[TypeId]) ON [PRIMARY]  
	--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
	SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
	INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDat AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
	SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
	SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
	INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
	INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType 
	SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
	SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
	INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
	INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
	AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
	SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
	SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
	INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102)
	GROUP BY EmployeeId) EmpCategory
	INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
	AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
	INSERT INTO #EmpPay
	SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
	SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
	INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
	AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FinalAttendanceSummary')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC('CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50),Sat_WorkHrs	numeric(18,1)' + @TableColumns + ')')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = 'Week' + CAST(@I AS VARCHAR(10))		
		SELECT 
		@fromDat = Tbl1.WeekDates,
		@ToDat = Tbl2.WeekDates FROM (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
		INNER JOIN (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
		WHERE Tbl1.Id = @I				
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10),WeekDay_WorkHrs decimal(18,1))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int,
		Sat_WorkHrs	numeric(18,1)
		)
		--Commented for local database
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
		SET @SQLQuery = 'SELECT * FROM 
		[ProjectManagementV3July16].[dbo].[Fn_GetProgressReport](''' + CAST(@fromDat AS VARCHAR(20)) + ''',''' + CAST(@ToDat AS VARCHAR(20)) + '''' + (CASE WHEN @empId = '' OR @empId IS NULL THEN ', NULL)' ELSE ', ' + @empId + ')' END)
		--Commented for local database
		INSERT INTO @ArmisTable
		EXEC(@SQLQuery)			
		--select * from @ArmisTable
		SET @SQLQuery = 'SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''' ELSE ''(BL)'' END,'
		SET @SQLQuery = @SQLQuery + ' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''), REPLACE(LD.Name, ''&amp;'', ''&''),'
		SET @SQLQuery = @SQLQuery + ' REPLACE(T.TitleName, ''&amp;'', ''&''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''-''), ISNULL(PD.OutTime, ''-''),'
		SET @SQLQuery = @SQLQuery + ' ISNULL(PD.HrsWork, ''-''), ((SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''00:00''), 4, 2))),'
		SET @SQLQuery = @SQLQuery + ' (S.Shift_ShortName + '' ('' + S.Shift_StartTime + '' - ''  + S.Shift_EndTime + '')''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''-''),'
		SET @SQLQuery = @SQLQuery + ' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' (CASE WHEN (ISNULL(PD.BreakIn, '''') = '''' OR ISNULL(PD.BreakOut, '''') = '''') AND PD.BreakHours <> ''00:00'' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),'
		SET @SQLQuery = @SQLQuery + ' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')),ISNULL(SS.MaxWorkPlaceInHours, ''00:10''), NULL
		,C.WeekDay_WorkHrs*60.0 FROM Ta_Tbl_Employee E'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id'    
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId'   
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id'
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId '
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId'
		SET @SQLQuery = @SQLQuery + ' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId '		
		set @SQLQuery = @SQLQuery + ' where 
		(
			(e.Employee_Status = 1) 
			or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102))
		) 	
		AND (e.Isdeleted = 0) AND (e.report_exclude = 0)'
		SET @SQLQuery = @SQLQuery + ' AND ((PD.date >= CONVERT(DATETIME, ''' + CAST(@fromDat AS NVARCHAR(11)) + ''', 102) 
		AND PD.Date <= CONVERT(DATETIME, ''' + CAST(@ToDat AS NVARCHAR(11)) + ''', 102)))'
		IF(@UserGroupName <> 'SuperAdmin')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND G.Grade_Level >= ' + @GradeLevel + ''
		END
		IF NOT(@EmployeeName = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_FirstName + '' '' + ISNULL(E.Employee_LastName, '''') LIKE ''' + CAST(@EmployeeName +'%' AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@empId='')  
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND (E.Employee_Code_Id = ''' + CAST(@empId AS NVARCHAR(100)) + ''')'
		END
		IF NOT(@EmpSwipeCard = '')
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND E.SwipeCardNo = ''' + @EmpSwipeCard + ''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND EC.CategoryId = ' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + ' AND ET.TypeId = ' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		If (@Gender <> 'Both')  
		Begin  
			Set @SQLQuery = @SQLQuery + ' And E.Gender = ''' + @Gender + ''' '  
		End
		SET @SQLQuery = @SQLQuery + ' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)'   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		--select * from #TempAttendanceDetails 
		--UPDATE #TempAttendanceDetails SET
		--HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		--TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		--FROM #TempAttendanceDetails AD
		--RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDat) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
		WHERE #TempAttendanceDetails.Day = 'Saturday' AND #TempAttendanceDetails.Date = @ThirdSat
		INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.CategoryName,
			TA.DefinedWorkHours,
			TA.DefinedWorkHours - SUM(
		(((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN('Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
		ELSE 
		0.0
		END
		) * 8,
		SUM(CAST(TA.TotalMinsWorked AS INT)),
		0,
		SUM(
		(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
		WHEN C.Sat_WorkHrs = 2 THEN 
		(CASE 
		WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
		WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
		0.0 END)
		ELSE 
		(CASE
		WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
		WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
		0.0 END
		)
		END
		) * 8,
		0,
		CAST(MAX(TA.[Date]) AS DATE),
		0,0
		FROM #TempAttendanceDetails TA
		INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != 'Sunday'
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
		UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
		UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
		--Commented for local database
		UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
		INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id		
		UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
		--select 
		--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
		CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
		(ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
						(
							substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX('.',convert(varchar(10),ArmisWorkHours)))*60
							+
							substring(convert(varchar(10),ArmisWorkHours),CHARINDEX('.',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
							+ 
							[Leave_Permision] *60
							+ 
							(DefinedWorkHours - TargetWorkHours)*60
						)
					)
		ELSE 0 
		END,
		Sat_WorkHrs=C.Sat_WorkHrs
		FROM #TempAttendanceSummary TAS
		INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
		INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
		SELECT	@WeekName AS WeekName,
				Employee_Code_Id,
				EmployeeName,
				CategoryName,
				REPLACE((TargetWorkHours - [Leave_Permision]), '.', ':') AS TargetWorkHours,
				CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + ':' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
				REPLACE(ArmisWorkHours, '.', ':') AS ArmisWorkHours,
				REPLACE([Leave_Permision], '.', ':') AS [Leave_Permision],
				case	when DeviationHours>ArmisDeviationHrs then	DeviationHours																
						when ArmisDeviationHrs>DeviationHours then	ArmisDeviationHrs
						when ArmisDeviationHrs=DeviationHours then	DeviationHours
				end AS DeviationHours,
				--DeviationHours AS DeviationHours,
				Sat_WorkHrs,				
			'TC:'+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN '0' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			'A:'+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN '0' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + ':' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END as DeviationHoursInFormat
		INTO #TempFinalResult FROM #TempAttendanceSummary WHERE (DeviationHours != 0 or ArmisDeviationHrs != 0 OR 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = 'UPDATE FinalAttendanceSummary SET 
		Employee_Code_Id	= TR.Employee_Code_Id,
		EmployeeName		= TR.EmployeeName,
		CategoryName		= TR.CategoryName,
		TargetWorkHours_' + @WeekName + ' = TR.TargetWorkHours,
		ActualWorkHours_' + @WeekName + ' = TR.ActualWorkHours,
		ArmisWorkHours_' + @WeekName + ' = TR.ArmisWorkHours,
		[Leave_Permision_' + @WeekName + '] = TR.[Leave_Permision],
		DeviationHours_' + @WeekName + ' = isnull(TR.DeviationHours,0),
		Sat_WorkHrs=TR.Sat_WorkHrs,
		DeviationHoursFormat_' + @WeekName + ' = TR.DeviationHoursInFormat
		 FROM FinalAttendanceSummary FAS
		INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName'
		EXEC(@SQLQuery)
		SET @SQLQuery = '
		INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName,
		Sat_WorkHrs,TargetWorkHours_' + @WeekName + ', ActualWorkHours_' + @WeekName + ', ArmisWorkHours_' + @WeekName + ', 
		[Leave_Permision_' + @WeekName + '], DeviationHours_' + @WeekName + ', DeviationHoursFormat_' + @WeekName +')
		SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName,TR.Sat_WorkHrs,TR.TargetWorkHours, TR.ActualWorkHours, 
		TR.ArmisWorkHours, TR.[Leave_Permision],isnull(TR.DeviationHours,0),TR.DeviationHoursInFormat FROM #TempFinalResult TR
		LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
		WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL'
		EXEC(@SQLQuery)
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		--Commented for local database
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	--select * from FinalAttendanceSummary
	--Getting 3rd saturday date.
	Create table #Temp(date datetime,day varchar(max),id int)
	;with cte(Date,id,week) as 
	(	
		select @FromDateOld,1 as id,DATEPART(WEEK,@FromDateOld)
		union all
		select Date+1,id+1,DATEPART(WEEK,Date+1) from cte where Date < @ToDateOld
	)
	insert into #Temp select Date,DATENAME(W,Date)Day,id from cte
	option (MAXRECURSION 0)
	Declare @ThirdSaturday datetime	
	select @ThirdSaturday=date from(select *,ROW_NUMBER()over(order by id)as row from #Temp where day='Saturday')as a where row=3
	set	@DeviationColumnsDisplay=SUBSTRING(@DeviationColumnsDisplay,2,len(@DeviationColumnsDisplay))
	--select @DeviationColumns
	--select @DeviationColumnsDisplay
	--declare @alter varchar(max)
	--set @alter='alter table #TempProcessedData add '+replace(@DeviationColumnsDisplay,',',' varchar(20),')+' varchar(20)'
	--Execute(@alter)
	set @sqlTempProcessedData1=  
	'insert into #TempProcessedData
	(Employee_Code_Id,NumberOfPresentDays,LateInMins,TotalLeaveDays,OtherLeaveDays,OverAllDeviations,'+@DeviationColumnsDisplay+')
	select	Employee_Code_Id	=	PD.Employee_Code_Id,
	NumberOfPresentDays	=	sum(CASE when PD.DATE= ''' +CONVERT(varchar(20),@ThirdSaturday) + ''' 
	and Sat_WorkHrs=2 and DATENAME(W,Date)=''Saturday'' then 
	case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
			when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
	end
	 when Sat_WorkHrs=0 and DATENAME(W,Date)=''Saturday'' then 
	 case	when FNAttendanceCode=''Present''	 and ANAttendanceCode=''Present''	 then 0.5
			when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Present''    and ANAttendanceCode=''Weekly Off'' then 0.5
			when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Present''    then 0.5
	  end
	when Sat_WorkHrs>0 and DATENAME(W,Date)=''Saturday'' then
		case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
		end
	WHEN (FNAttendanceCode=''Present'') THEN 0.5
	else 0.0
	END)+
	sum(CASE when PD.DATE= ''' +CONVERT(varchar(20),@ThirdSaturday) + ''' and Sat_WorkHrs=2 and DATENAME(W,Date)=''Saturday'' 
	then case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
		when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
	end
		when Sat_WorkHrs=0 and DATENAME(W,Date)=''Saturday'' then case	when FNAttendanceCode=''Present''	 
		and ANAttendanceCode=''Present''	 then 0.5
		when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Present''    and ANAttendanceCode=''Weekly Off'' then 0.5
		when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Present''    then 0.5
   end
		when Sat_WorkHrs>0 and DATENAME(W,Date)=''Saturday'' then
		case	when FNAttendanceCode=''Present''	  and ANAttendanceCode=''Present''	  then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Present''     and ANAttendanceCode=''Weekly Off'' then 0.5
				when FNAttendanceCode=''Weekly Off''  and ANAttendanceCode=''Present''    then 0.5
		end
		WHEN (ANAttendanceCode=''Present'') THEN 0.5
		else 0.0
   END),							
		LateInMins			=	sum(isnull(LateInMins,0)),
		TotalLeaveDays		=  sum(CASE WHEN FNAttendanceCode=''CL''		THEN 0.5
										WHEN FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN 1
										WHEN FNAttendanceCode=''LOP''		THEN 0.5
										WHEN FNAttendanceCode=''Absent''	THEN 0.5
										WHEN FNAttendanceCode=''SL''		THEN 0.5
										WHEN FNAttendanceCode=''CompOff''	THEN 0.5
										else 0 
										END
										)+
								sum(CASE	WHEN ANAttendanceCode=''CL''		THEN 0.5
											WHEN ANAttendanceCode=''LOP'' and FNAttendanceCode=''Weekly Off'' THEN 1
											WHEN ANAttendanceCode=''LOP''		THEN 0.5
											WHEN ANAttendanceCode=''Absent''	THEN 0.5
											WHEN ANAttendanceCode=''SL''		THEN 0.5
											WHEN ANAttendanceCode=''CompOff''	THEN 0.5
											else 0 
									END
									),
		OtherLeaveDays		=	sum(CASE	WHEN FNAttendanceCode=''LOP'' and ANAttendanceCode=''Weekly Off'' THEN 1
											WHEN FNAttendanceCode=''LOP''		THEN 0.5
											WHEN FNAttendanceCode=''Absent''	THEN 0.5
											else 0 
									END
									) + 
								sum(CASE	WHEN ANAttendanceCode=''LOP'' and FNAttendanceCode=''Weekly Off'' THEN 1
											WHEN ANAttendanceCode=''LOP''		THEN 0.5
											WHEN ANAttendanceCode=''Absent''	THEN 0.5
											else 0 
									END
									),
			OverAllDeviations	=	convert(int,'+@DeviationColumns+'),
			'+@DeviationColumnsDisplay+'
	from TA_Tbl_ProcessedData PD 
	inner join FinalAttendanceSummary as fat on fat.Employee_Code_Id=PD.Employee_Code_Id
    where ((PD.date >= CONVERT(DATETIME,'''+cast( @FromDateOld as nvarchar(50))+''', 102))
	AND (PD.date <= CONVERT(DATETIME,'''+cast(@ToDateOld as nvarchar(50))+''', 102)))'
	If Not (@empId = '')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' And PD.Employee_Code_Id = ''' + @empId + ''' '  
		End
	Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + ' group by PD.Employee_Code_Id,'+@DeviationColumnsDisplay+','+@DeviationColumns
	execute(@sqlTempProcessedData1)
	--select * from #TempProcessedData
	--select @FromDateOld,@ToDateOld
	--select * from TA_Tbl_ProcessedData PD where Employee_Code_Id='787'
	--and ((PD.date >= CONVERT(DATETIME,cast( @FromDateOld as nvarchar(50)), 102))
	--AND (PD.date <= CONVERT(DATETIME,cast(@ToDateOld as nvarchar(50)), 102)))
	Create table #TempFinal([Employee ID] varchar(50),[Emp.Name] varchar(100),[Level Name] varchar(250),
	[Present] decimal(18,1),[Leave] decimal(18,1),[Other Leave] decimal(18,1),Deviation decimal(18,1))
	insert into #TempFinal
	select 
	--ld.id,	
	PD.Employee_Code_Id as [Employee ID],
			FS.EmployeeName as [Emp.Name],
			ld.name as [Level Name],			
			NumberOfPresentDays as [Present],
			TotalLeaveDays as [Leave],
			OtherLeaveDays as [Other Leave],			
			(
				select	case	when OverAllDeviations =0 then 0
								when OverAllDeviations	between  starttime1		and		EndTime1	then Day1
								when OverAllDeviations	between  StartTime2		and		EndTime2	then Day2
								when OverAllDeviations	between  StartTime3		and		EndTime3	then Day3
								when OverAllDeviations	between  StartTime4		and		EndTime4	then Day4
								when OverAllDeviations	between  StartTime5		and		EndTime5	then Day5
								when OverAllDeviations	between  StartTime6		and		EndTime6	then Day6
								when OverAllDeviations	between  StartTime7		and		EndTime7	then Day7
								when OverAllDeviations	between  StartTime8		and		EndTime8	then Day8
								when OverAllDeviations	between  StartTime9		and		EndTime9	then Day9
								when OverAllDeviations	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Workhrs
			)+
			(
				select	case	when LateInMins =0 then 0
								when LateInMins	between  starttime1		and		EndTime1	then Day1
								when LateInMins	between  StartTime2		and		EndTime2	then Day2
								when LateInMins	between  StartTime3		and		EndTime3	then Day3
								when LateInMins	between  StartTime4		and		EndTime4	then Day4
								when LateInMins	between  StartTime5		and		EndTime5	then Day5
								when LateInMins	between  StartTime6		and		EndTime6	then Day6
								when LateInMins	between  StartTime7		and		EndTime7	then Day7
								when LateInMins	between  StartTime8		and		EndTime8	then Day8
								when LateInMins	between  StartTime9		and		EndTime9	then Day9
								when LateInMins	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Lateentry
			)AS [Deviation]
	from #TempProcessedData PD
	inner join FinalAttendanceSummary FS on PD.Employee_Code_Id=FS.Employee_Code_Id
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = PD.Employee_Code_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId
	INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id
	INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId
	order by ld.id,convert(int,pd.Employee_Code_Id)	
	select [Employee ID] ,[Emp.Name] ,[Level Name],[Present],[Leave] ,[Other Leave] ,Deviation,	Present+Leave-[Other Leave]-Deviation as
	[Tot.Worked]
	from #TempFinal
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	DROP TABLE #EmployeeIds
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #EmpPay		
	DROP TABLE FinalAttendanceSummary
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- Author:  senthil    Proc_TA_RptPermanentShift '2015/05/01',[0,1],'787,','',0,0,'SuperAdmin',0,'',0,0,'Both',0
-- ALTER  date: 17Aug2007      
-- Description: Report Permanent Shift 
-- Modified by : sashma
-- Modified on : 12-May-2011   
-- =============================================      
CREATE  PROCEDURE [dbo].[Proc_TA_RptPermanentShift]       
(      
 @fromDate datetime,       
 @LevelID varchar(8000),
 @EmployeeId varchar(max),
 @EmployeeName varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @shift int,
 @EmpAutoId bigint	     
)      
AS      
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	----Employee Level insert in Temporary table
	--insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	--select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) ELevel
	--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
	----select * from #EmpLevel
	----Employee Designation insert in Temporary table
	--insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	--select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	--inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EDesig
	--inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	--AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
	----select * from #EmpDesignation
	----Employee Type insert in Temporary table
	--insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	--select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	--inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EmpType
	--inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	--AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
	----select * from #EmpType
	----Employee Category insert in Temporary table
	--insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	--select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	--inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	--inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	--AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null	
	Declare @sqlEmpLevel nvarchar(4000)
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @fromDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @fromDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @fromDate,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@fromDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)      
	SET @sqlQuery = ''      
	SET @sqlQuery1 = ''
	DECLARE @timeformat   varchar(10)
	SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat='hh:mm tt')
		begin
			SET @sqlQuery = @sqlQuery + ' SELECT dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''&amp;'',''&'') + '' ('' + TA_Tbl_Shift.Shift_Starttime +'' - '' + TA_Tbl_Shift.Shift_endtime + '')'' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + Space(1) + '      
		end
	else
		begin
			SET @sqlQuery = @sqlQuery + ' SELECT dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''&amp;'',''&'') + '' ('' + convert(char(5),cast(TA_Tbl_Shift.Shift_Starttime as datetime),108)  +'' - '' + convert(char(5),cast(TA_Tbl_Shift.Shift_endtime as datetime),108) + '')'' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + Space(1) + '      
		end
	SET @sqlQuery = @sqlQuery + ' isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') as empname, replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,replace(dbo.TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,TA_Tbl_Employee.Gender'      
	SET @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_PermanentShiftAllocation LEFT OUTER JOIN'      
	SET @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN'      
	SET @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id'      
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'      
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	SET @sqlQuery = @sqlQuery + ' WHERE (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'      
	SET @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0'
	if(@shift<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery +  ' And  TA_Tbl_Shift.Shift_Id = ' +  cast(@shift  as nvarchar(20))  
		END
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End      	
	if(@Gender<>'Both')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		END		
	if(@UserGroupName<>'SuperAdmin')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
		END
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
		END
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		END
	if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	exec (@sqlQuery)
	--Remove the temporary tables here
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

-- =============================================
-- Author:		senthil
-- Create date: 17Aug2007
-- Description:	Report Permanent Shift
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptPermanentShit]
(
	@fromDate datetime,	
	@LevelID varchar(18) 
)
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''
					  set @sqlQuery = @sqlQuery + ' SELECT     dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId, dbo.TA_Tbl_Shift.Shift_ShortName, dbo.TA_Tbl_Employee.Employee_FirstName + Space(1) + '
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee.Employee_LastName as empname, dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName'
					  set @sqlQuery = @sqlQuery + ' FROM  dbo.TA_Tbl_PermanentShiftAllocation INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = dbo.TA_Tbl_Title.TitleId'
					  set @sqlQuery = @sqlQuery + ' WHERE     (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'
if not(@LevelID='' or @LevelID='0')
		begin
					set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.LevelId = ' + cast (@LevelId as nvarchar(50)) 
		end	
END
exec (@sqlQuery)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermission]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_RptPermission '04/05/2011','05/15/2013','','','',0,0,'SuperAdmin',0,'All','',0,0,'Both'
--  Proc_TA_RptPermission '01/Aug/2016','30/Sep/2016','','0,1','',0,0,'SuperAdmin',0,'All','',1,0,'Both',0
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
CREATE  PROCEDURE [dbo].[Proc_TA_RptPermission]
 (
    @fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LeaveStatus varchar(30),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
    @Gender varchar(10),
    @EmpAutoId bigint
 )
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as varchar(8000)
	set @sqlQuery=''
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_LastName,'''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation, case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_Permission.Permission_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, TA_Tbl_Permission.Permission_Date, '+cast(@dateFormat as varchar(100))+')
	end AS Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Gender,TA_Tbl_Permission.Permission_Hours,((SUBSTRING(ISNULL(TA_Tbl_Permission.Permission_Hours,''00:00''),0,CHARINDEX('':'',TA_Tbl_Permission.Permission_Hours))*60) + (SUBSTRING(ISNULL(TA_Tbl_Permission.Permission_Hours,''00:00''),(LEN(TA_Tbl_Permission.Permission_Hours)-1),2))) AS TOTALPERMISSIONMINS,Permission_Reason,
	Case when Permission_Status=''Pending'' then ''-''
	Else Ta_Tbl_Employee.Employee_FirstName
	End As Approved_By,
	case when '+CONVERT(varchar,@dateFormat)+'=106 then REPLACE(CONVERT(VARCHAR,TA_Tbl_PermissionConversation.Timestamp,'+CONVERT(Varchar,@dateFormat)+'),'' '',''-'')
		 else CONVERT(VARCHAR,TA_Tbl_PermissionConversation.Timestamp,'+CONVERT(varchar,@dateFormat)+')
		 End As Approved_Date
	
	
	from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id
	Left join Ta_Tbl_Employee on Ta_Tbl_Employee.Employee_Id = Ta_Tbl_Permission.Emp_Id
	Left join TA_Tbl_PermissionConversation on TA_Tbl_PermissionConversation.PermissionId=Ta_Tbl_Permission.Permission_Id and TA_Tbl_PermissionConversation.Emp_Id=Ta_Tbl_Permission.Emp_Id'
	
	--from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 
	and 
	((e.employee_Status=1)
	or
	(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),TA_Tbl_Permission.Permission_Date,102))
	) 
	and (TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102) and TA_Tbl_Permission.Permission_Date <= CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102))'
	if(@UserGroupName<>'SuperAdmin')
	begin
		set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
	end
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	   
	if not(@LeaveStatus='All')
		begin
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Permission.Permission_Status= ''' + cast(@LeaveStatus as nvarchar(100)) + ''''
		end
	if(@isReportingto > 0)
    BEGIN
       set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
    END
	set @sqlQuery = @sqlQuery + ' Group by TA_Tbl_PermissionConversation.TimeStamp,Ta_Tbl_Employee.Employee_FirstName,TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,TA_Tbl_Permission.Permission_Hours,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName,e.Gender,Permission_Reason order by e.Employee_Code_Id,e.Employee_FirstName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName,Permission_Reason ASC'	
   
    exec(@sqlQuery)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_rptPunctuality]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptMonthlyAttendance  
MOdified By : Gopinath.K  
Modified Date : 20-Dec-2013 & 11-Jan-2014
Description   :SQL Query Optimization & Emp name filtering
*/
-- proc_ta_rptPunctuality  '01/01/2016','12/31/2020','',0,'','',0,0,'SuperAdmin','0','',0,0,'Both',0,1
CREATE  PROCEDURE [dbo].[proc_ta_rptPunctuality]  
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeId varchar(max),  
	@shift int = 0,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000),
	@employeeCategory int = 0,
	@employeeType int = 0,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	--This get the current datetime format
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where emp.Isdeleted=0 
		and (isnull(@EmployeeId,'')='' or emp.Employee_Code_Id in(select * from #EmployeeID))
		and (isnull(@EmployeeName,'')='' or emp.Employee_Code_Id in(select * from #EmployeeName))
		and(@Gender='Both' or emp.Gender=@Gender)
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,@todat, 102) and EL.LevelId is not null
	
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
    insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	and (isnull(@EmployeeId,'')='' or TA_Tbl_Employee.Employee_Code_Id in(select * from #EmployeeID))
	and (isnull(@EmployeeName,'')='' or TA_Tbl_Employee.Employee_Code_Id in(select * from #EmployeeName))
	
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id
	from TA_Tbl_ProcessedData 
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
    where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102))  
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(20)), 102))  
	and  dbo.TA_Tbl_ProcessedData.LateIn='00:00' and intime<>'00:00'
	and (@shift=0 or TA_Tbl_ProcessedData.Shift_Id=@shift)
	
	Create table #TempPunc(shift_shartName nVarchar(5), shiftIn nvarchar(20),Employee_Code_Id nvarchar(20),Date nvarchar(20),shift_id int,InTime nvarchar(20),Employee_FirstName nvarchar(100),[Level Name] nvarchar(100),TitleName nvarchar(100),Gender nvarchar(10),format datetime)
	insert into #TempPunc 
	select	ta_tbl_shift.shift_shortName, 
			right(dbo.ta_tbl_shift.Shift_StartTime,8)as shiftIn, 
			TA_Tbl_Employee.Employee_Code_Id,
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, #TempProcessedData.Date,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, #TempProcessedData.Date, @dateFormat) 
			end AS 'Date', #TempProcessedData.shift_id,
			#TempProcessedData.InTime,
			(dbo.TA_Tbl_Employee.Employee_FirstName + ' ' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'')) as Employee_FirstName,
			replace(dbo.Ta_Tbl_levelDetails.name,'&amp;','&') AS 'Level Name',
			replace(TA_Tbl_Title.TitleName,'&amp;','&') AS 'TitleName',
			TA_Tbl_Employee.Gender,#TempProcessedData.Date as format FROM
			#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee  ON #TempProcessedData.EmpAutoId = ta_tbl_employee.Employee_ID 
			Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id 
			inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id
			inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId
			inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId
			INNER JOIN dbo.ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id
			Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id
			Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id
			where #TempProcessedData.InTime <> '0' and #TempProcessedData.InTime <> '00:00:00' and #TempProcessedData.InTime is not null
			And (	TA_Tbl_Employee.Employee_Status = 1 or (TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102) >= convert(varchar(11),#TempProcessedData.Date,102))) 
			AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0)
			and (@UserGroupName='Superadmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			and(@isReportingto=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds))) 
			and(@EmpAutoId=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)))
			order by lower(TA_Tbl_Employee.Employee_Code_Id),ta_tbl_Employee.Employee_FirstName,cast(#TempProcessedData.Date as datetime)
	if(@ExportType=1)
	begin
		select Employee_Code_Id ,Employee_FirstName,Gender,Date,shiftIn,InTime,shift_shartName as shift_shortName,shift_id,[Level Name],TitleName,format from #TempPunc
	end
	else
	begin		
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempPunc
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempPunc order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + '@'
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempPunc where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(@RowCount as nvarchar(20)) + '%'
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + '$' + cast(0 as nvarchar(1)) + '%'
				end
				--select distinct Date from #TempLate where [Level Name]=(select Name from #TempLevelName where ID=@cou)
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + '#'
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as 'Value'
	end
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
	drop table #TempProcessedData
	drop table #TempEmployee 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptRawData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_rptRawData '2019/04/01','2019/08/24','','','SuperAdmin',0,0,0,0,'Both',2,1,'0'
-- Proc_TA_rptRawData '2019/04/01','2019/08/24','','','SuperAdmin',0,0,0,0,'Both',2,1,'91280'
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- drop procedure [Proc_TA_rptRawData]
-- =============================================
/*
exec Proc_TA_rptRawData @ProcessType=N'0',@DesignationID=N'0',@Gender=N'Both',@EmployeeId=N'',
@EmpAutoId=N'0',@ParentID=N'37',@ToDate=N'05-02-2024 00:00:00',@UserGroupName=N'SuperAdmin',
@EmployeeName=N'',@FromDate=N'05-02-2024 00:00:00',@employeeType=N'0',@DeviceId=N'0',@employeeCategory=N'0'
*/
CREATE PROCEDURE [dbo].[Proc_TA_rptRawData]
(
	@FromDate varchar(20),
	@ToDate varchar(20),
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),
	@UserGroupName varchar(250),
	@DesignationID int,
	@employeeCategory int,
	@employeeType int,
	@ParentID int,
	@Gender varchar(10),
	@ProcessType int,
	@EmpAutoID int,
	@DeviceId varchar(50)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel int
	SET @Isdel=0
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmployeeName(EmployeeID varchar(25))
	create table #EmployeeID(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '')
	begin		
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@EmployeeId)
	end	
	if(@EmployeeName is not null and @EmployeeName <> '')
	begin
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
	end	
	--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Type insert in Temporary table
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		Left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id 
		where emp.Isdeleted=0 group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	set @sqlQuery='select	RD.CLK_CARDID as ''Employee_Code_Id'',
							Emp.Employee_FirstName + '' '' + isnull(Emp.Employee_LastName,'''') as EmployeeName,
							(isnull(Ter.Terminal_Name,'''') + '' ('' + RD.CLK_DEVICEID + '')'') as ''Terminal_Name'', 
							case	when '+cast(@dateFormat as varchar(100))+'=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') else CONVERT(VARCHAR, RD.CLK_DATE, '+cast(@dateFormat as varchar(100))+') 
									end AS ShiftDate,
							case	when '+cast(@dateFormat as varchar(100))+'=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') else CONVERT(VARCHAR, RD.CLK_DATE, '+cast(@dateFormat as varchar(100))+') end AS PunchDate,RD.CLK_TIME as PunchTime,(isnull(PY.PunchType,'''') + '' ('' + RD.CLK_TYPE + '')'') as ''PunchType'',RD.*,
							CONVERT(datetime,''01-01-1900 '' + RD.CLK_Time,103) as OrderTime, case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''Processing...'' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''Processed'' else case when ReasonId=''0'' then ''Processed'' else case when ReasonId=''1'' then ''Remedy 1'' else case when ReasonId=''2'' then ''Remedy 2'' else case when ReasonId=''3'' then ''Remedy 3'' else ''Remedy 4'' end end end end end 
									end  as Resolution,
							case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''Processing...'' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''Processed'' else ''Non Processed'' end end as Process
	from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.SwipeCardNo=RD.CLK_CARDID  '
	set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID '
	set @sqlQuery = @sqlQuery + ' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value '
	if(@ParentID=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
	end
	if(@employeeType=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
	end
	if(@DesignationID=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
	end
	if(@employeeCategory=0)
	begin
		set @sqlQuery = @sqlQuery + ' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
	end
	else
	begin
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
	end
	If Not (@EmployeeId = '')  
	Begin  
	SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.Employee_Code_Id '
	End
	If Not (@EmployeeName = '')  
	Begin  
		SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.Employee_Code_Id '
	End
	--set @sqlQuery = @sqlQuery + ' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where RD.CLK_DATE >='''+ @FromDate +''' and RD.CLK_DATE <=''' + @ToDate +''''

	if(@ProcessType <> 0)
	begin
	if(@ProcessType =1)
	begin
		set @sqlQuery = @sqlQuery + ' and CLK_FLAG=1 and CLK_PROCESS=1 '
	end
	else if(@ProcessType =2)
	begin
		if(@ParentID=0)
		Begin
			set @sqlQuery = @sqlQuery + ' and CLK_FLAG=1 and CLK_PROCESS=0 '
		End
		else
		Begin
			set @sqlQuery = @sqlQuery + ' and CLK_FLAG=1 and CLK_PROCESS=0 and Emp.InActive_Status=0 '
		End
	end
	end
	
	if(@Gender<>'Both')
	begin
		set @sqlQuery = @sqlQuery + ' and Emp.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
	end

	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + ' and (Emp.Employee_ID IN (select * from #EmployeeIds)) '  
	END

	if(@DeviceId !='0')
	begin
		set @sqlQuery = @sqlQuery + ' and RD.CLK_DEVICEID = ''' + cast(@DeviceId as nvarchar(40)) + ''' '
	end

	set @sqlQuery = @sqlQuery +' Order by RD.CLK_DATE,OrderTime desc'
	exec(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_RPTRAWDATAPUNCHES]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.MANIKANDAN
-- CREATE DATE: 11-11-2014
-- DESCRIPTION:	TO DISPLAY THE RAW DATA DETAILS
-- DROP PROC PROC_TA_RAWDATAPUNCHES
-- =============================================
CREATE PROCEDURE [dbo].[PROC_TA_RPTRAWDATAPUNCHES]
	-- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
	@EMPLOYEEID VARCHAR(50),
	@FROMDATE DATETIME,
	@TODATE DATETIME,	
	@PROCESSED INT,
	@TERMINALID INT,
	@PUNCHTYPES VARCHAR(20),
	@EMPLOYEENAME VARCHAR(150)
AS
BEGIN
	-- INTERFERING WITH SELECT STATEMENTS.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
    DECLARE @SQLQUERY VARCHAR(MAX)
    SET @SQLQUERY =''
	SET @SQLQUERY ='SELECT C.* FROM TA_TBL_CLK_RAWDATA C
					INNER JOIN TA_TBL_EMPLOYEE E ON C.CLK_CARDID=E.SWIPECARDNO
					INNER JOIN TA_TBL_TERMINAL T ON T.TERMINAL_READERID=C.CLK_DEVICEID
					INNER JOIN TA_TBL_PUNCHTYPES P ON T.TERMINAL_ID=P.TERMINAL_ID
					WHERE E.ISDELETED=0'
	IF(@EMPLOYEEID!='')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND E.EMPLOYEE_CODE_ID='+CONVERT(VARCHAR(50),@EMPLOYEEID)
		END
	IF(@FROMDATE!='' AND @TODATE!='')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND (C.CLK_DATE>='+@FROMDATE+'C.CLK_DATE<='+@TODATE+')'
		END
	IF(@TERMINALID!=0)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND (T.TERMINAL_ID='+CONVERT(VARCHAR(20),@TERMINALID)+')'
		END
	IF(@PROCESSED=1)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND (C.CLK_FLAG=1 AND C.CLK_PROCESS=1)'
		END
	IF(@PROCESSED=2)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND (C.CLK_FLAG!=1 OR C.CLK_PROCESS!=1)'
		END
	IF(@PUNCHTYPES<>'')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ ' AND P.PUNCHTYPE='+CONVERT(VARCHAR(20),@PUNCHTYPES)
		END
	SET @SQLQUERY =@SQLQUERY+ ' ORDER BY C.CLK_CARDID,CLK_DATE,CLK_TIME'
	EXECUTE(@SQLQUERY)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptRawDataPunches_Dashboard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_RptRawDataPunches_Dashboard '2015/09/01','2015/09/11','101,','karthikeyan','SuperAdmin',0,1,0,0,'Both'
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptRawDataPunches_Dashboard]
(
@FromDate varchar(20),
@ToDate varchar(20),
@EmployeeId varchar(max),
@EmployeeName varchar(max),
@UserGroupName varchar(250),
@DesignationID int,
@employeeCategory int,
@employeeType int,
@ParentID int,
@Gender varchar(10),
@EmpAutoID int
)
	-- Add the parameters for the stored procedure here
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
		if(@EmployeeId is not null and @EmployeeId <> '')
			begin
				create table #EmployeeID(EmployeeID varchar(25))
				insert into #EmployeeID
				select * from SplitupEmployeeCode(@EmployeeId)
			end	
		if(@EmployeeName is not null and @EmployeeName <> '')
			begin
				create table #EmployeeName(EmployeeID varchar(25))
				insert into #EmployeeName
				select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
			end	
		--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		create table #LevelRights(LevelId int)
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Employee Level Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type insert in Temporary table
		insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
		insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
		insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
		declare @sqlEmpLevel nvarchar(Max)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select * from #LevelRights
		set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.SwipeCardNo '
		End
	Execute(@sqlEmpLevel)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select CAST(Emp_ID as int) from TA_Tbl_Employee
		--select * from #EmployeeID
		--select * from #EmployeeName
		--select * from Ta_Tbl_levelDetails
		declare @sqlQuery as nvarchar(max)
		set @sqlQuery=''
		set @sqlQuery='select RD.CLK_CARDID as ''Employee_Code_Id'',Emp.Employee_FirstName + '' '' + Emp.Employee_LastName as EmployeeName,
		Ter.Terminal_Name,CONVERT(nvarchar(20),RD.CLK_DATE, '+ convert(varchar,@dateFormat) +') as ShiftDate,
		CONVERT(nvarchar(20),RD.CLK_DATE, '+ convert(varchar,@dateFormat) +') as PunchDate,RD.CLK_TIME as PunchTime,
		PY.PunchType,RD.*,ld.Name as LevelName,CAST(''01-01-1900 '' + RD.CLK_Time as datetime) as OrderTime
		from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.Employee_Code_Id=RD.CLK_CARDID  '
		set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID '
		set @sqlQuery = @sqlQuery + ' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value '
		if(@ParentID=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
				set @sqlQuery = @sqlQuery + ' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id'
				set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID'
			end
		if(@employeeType=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id'
			end
		if(@DesignationID=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id'
			end
		if(@employeeCategory=0)
			begin
				set @sqlQuery = @sqlQuery + ' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
			end
		else
			begin
				set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id '
			end
		If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.SwipeCard '
		End
		If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.SwipeCard '
		End
		set @sqlQuery = @sqlQuery + ' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where 
		RD.CLK_FLAG=1 and RD.CLK_PROCESS=1 and RD.ReasonId in (0) and RD.CLK_DATE >='''+ @FromDate +''' and RD.CLK_DATE <=''' + @ToDate +''''
		if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and Emp.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (Emp.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		set @sqlQuery = @sqlQuery +'Order by RD.CLK_DATE,OrderTime desc'
		exec(@sqlQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
exec Proc_TA_RptShiftAllocation @fromDat='2021-11-01 00:00:00.000',@ToDat='2021-11-25 00:00:00.000',
@EmployeeName=N'',@LevelID=N'1',@EmployeeId=N'',@employeeCategory=0,@employeeType=0,
@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=1,@DesignationID=0,
@Gender=N'Both',@Religion =0,@EmpAutoId = 0
*/
/*
Need to comment pivot table concept for product, Since lcoation table is not in product.
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftAllocation] 
(
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000), 
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(250),
	@EmpSwipeCard varchar(250),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(210),
	@Religion int,
	@EmpAutoId bigint
)	
AS  
BEGIN  
	SET NOCOUNT ON;

	
	
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId


	--Select * from #EmployeeIds

	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
	set @sqlQuery = 'select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') as Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender, e.employee_id from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_Code_Id '
		End
	set @sqlQuery=@sqlQuery + ' where e.Isdeleted=0 and 	
	 e.Report_exclude=0 and convert(datetime,convert(varchar(11),dateShift))>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(day(CONVERT(DATETIME, '''+  cast(@fromDat as nvarchar(20)) +''', 102 )) as nvarchar(2)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat as nvarchar(20)) +''', 102 ))as nvarchar(10)),102) '
	set @sqlQuery=@sqlQuery + ' and convert(datetime,convert(varchar(11),dateShift))<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(day(CONVERT(DATETIME, '''+  cast(@ToDat as nvarchar(20)) +''', 102 )) as nvarchar(2)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102 ))as nvarchar(10)),102)'
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>=' + @GradeLevel  
		end
	IF(@Religion!=1 and @Religion!=0)
		BEGIN
			SET @sqlQuery=@sqlQuery+' AND e.Religion = '+cast(@Religion as varchar(50))+' '
		END
	if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
	  END
	set @sqlQuery = @sqlQuery + ' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month' 
	exec(@sqlQuery) 	
	--print(@sqlQuery) 	
	
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation_Surguru]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec Proc_TA_RptShiftAllocation @fromDat='2019-07-01 00:00:00',
--@ToDat='2019-07-30 00:00:00',@EmployeeName=N'',@LevelID=N'0',
--@EmployeeId=N'4',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',
--@EmpSwipeCard=N'',@ParentId=1,@DesignationID=0,@Gender=N'Both',@Religion =0,@EmpAutoId = 0



/*  
Procedure Name : Proc_TA_RptShiftAllocation_Surguru '01/01/2019','12/12/2019','','','','','','SuperAdmin',1,'',0,0,'Both',0,0
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By : Velumani P 
Created on :   

-- Description	:	SQL Query Optimazation & Emp name filtering
exec Proc_TA_RptShiftAllocation @fromDat='2017-04-01 00:00:00',
@ToDat='2018-03-30 00:00:00',@EmployeeName=N'',@LevelID=N'26',
@EmployeeId=N'',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',
@EmpSwipeCard=N'',@ParentId=26,@DesignationID=0,@Gender=N'Both',@Religion =0,@EmpAutoId =0
*/ 

/*
Need to comment pivot table concept for product, Since lcoation table is not in product.
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftAllocation_Surguru] 
(
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000), 
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Religion int,
	@EmpAutoId bigint
)	
AS  
BEGIN  
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end


	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
	set @sqlQuery = 'select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') as Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender, e.employee_id from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_Code_Id '
		End
	set @sqlQuery=@sqlQuery + ' where e.Isdeleted=0 and 	
	 e.Report_exclude=0 and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat as nvarchar(20)) +''', 102 ))as nvarchar(10)),102) '
	set @sqlQuery=@sqlQuery + ' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102 ))as nvarchar(10)),102)'
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end	
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>=' + @GradeLevel  
		end
	IF(@Religion!=1 and @Religion!=0)
		BEGIN
			SET @sqlQuery=@sqlQuery+' AND e.Religion = '+cast(@Religion as varchar(50))+' '
		END
	if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
	  END
	set @sqlQuery = @sqlQuery + ' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month' 
	exec(@sqlQuery)  

	--query to show employee shift allocated location in report 
	create table #ShiftLocationTble(EmployeeName varchar(100),employee_Code_Id int,Year int, Month int, 
	Day1Shift int,Day2Shift int,Day3Shift int,Day4Shift int,Day5Shift int,
	Day6Shift int,Day7Shift int,Day8Shift int,Day9Shift int,Day10Shift int,
	Day11Shift int,Day12Shift int,Day13Shift int,Day14Shift int,Day15Shift int,
	Day16Shift int,Day17Shift int,Day18Shift int,Day19Shift int,Day20Shift int,
	Day21Shift int,Day22Shift int,Day23Shift int,Day24Shift int,Day25Shift int,
	Day26Shift int,Day27Shift int,Day28Shift int,Day29Shift int,Day30Shift int,Day31Shift int,
    emp_id int, timestamp datetime, dateShift datetime, titleName varchar(50), Gender nvarchar(10),employee_id nvarchar(15))
	
	insert into #ShiftLocationTble exec(@sqlQuery)  --employee_Id

	

	create table #PivotShiftTable1 (Employee_Code_Id varchar(15), EmployeeName varchar(100),LocName varchar(220),ShiftDate datetime, DayShiftName varchar(10), monthNo int)

	insert into #PivotShiftTable1 
	select Employee_Code_Id, a.EmployeeName,
	UPPER(isnull(LVL.name,'''')) as LocName, dbo.DateOnly(LOC.ShiftDate) as ShiftDate,'Day'+convert(nvarchar, DATEPART(d, LOC.ShiftDate))+'Shift' as DayShiftName, DATEPART(M, LOC.ShiftDate) as monthNo from #ShiftLocationTble a
	LEFT OUTER JOIN TA_tbl_ShiftAdd_Location LOC ON (convert(nvarchar,LOC.EmployeeId) = a.employee_Id)
	LEFT OUTER JOIN TA_TBL_LEVELDETAILS LVL on (LVL.Id = LOC.LocationId)
	where (LOC.ShiftDate) <=@ToDat and (LOC.ShiftDate >= @fromDat)

	select * from #PivotShiftTable1

	SELECT [Employee_Code_Id],EmployeeName,
	Day1Shift,Day2Shift,Day3Shift,Day4Shift, Day5Shift, 
	Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,
	Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,
	Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,
	Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,
	Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
	FROM   
	(
		SELECT DayShiftName,Employee_Code_Id, EmployeeName,LocName,monthNo FROM  #PivotShiftTable1
	)Tab1  
	
	PIVOT  
	
	(  
	Max(LocName) FOR DayShiftName	
	IN (
	Day1Shift,Day2Shift,Day3Shift,Day4Shift, Day5Shift, 
	Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,
	Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,
	Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,
	Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,
	Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
	)
)	AS Tab2 
	
	ORDER BY [Tab2].[Employee_Code_Id] 

	--Remove the temporary tables here 
    drop table #ShiftLocationTble

	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftNotAllocated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptShiftNotAllocated '10/01/2019','10/31/2019','','','9547','','','SuperAdmin',1,'',0,0,'Both',1
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation and  TA_tbl_TemporaryShiftAllocation
Created By : Sashma  
Created on : 10-May-2011    
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftNotAllocated] 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(max),  
 @LevelID varchar(8000), 
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoId bigint
AS  
BEGIN  
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
		if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	create table #TempEmployee 
	(EmployeeAutoID bigint,EmpName varchar(150),Employee_Code_Id varchar(20),Designation varchar(150),Gender varchar(10),name varchar(150),datetOfjoining datetime)
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
    set @sqlQuery = 'insert into #TempEmployee select e.employee_Id,e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,''''),e.employee_code_id,T.TitleName,e.Gender,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,e.DateOfJoining from TA_Tbl_Employee e '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID'
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id '
		End
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id '
		End
	set @sqlQuery=@sqlQuery + ' where e.Isdeleted=0  and e.Report_exclude=0 and e.Employee_Status=1 '
		if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
		END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND G.Grade_Level>=' + @GradeLevel  
		end
    if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end
	exec(@sqlQuery)  
	--To fill the dates in between the from date and to date for all employees
	create table #TempEmployeeWithDate(EmployeeAutoID bigint,EmpName varchar(150),Employee_Code_Id varchar(20),Designation varchar(150),Gender varchar(10),name varchar(150),Date datetime)
	;WITH DateField AS
	(
	SELECT @fromDat Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < @ToDat
	)
	insert into #TempEmployeeWithDate
	SELECT TE.EmployeeAutoID,TE.EmpName,TE.Employee_Code_Id,TE.Designation,TE.Gender,TE.name,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where (Df.Dates between @fromDat and @ToDat) and (DF.Dates>=TE.datetOfjoining)Option (maxrecursion 0) 
	
	--select * from #TempEmployeeWithDate where Employee_Code_Id='9547'
	 
	create table #TempShiftNotAllocated_Permanent (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	create table #TempShiftNotAllocated_Temporary (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftNotAllocated_Permanent (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt where ShiftId<>0;
	--select * from #TempShiftNotAllocated_Permanent
	--Unpivot the temporary shift allocation table.
	insert into #TempShiftNotAllocated_Temporary (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + '/' + Replace(Replace(Day,'Day',''),'Shift','') + '/' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt where ShiftId<>0;
	--select * from #TempShiftNotAllocated_Temporary
	--update the shift id in the permanent table from temporary table
	update #TempShiftNotAllocated_Permanent set ShiftId=T.ShiftId
	from #TempShiftNotAllocated_Permanent P
	inner join  #TempShiftNotAllocated_Temporary T on (P.EmployeeID=T.EmployeeID
	and P.Year=T.Year and P.Month=T.Month and P.Day=T.Day)
    --inserts the records from the temporary table to the permanant table(records which is not exists in permanant table
	insert into #TempShiftNotAllocated_Permanent
	select T.EmployeeID,T.Year,T.Month,T.Day,T.ShiftId,T.Date from #TempShiftNotAllocated_Temporary T
	where not exists (select * from #TempShiftNotAllocated_Permanent P where P.EmployeeID=T.EmployeeID
	and P.Year=T.Year and P.Month=T.Month and P.Day=T.Day)
    --delete from permanant table if the date is not valid
	delete from #TempShiftNotAllocated_Permanent where isDate(Date) = 0 
    --select records from permanant table which has shift Id as 0 and also the dates which does not exists in the permanant table
	select	E.Employee_Code_Id,
			E.empname,
			E.name as DeptName,
			E.Designation as TitleName,
			E.Gender,
			E.Date as NotAllocatedDates 
	from #TempEmployeeWithDate E 
	where not exists(select * from  #TempShiftNotAllocated_Permanent PS where E.EmployeeAutoID = EmployeeID and E.Date=cast(PS.Date as datetime) and cast(PS.Date as datetime) between @fromDat and @ToDat)
	--union all
	--select E.Employee_Code_Id,(E.Employee_FirstName + ' ' + E.Employee_LastName) as empname,
	--LD.name as DeptName,T.TitleName,E.Gender,cast(PS.Date as Datetime) as NotAllocatedDates from #TempShiftNotAllocated_Permanent PS
	--inner join TA_Tbl_Employee E on PS.EmployeeID=E.Employee_Id
	--inner join TA_Tbl_EmployeeDesignation ED on ED.EmployeeID=E.Employee_Id
	--inner join TA_Tbl_Title T on T.TitleId=ED.DesignationID
	--inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
	--inner join Ta_Tbl_levelDetails LD on LD.id= EL.LevelId
	--where PS.ShiftId=0 and cast(PS.Date as datetime) between @fromDat and @ToDat order by E.Employee_Code_Id,NotAllocatedDates
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights 
	drop table #TempEmployee
	drop table #TempEmployeeWithDate
	drop table #TempShiftNotAllocated_Permanent
	drop table #TempShiftNotAllocated_Temporary
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_RptSummary '11-Jan-11','SuperAdmin','0'
CREATE PROCEDURE [dbo].[Proc_TA_RptSummary]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int       
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
--select * from #tempProcessSecSummary
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempProcessSecSummary '    
set @SelectSQL = @SelectSQL + ' select replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,Ta_tbl_Employee.SwipeCardNo  
as Employee_Code_Id,Ta_Tbl_ProcessedData.Date,Ta_Tbl_ProcessedData.FNAttendanceCode,Ta_Tbl_ProcessedData.ANAttendanceCode,Ta_Tbl_ProcessedData.EarlyOutMins,Ta_Tbl_ProcessedData.LateInMins,Ta_Tbl_ProcessedData.intime,Ta_Tbl_ProcessedData.outtime '    
set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave, null '    
set @SelectSQL = @SelectSQL + ' From Ta_Tbl_ProcessedData inner join Ta_tbl_Employee on Ta_Tbl_ProcessedData.[date]=''' + @Date +  ''' and Ta_Tbl_ProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo'    
set @SelectSQL = @SelectSQL + ' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
--set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_Employee.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 '    
exec (@SelectSQL)     
  --select * from  #tempProcessSecSummary  
create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempProcessSecSummaryFinal '    
set @SelectSQL = @SelectSQL + ' select distinct replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,'''' as   
Employee_Code_Id,''' + @Date +  ''' as Date,'''' as FNAttendanceCode,'''' as ANAttendanceCode,0 as EarlyOutMins,0 as LateInMins,'''' as  intime,'''' as outtime '    
set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 '    
set @SelectSQL = @SelectSQL + ' From Ta_tbl_Employee'    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
exec (@SelectSQL)     
update #tempProcessSecSummaryFinal set Absence=AbsenceCount.Absence    
from (select count(*) as Absence,levelID from #tempProcessSecSummary where    
FNAttendanceCode = 'Absent' and ANAttendanceCode = 'Absent'    
Group by levelID) AbsenceCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AbsenceCount.levelID    
update #tempProcessSecSummaryFinal set EarlyOut=EarlyOutCount.EarlyOut    
from (select count(*) as EarlyOut,levelID from #tempProcessSecSummary where    
(EarlyOutMins != 0 and  EarlyOutMins is not null and intime is not null and (LateInMins=0))    
Group by levelID) EarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=EarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set LateIn=LateInCount.LateIn    
from (select count(*) as LateIn,levelID from #tempProcessSecSummary where    
(LateInMins != 0 and LateInMins is not null and outtime is not null and (EarlyOutMins=0))    
Group by levelID) LateInCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInCount.levelID    
update #tempProcessSecSummaryFinal set [LateIn/EarlyOut]=LateInEarlyOutCount.[LateIn/EarlyOut]    
from (select count(*) as [LateIn/EarlyOut],levelID from #tempProcessSecSummary where    
EarlyOutMins != 0 and EarlyOutMins is not null and LateInMins != 0 and LateInMins is not null    
Group by levelID) LateInEarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInEarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set TotalPresent=TotalPresentCount.TotalPresent    
from (select count(*) as TotalPresent,levelID from #tempProcessSecSummary where    
(intime is not null or outtime is not null)    
Group by levelID) TotalPresentCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalPresentCount.levelID    
update #tempProcessSecSummaryFinal set MissingOut=MissingOutCount.MissingOut    
from (select count(*) as MissingOut,levelID from #tempProcessSecSummary where    
((intime is null and outtime is not null)     
or (intime is not null and outtime is null))     
Group by levelID) MissingOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=MissingOutCount.levelID    
update #tempProcessSecSummaryFinal set AttendancePunched=AttendancePunchedCount.AttendancePunched    
from (select count(*) as AttendancePunched,levelID from #tempProcessSecSummary where    
intime is not null and outtime is not null    
and LateInMins = 0     
and EarlyOutMins = 0     
Group by levelID) AttendancePunchedCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AttendancePunchedCount.levelID    
update #tempProcessSecSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees    
--from (select count(*) as TotalEmployees,TA_Tbl_Employee.LevelId from TA_tbl_EmployeeLevel     
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID     
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0    
--and @Date between TA_Tbl_EmployeeLevel.EffectiveDate and isnull(TA_Tbl_EmployeeLevel.endDate,getdate())    
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalEmployeesCount.levelID    
select * from #tempProcessSecSummaryFinal order by Dept    
 --remove the temporary tables     
drop table #tempProcessSecSummary    
drop table #tempProcessSecSummaryFinal    
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary_Old]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_RptSummary '11-Jan-11','SuperAdmin','0'
create PROCEDURE [dbo].[Proc_TA_RptSummary_Old]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int       
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
--select * from #tempProcessSecSummary
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempProcessSecSummary '    
set @SelectSQL = @SelectSQL + ' select replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,Ta_tbl_Employee.SwipeCardNo  
as Employee_Code_Id,Ta_Tbl_ProcessedData.Date,Ta_Tbl_ProcessedData.FNAttendanceCode,Ta_Tbl_ProcessedData.ANAttendanceCode,Ta_Tbl_ProcessedData.EarlyOutMins,Ta_Tbl_ProcessedData.LateInMins,Ta_Tbl_ProcessedData.intime,Ta_Tbl_ProcessedData.outtime '    
set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave, null '    
set @SelectSQL = @SelectSQL + ' From Ta_Tbl_ProcessedData inner join Ta_tbl_Employee on Ta_Tbl_ProcessedData.[date]=''' + @Date +  ''' and Ta_Tbl_ProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo'    
set @SelectSQL = @SelectSQL + ' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
--set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_Employee.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 '    
exec (@SelectSQL)     
  --select * from  #tempProcessSecSummary  
create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
set @SelectSQL = ' '     
set @SelectSQL = @SelectSQL + ' insert into #tempProcessSecSummaryFinal '    
set @SelectSQL = @SelectSQL + ' select distinct replace(L.Name,''&amp;'',''&'') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''&amp;'',''&''),replace(L.Name,''&amp;'',''&'')) as ParentName,'''' as   
Employee_Code_Id,''' + @Date +  ''' as Date,'''' as FNAttendanceCode,'''' as ANAttendanceCode,0 as EarlyOutMins,0 as LateInMins,'''' as  intime,'''' as outtime '    
set @SelectSQL = @SelectSQL + ' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 '    
set @SelectSQL = @SelectSQL + ' From Ta_tbl_Employee'    
set @SelectSQL = @SelectSQL + ' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id '    
set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id '    
set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id '    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId '    
set @SelectSQL = @SelectSQL + ' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 '    
exec (@SelectSQL)     
update #tempProcessSecSummaryFinal set Absence=AbsenceCount.Absence    
from (select count(*) as Absence,levelID from #tempProcessSecSummary where    
FNAttendanceCode = 'Absent' and ANAttendanceCode = 'Absent'    
Group by levelID) AbsenceCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AbsenceCount.levelID    
update #tempProcessSecSummaryFinal set EarlyOut=EarlyOutCount.EarlyOut    
from (select count(*) as EarlyOut,levelID from #tempProcessSecSummary where    
(EarlyOutMins != 0 and  EarlyOutMins is not null and intime is not null and (LateInMins=0))    
Group by levelID) EarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=EarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set LateIn=LateInCount.LateIn    
from (select count(*) as LateIn,levelID from #tempProcessSecSummary where    
(LateInMins != 0 and LateInMins is not null and outtime is not null and (EarlyOutMins=0))    
Group by levelID) LateInCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInCount.levelID    
update #tempProcessSecSummaryFinal set [LateIn/EarlyOut]=LateInEarlyOutCount.[LateIn/EarlyOut]    
from (select count(*) as [LateIn/EarlyOut],levelID from #tempProcessSecSummary where    
EarlyOutMins != 0 and EarlyOutMins is not null and LateInMins != 0 and LateInMins is not null    
Group by levelID) LateInEarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInEarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set TotalPresent=TotalPresentCount.TotalPresent    
from (select count(*) as TotalPresent,levelID from #tempProcessSecSummary where    
(intime is not null or outtime is not null)    
Group by levelID) TotalPresentCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalPresentCount.levelID    
update #tempProcessSecSummaryFinal set MissingOut=MissingOutCount.MissingOut    
from (select count(*) as MissingOut,levelID from #tempProcessSecSummary where    
((intime is null and outtime is not null)     
or (intime is not null and outtime is null))     
Group by levelID) MissingOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=MissingOutCount.levelID    
update #tempProcessSecSummaryFinal set AttendancePunched=AttendancePunchedCount.AttendancePunched    
from (select count(*) as AttendancePunched,levelID from #tempProcessSecSummary where    
intime is not null and outtime is not null    
and LateInMins = 0     
and EarlyOutMins = 0     
Group by levelID) AttendancePunchedCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AttendancePunchedCount.levelID    
update #tempProcessSecSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees    
--from (select count(*) as TotalEmployees,TA_Tbl_Employee.LevelId from TA_tbl_EmployeeLevel     
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID     
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0    
--and @Date between TA_Tbl_EmployeeLevel.EffectiveDate and isnull(TA_Tbl_EmployeeLevel.endDate,getdate())    
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalEmployeesCount.levelID    
select * from #tempProcessSecSummaryFinal order by Dept    
 --remove the temporary tables     
drop table #tempProcessSecSummary    
drop table #tempProcessSecSummaryFinal    
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummaryCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_RptSummaryCount   '27/01/2015','superadmin',0
CREATE PROCEDURE [dbo].[Proc_TA_RptSummaryCount]   
(    
 @Date VarChar(50),  
 @UserGroupName varchar(250),  
 @ParentId int      
)   
AS    
BEGIN    
  SET NOCOUNT ON 
 --added to prevent extra result sets from    
 -- interfering with SELECT statements.    
create table #LevelRights(LevelId int)  
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
Declare @SelectSQL As Varchar(8000)    
Set @SelectSQL = ' '      
Set @SelectSQL = 'Select count(*) as ReportCount '  
Set @SelectSQL = @SelectSQL + ' From Ta_Tbl_ProcessedData PD'  
Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo = PD.Employee_Code_Id'    
Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= ED.Employee_Id'    
Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id'    
set @SelectSQL = @SelectSQL + ' Inner join #LevelRights on #LevelRights.LevelId = Lev.LevelId '  
Set @SelectSQL = @SelectSQL + ' where ED.IsDeleted = ''0''  and ED.report_exclude=0'   
 If (@Date <> '')    
 Begin    
  Set @SelectSQL = @SelectSQL + ' And (PD.Date >= CONVERT(DATETIME,'''+cast(@Date as nvarchar(50))+''', 102))'
 End    
 exec (@SelectSQL)    
 --remove the temporary tables    
 SET NOCOUNT ON;    
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTawazunMonthlyAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec Proc_TA_RptTawazunMonthlyAttendance @MinWorkHours=N'',@fromDat='2020-02-01 00:00:00',@ToDat='2021-03-24 00:00:00',@EmployeeName=N'',@LevelID=N'0,1',@EmployeeId=N'',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@DesignationID=0,@Gender=N'Both',@Shift=0,@DataLoading=0,@EmpAutoId=0,@Export=0
CREATE  PROCEDURE [dbo].[Proc_TA_RptTawazunMonthlyAttendance]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		id int identity(1,1),
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		OD_Time varchar(20),
		Tot_OD_Mins int,
		EmpLevelID int
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!='Superadmin')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,',')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER='BOTH' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME='Superadmin')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'')='' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	

	declare @Count int=0, @loop int=1,@SQLStr nvarchar(MAX)=''
	create table #Emptest (
		EmployeeId nvarchar(20),
		LevelId int,
		Level1Name nvarchar(200),
		Level1Details nvarchar(200),
		Level2Name nvarchar(200),
		Level2Details nvarchar(200),
		Level3Name nvarchar(200),
		Level3Details nvarchar(200),
		Level4Name nvarchar(200),
		Level4Details nvarchar(200),
		Level5Name nvarchar(200),
		Level5Details nvarchar(200)
	)
	select @Count=count(*) from #EMPLEVEL
	while(@Count>=@loop)
		begin
			Set @SQLStr=''
			declare @EmpID nvarchar(20),@LoopLevelID bigint
			Select @EmpID=EMPLOYEE_CODE_ID,@LoopLevelID=LEVELID from #EMPLEVEL where id=@loop
			select @SQLStr=dbo.Func_TA_LoadSpace(@EmpID,@LoopLevelID,'#Emptest')
			execute(@SQLStr)
			Set @loop=@loop+1
		end
	
	--select * from #Emptest

	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			--updated by velumani for Abraj Monthly attendance design issue
			--case when vp.INTIME='00:00' then '' else vp.INTIME end,
			--case when vp.OUTTIME='00:00' then '' else vp.OUTTIME end,
			--vp.SHIFT_ID,
			--case when vp.HRSWORK='00:00' then '' else vp.HRSWORK end,
			(case when  vp.INTIME is null or vp.INTIME='00:00'  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME='00:00' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK='00:00' then null else vp.HRSWORK end) as HRSWORK,
		-------------------------
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX('.',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode='Holiday' and ANAttendanceCode='Holiday' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude,'00:00',0,#EMPLEVEL.LEVELID
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= 'HOLIDAY' AND vp.ANATTENDANCECODE= 'HOLIDAY'))))
		AND ((INTIME IS NOT NULL OR not(INTIME='00:00')) OR (OUTTIME IS NOT NULL OR not(OUTTIME='00:00')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= 'WEEKLY OFF' AND vp.ANATTENDANCECODE= 'WEEKLY OFF') OR (vp.SHIFT_ID= -1)))
	)

	create table #Onduty(
		EMPLOYEE_CODE_ID VARCHAR(20),	
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		ManualTimeEntry_InDate datetime,
		ManualTimeEntry_OutDate datetime)
	insert into #Onduty
	Select ManualTimeEntry_Employee_Id,ManualTimeEntry_InTime,ManualTimeEntry_OutTime,ManualTimeEntry_InDate,ManualTimeEntry_OutDate from TA_Tbl_ManualTimeEntry where (ManualTimeEntry_InDate between convert(datetime, cast(@local_FROMDAT as nvarchar(11)) , 101) and convert(datetime, cast(@local_TODAT as nvarchar(11)) ,101) or ManualTimeEntry_OutDate between convert(datetime,cast(@local_FROMDAT as nvarchar(11)) , 101) and convert(datetime, cast(@local_TODAT as nvarchar(11)),101)) and IsOnDuty=1 and ManualTimeEntry_Status='Approved' and Isdeleted=0
	--Select * from #Onduty
	update T set 
	T.OD_Time=CONVERT(varchar(5),DATEADD(minute,DATEDIFF(MINUTE,(ManualTimeEntry_InDate + OD.INTIME),(ManualTimeEntry_OutDate + OD.OUTTIME)), 0), 114),
	T.Tot_OD_Mins=DATEDIFF(MINUTE,(ManualTimeEntry_InDate + OD.INTIME),(ManualTimeEntry_OutDate + OD.OUTTIME))
	from #TEMPPROCESSEDDATA T inner join #Onduty OD on T.EMPLOYEE_CODE_ID=OD.EMPLOYEE_CODE_ID and cast(T.DATE as date)=cast(OD.ManualTimeEntry_InDate as date)

	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE='CL' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='PM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='AM' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)='AM' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)='PM' AND PD.OUTTIME>'00:00 AM' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,'00:00'))
	if(@TOTALMIN='') set @TOTALMIN=0
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		Day_Name varchar(25),
		OD_Hours nvarchar(20),
		Tot_OD_Mins int,
		EmpLevelID int
	)	
	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	CASE	WHEN PD.FNATTENDANCECODE='PRESENT' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,'FN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION='M' then ' #' else '' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE ='PRESENT' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,'AN',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '' ELSE '(BL)' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION='M' then ' #' else '' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,'&AMP;','&') AS BRANCHNAME,
	REPLACE(T.TITLENAME,'&AMP;','&') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE='WEEKLY OFF' AND ANATTENDANCECODE='WEEKLY OFF' THEN	'-' 
			WHEN PD.FNATTENDANCECODE='HOLIDAY'OR ANATTENDANCECODE='HOLIDAY' THEN '-'
			ELSE PD.SUPPOSEDWORKHOURS 
	END 'SUPPOSEDWORKHOURS',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN 'BL' THEN ' - ' ELSE '' END + ISNULL(PD.STATUS,'')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),0,CHARINDEX(':',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,'00:00'),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE PD.SHIFT_ID WHEN '-1' THEN 'WEEKLY OFF' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN '-' 
				 WHEN PD.SHIFT_ID=-1 THEN '-'
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),'00:00'
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'NORMOTMINS',
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'WEEKOFFOTMINS',
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS 'HOLIDAYOTMINS',
	CASE WHEN ISNULL(NORMOT,'00:00')='00:00' THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX(':',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = 'HOLIDAY') OR (PD.ANATTENDANCECODE = 'HOLIDAY')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX(':',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN '-' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	'00:00',
	'00:00',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+'/'+
			CASE	WHEN ANATTENDANCECODE in('Present','Absent','Weekly Off','Holiday') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,'00:00')='00:00'	THEN '00:00' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!='Approved' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude,Format(PD.DATE,'dddd') ,PD.OD_Time,PD.Tot_OD_Mins,PD.EmpLevelID
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME='Superadmin' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'')='' or dbo.ConvertHoursToMinites(isnull(HRSWORK,'00:00'))>=@TOTALMIN)
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	IF(@EXPORT=0)
	BEGIN
		SELECT	
		T.EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),' ','-') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME='WEEKLY OFF' THEN 'OFF' ELSE T.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,'0'))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'' as Intime1,
		'' as OutTime1,		 
		'' as Intime2,
		'' as OutTime2,
		'' as Intime3,
		'' as OutTime3,
		'' as Intime4,
		'' as OutTime4,
		'' as Intime5,
		'' as OutTime5,
		'' as AcutalWorkedHours,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ ' : ' +left(datename(MONTH,DATE),15),ATTENDANCE,Day_Name,OD_Hours,Tot_OD_Mins,EmpLevelID,dbo.Func_TA_GetOrganizationNamedetails(EmpLevelID) As EmployeeLevelDetails,Level1Name,Level1Details,Level2Name,Level2Details,Level3Name,Level3Details,Level4Name,Level4Details,Level5Name,Level5Details
		FROM #TEMPMONTHLYATTENDANCE T Inner join #Emptest ET on T.EMPLOYEE_ID=ET.EmployeeId ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	drop table #Onduty
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	
	drop table #Emptest
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil Proc_TA_RptTemporaryShift '05/01/2011','','','','','','SuperAdmin','','',323,0,'Both'
-- ALTER  date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptTemporaryShift]  
(
	@fromDate datetime,	
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@EmployeeName varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
    @ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @shift int,
	@EmpAutoId bigint			          
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
    insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Temporary table's creation
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
			--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
		--Employee Level insert in Temporary table
		insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) ELevel
		inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
		--Employee Designation insert in Temporary table
		insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
		--Employee Type insert in Temporary table
		insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
		--Employee Category insert in Temporary table
		insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		----Employee Pay insert in Temporary table
		--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
		--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
		--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
		--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
		--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
		--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''
			set @sqlQuery = @sqlQuery + ' SELECT     dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''&amp;'',''&'')+ '' ('' + TA_Tbl_Shift.Shift_Starttime +'' - '' + TA_Tbl_Shift.Shift_endtime + '')'' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''') + Space(1) + '
            set @sqlQuery = @sqlQuery + ' isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') as empname, replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, replace(dbo.TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,dbo.TA_Tbl_Employee.Gender ' 
			set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation LEFT OUTER JOIN'
            set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN'
            set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id'
			set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '
			set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
			set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id '
       		set @sqlQuery = @sqlQuery + ' Inner join dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'      
			set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
			set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id '
			set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN'
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
			--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
			--set @sqlQuery = @sqlQuery + ' inner JOIN dbo.TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId '
			--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
            set @sqlQuery = @sqlQuery + ' WHERE (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'
			set @sqlQuery = @sqlQuery + ' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0'
		if(@UserGroupName<>'SuperAdmin')
			begin
				SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
			end
		if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		END
		If Not (@EmpSwipeCard = '')  
			Begin  
				  Set @sqlQuery = @sqlQuery + 'And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			End  
		if not(@EmployeeId='')  
			begin  
				set @sqlQuery = @sqlQuery + 'and (ta_tbl_Employee.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
			end 
		if not(@EmployeeName='')  
			begin  
				set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' +  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
			end  
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
			end
		if(@DesignationID<>0)
			begin
			   set @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
			end	
	    if(@Gender<>'Both')
			begin
			   set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
			end	
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  ' And  TA_Tbl_Shift.Shift_Id = ' +  cast(@shift  as nvarchar(20))  
			end
		set @sqlQuery = @sqlQuery + ' order by TA_Tbl_Employee.Employee_Code_Id' 
exec (@sqlQuery)
--Remove the temporary tables here
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShit]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		senthil
-- Create date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_RptTemporaryShit]
(
	@fromDate datetime,	
	@LevelID varchar(18) 
)
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''
					  set @sqlQuery = @sqlQuery + ' SELECT     
dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId, dbo.TA_Tbl_Shift.Shift_ShortName, dbo.TA_Tbl_Employee.Employee_FirstName + 
Space(1) + '
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee.Employee_LastName as empname, 
dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName'
					  set @sqlQuery = @sqlQuery + ' FROM         dbo.TA_Tbl_TemporaryShiftAllocation 
INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast 
(day(@fromDate) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = 
dbo.TA_Tbl_Employee.Employee_Id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = 
dbo.Ta_Tbl_levelDetails.id INNER JOIN'
                      set @sqlQuery = @sqlQuery + ' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = 
dbo.TA_Tbl_Title.TitleId'
					  set @sqlQuery = @sqlQuery + ' WHERE     (dbo.TA_Tbl_TemporaryShiftAllocation.Year 
=' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) 
as nvarchar(10)) + ')'
if not(@LevelID='' or @LevelID='0')
		begin
					set @sqlQuery = @sqlQuery + ' and ta_tbl_Employee.LevelId = ' + cast (@LevelId as 
nvarchar(50)) 
		end	
END
exec (@sqlQuery)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTempShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 
Procedure Name : Proc_TA_RptTempShiftAllocation  '2015/06/01','2015/06/30','','','','','','SuperAdmin','','',0,0,'Both',1
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07 
Modified by : sashma
Modified on : 12-May-2011    */  
CREATE PROCEDURE [dbo].[Proc_TA_RptTempShiftAllocation]  
(
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @Religion int,
 @EmpAutoId bigint
)	
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	--create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) AS LevelId
--Select * from #LevelRights
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level INSERT in Temporary table
	--INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	--SELECT max(el.EffectiveDate) AS EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 GROUP by EmployeeId) ELevel
	--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpLevel select * from [Func_TA_EmpLevel] (@ToDat,@EmpSwipeCard)
	--Select * from #EmpLevel
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	SELECT max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type INSERT in Temporary table
	INSERT INTO #EmpType SELECT EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	SELECT max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category INSERT in Temporary table
	INSERT INTO #EmpCategory SELECT EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	SELECT max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)   and ECategory.CategoryId is not null
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	declare @sqlQuery AS varchar(8000)  
	SET @sqlQuery=''  
	SET @sqlQuery = 'SELECT e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''') AS Employee_FirstName,e.employee_code_id AS employee_id,ts.Year,ts.Month,ts.Day1Shift,ts.Day2Shift,ts.Day3Shift,ts.Day4Shift,ts.Day5Shift,ts.Day6Shift,ts.Day7Shift,ts.Day8Shift,ts.Day9Shift,ts.Day10Shift,ts.Day11Shift,ts.Day12Shift,ts.Day13Shift,ts.Day14Shift,ts.Day15Shift,ts.Day16Shift,ts.Day17Shift,ts.Day18Shift,ts.Day19Shift,ts.Day20Shift,ts.Day21Shift,ts.Day22Shift,ts.Day23Shift,ts.Day24Shift,ts.Day25Shift,ts.Day26Shift,ts.Day27Shift,ts.Day28Shift,ts.Day29Shift,ts.Day30Shift,ts.Day31Shift,ts.emp_id,ts.TimeStamp,ts.DateShift,TA_Tbl_Title.TitleName AS TitleName,e.Gender from TA_Tbl_TemporaryShiftAllocation ts inner join TA_Tbl_Employee e on e.Employee_Id=ts.EmployeeId '
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	SET @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId '	
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id '
		End
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id '
		End
	SET @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.employee_Status=1 and e.Report_exclude=0 '  
	SET @sqlQuery=@sqlQuery + ' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat AS nvarchar(20)) + ''', 102)) AS nvarchar(20))+''/''+ cast(1 AS nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat AS nvarchar(20)) +''', 102 ))AS nvarchar(10)),102) '
	SET @sqlQuery=@sqlQuery + ' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat AS nvarchar(20)) + ''', 102)) AS nvarchar(20))+''/''+ cast(1 AS nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat AS nvarchar(20)) + ''', 102 ))AS nvarchar(10)),102)'
	--if not(@EmployeeName='')  
	--	BEGIN  
	--		SET @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName + '' '' +  isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' AS nvarchar(100)) + ''')'
	--	END
	If Not (@EmpSwipeCard = '')  
		BEGIN  
			Set @sqlQuery = @sqlQuery + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
	--if not(@EmployeeId='')  
	--	BEGIN  
	--		SET @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId AS nvarchar(100)) + ''')'  
	--	END  
	if(@Gender<>'Both')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender AS nvarchar(8)) + ''' '
		END	
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID AS nvarchar(8))
		END	
	if(@UserGroupName<>'SuperAdmin')
		BEGIN
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpType.TypeId = ' + cast(@employeeType AS nvarchar(8))
		END		
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + ' and #EmpCategory.CategoryId = ' + cast(@employeeCategory AS nvarchar(8))
		END
	IF(@Religion!=1)
		BEGIN
			SET @sqlQuery=@sqlQuery+' AND e.Religion = '+cast(@Religion as varchar(50))+' '
		END
		if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
	  END
	SET @sqlQuery = @sqlQuery + ' order by e.employee_code_id,e.Employee_FirstName,ts.Year,ts.Month'   
	exec(@sqlQuery)  
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTimeSheet]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan
-- Create date: <2020-Jun-04>
-- Description:	<Description,,>
--
/*
Proc_TA_RptTimeSheet @fromDat='2020-07-01 00:00:00',@ToDat='2020-07-27 00:00:00',
@EmployeeName=N'',@LevelID=N'0,1',@EmployeeId=N'4',@employeeCategory=0,@employeeType=0,@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@ParentId=1,@DesignationID=0,@Gender=N'Both',@EmpAutoId=0,@IsExport=0,@status='All'
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptTimeSheet] 
	-- Add the parameters for the stored procedure here
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000), 
	 @EmployeeId varchar(max),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(20),
	 @GradeLevel varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @EmpAutoId bigint,	 
	 @IsExport int=0,
	 @status varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	set @dateFormat =(Select DateFormat from Func_TA_GetDateTimeFormat())
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end

	declare @sqlQuery as varchar(8000)  
	set @sqlQuery='' 
	
	select 
		[Employee ID]=E.Employee_Code_Id,
		[Employee Name]=E.Employee_FirstName,
		Department=LD.name,
		Designation=D.TitleName,
		CategoryName=C.CategoryName,
		[Shift Date]=ShiftDate,
		[Project Name]=P.Project_Name,
		[Task Name]=PT.TaskName,
		[Task Description]=TP.TaskDescription,
		[Task Hours]=PT.TaskHours,
		[Spent Hours]=case when TP.Status='Approved' then TPS.ApprovedHours else  TP.SpentHours end,
		[Approved By]=(select ie.Employee_FirstName from ta_tbl_employee ie where employee_id in(case when TPS.ApprovedBy is null or TPS.ApprovedBy='' then TP.ApprovedBy1 else TPS.ApprovedBy end)),
		[Approved Date]=case when TPS.ApprovedBy is null or TPS.ApprovedBy='' then TP.ApprovedDate1 else TPS.ApprovedDate end,
		[Approved By]=
		case when TP.Status='Forwarded' then '' 
			when TP.Status='Approved' then  
		(select ie.Employee_FirstName from ta_tbl_employee ie where employee_id in(case when TPS.ApprovedBy is null or TPS.ApprovedBy='' then  TP.ApprovedBy2 else TPS.ApprovedBy end))
		end,
		[Approved Date]=case when TP.Status='Forwarded' then '' 
			when TP.Status='Approved' then
		case when TPS.ApprovedBy is null or TPS.ApprovedBy='' then TP.ApprovedDate2 else TPS.ApprovedDate end
		end,
		[Task Status]=TP.Status,
		TPS.ApprovedHours
	FROM TA_Tbl_Project P
	Inner join TA_tbl_ProjectTaskList PT on P.Project_Id=PT.ProjectID
	Inner join Ta_tbl_TaskProgressDetails  TP on (TP.TaskID=PT.TaskID and TP.ProjectID=PT.ProjectID)
	LEFT outer join ta_tbl_taskprogressStatus TPS on TP.TaskDetailID=TPS.TaskDetailID
	inner join TA_Tbl_Employee E on E.Employee_Id=TP.TaskSubmittedBy
	inner join #EmpLevel EL on E.Employee_Id=EL.EmployeeId
	Inner join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId
	inner join #LevelRights LR on LR.LevelId=LD.id
	inner join #EmpCategory EC on E.Employee_Id=EC.EmployeeId
	inner join #EmpType ET on E.Employee_Id=ET.EmployeeId
	inner join #EmpDesignation ED on E.Employee_Id=ED.EmployeeId
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId
	inner join TA_Tbl_Title D on D.TitleId=ED.DesignationId
	where E.Isdeleted=0 and E.Report_Exclude=0
	and (TP.ShiftDate>=@fromDat and TP.ShiftDate<=@ToDat)
	and (@status='All' or TP.Status=@status) 
	order by E.Employee_Code_Id,convert(datetime,ShiftDate),TP.Status
	
	
	select 
		[Employee ID]=E.Employee_Code_Id,
		[Employee Name]=E.Employee_FirstName,
		Department=LD.name,
		Designation=D.TitleName,
		CategoryName=C.CategoryName,
		[Shift Date]=ShiftDate,
		[Project Name]=P.Project_Name,
		[Spent Hours]=
		case when LEN(convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))/60))=1 then 
		'0'+convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))/60)
		else convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))/60)
		end +':'+
		case when LEN(convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))%60))=1 then 
		'0'+convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))%60)
		else 
		convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,'00:00')))%60)
		end,
		[Approved By1]=case when TPS.ApprovedBy is null or TPS.ApprovedBy='' then TP.ApprovedBy1 else TPS.ApprovedBy end,
		[Approved Date]=TP.ApprovedDate1,
		[Approved By1]=TP.ApprovedBy2,
		[Approved Date]=TP.ApprovedDate2,
		[Task Status]=TP.Status		
	FROM TA_Tbl_Project P
	Inner join TA_tbl_ProjectTaskList PT on P.Project_Id=PT.ProjectID
	Inner join Ta_tbl_TaskProgressDetails  TP on (TP.TaskID=PT.TaskID and TP.ProjectID=PT.ProjectID)
	LEFT outer join ta_tbl_taskprogressStatus TPS on TP.TaskDetailID=TPS.TaskDetailID
	inner join TA_Tbl_Employee E on E.Employee_Id=TP.TaskSubmittedBy
	inner join #EmpLevel EL on E.Employee_Id=EL.EmployeeId
	Inner join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId
	inner join #LevelRights LR on LR.LevelId=LD.id
	inner join #EmpCategory EC on E.Employee_Id=EC.EmployeeId
	inner join #EmpType ET on E.Employee_Id=ET.EmployeeId
	inner join #EmpDesignation ED on E.Employee_Id=ED.EmployeeId
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId
	inner join TA_Tbl_Title D on D.TitleId=ED.DesignationId
	where E.Isdeleted=0 and E.Report_Exclude=0
	and (TP.ShiftDate>=@fromDat and TP.ShiftDate<=@ToDat)
	and (@status='All' or TP.Status=@status) 
	group by E.Employee_Code_Id,E.Employee_FirstName,LD.name,D.TitleName,C.CategoryName,P.Project_Name,TP.ApprovedBy1,
	TP.ApprovedDate1,TP.ApprovedBy2,TP.ApprovedDate2,TP.Status,convert(datetime,ShiftDate),ApprovedBy
	order by E.Employee_Code_Id,convert(datetime,ShiftDate),TP.Status
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalDaysWorked]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_RptTotalDaysWorked '07/01/2010','12/30/2011','','0','','0','0','','SuperAdmin','0','',0,0,'Both','ExcludingOD'
-- Proc_TA_RptTotalDaysWorked '2015/04/01','2015/04/30','manikandan,','0','','0','0','','SuperAdmin','0','',0,0,'Both','IncludingOD'
CREATE   PROCEDURE [dbo].[Proc_TA_RptTotalDaysWorked] 
(
    @fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@NoOfDays int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@TotalDays varchar(50),
	@EmpAutoID int
)
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,Attendance nvarchar(20),TotalDays numeric(18, 1),ANAttendanceCode nvarchar(15),FNAttendanceCode nvarchar(15),HRSWORK nvarchar(25))
--#TempProcessedData Indexes
/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
(
	[Employee_Code_Id] ASC
) ON [PRIMARY]
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
		Declare @sqlEmpLevel nvarchar(4000)
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDat as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id '
		End
	Execute(@sqlEmpLevel)
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	--select * from #TempEmployee
	 Declare @sqlTempProcessedData varchar(8000)
Declare @sqlTempProcessedData1 varchar(8000)
set @sqlTempProcessedData=	
	'insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.TotalDays,TA_Tbl_ProcessedData.ANAttendanceCode,TA_Tbl_ProcessedData.FNAttendanceCode,TA_Tbl_ProcessedData.HRSWORK 
	from TA_Tbl_ProcessedData 
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
    where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,'''+cast(@fromDat as nvarchar(50))+''', 102))  
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''+cast(@todat as nvarchar(50))+''', 102)) 
	AND TA_Tbl_ProcessedData.attendance=''Present'''
	--select * from #TempProcessedData
	Execute(@sqlTempProcessedData)	
	create table #Tempfinal(Employee_Id nvarchar(15),empName nvarchar(150),BranchName nvarchar(250),Designation nvarchar(250),[Total Days Worked1] decimal(18,1),[Total Days Worked] decimal(18,1),Gender varchar(10))
		Begin
		if(@NoOfDays='' or @NoOfDays=0)
		set @NoOfDays=1
		End
		declare @sqlQuery as varchar(8000)
		declare @sqlQuery1 as varchar(8000)
		set @sqlQuery=''
		set @sqlQuery1 = ''
		set @sqlQuery = 'insert into #Tempfinal select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'')  as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,sum(pd.TotalDays) as "Total Days Worked1"  ' 
		set @sqlQuery = @sqlQuery + ' ,''Total Days Worked'' = sum( CASE FNAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays end else 0 END) + sum( CASE ANAttendanceCode WHEN ''Present'' THEN Case TotalDays When ''1.0'' Then ''0.5'' Else TotalDays END  else 0 END),e.Gender'
		set @sqlQuery = @sqlQuery + ' from Ta_Tbl_Employee e inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	    set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '
		set @sqlQuery = @sqlQuery + ' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'
		SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId' 
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
		--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		--set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '
		--set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	    --set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	    --set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
	    --set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
		--set @sqlQuery = @sqlQuery + ' inner JOIN dbo.TA_Tbl_EmployeePay ON e.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId '
		--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		--set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	    set @sqlQuery = @sqlQuery + ' where  (	e.Employee_Status = 1 or 
	(e.Employee_Status = 0 and  convert(varchar(11), e.InActiveDate,102) >= convert(varchar(11),pd.Date,102))) 
	AND (e.Isdeleted = 0) AND (e.report_exclude = 0)' 
		if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
		--if(@employeeCategory<>0)
		--begin
		--	SET @sqlQuery1 = @sqlQuery1 + ' And #EmpCategory.CategoryId = ' +cast(@employeeCategory as nvarchar(8)) 
		--end
		--if(@employeeType<>0)
		--begin
		--	set @sqlQuery1 = @sqlQuery1 + ' And #EmpType.TypeId = ' +cast(@employeeType as nvarchar(8))
		--end
		--If Not (@EmpSwipeCard = '')  
		-- Begin  
		--	  Set @sqlQuery1 = @sqlQuery1 + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		-- End
		-- if(@DesignationID<>0)
		--	begin
		--	   set @sqlQuery1 = @sqlQuery1 + ' and EDesig.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		--	end	
		if(@Gender<>'Both')
			begin
			   set @sqlQuery1 = @sqlQuery1 + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
			end	
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		set @sqlQuery1 = @sqlQuery1 + ' Group by pd.Employee_Code_Id,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_LastName,TA_Tbl_LevelDetails.name,T.TitleName,e.Gender '
		set @sqlQuery1 = @sqlQuery1 + ' having count(pd.attendance)>= ''' + cast(@NoOfDays as nvarchar(10)) +  ''' order by e.Employee_FirstName,TA_Tbl_LevelDetails.name,T.TitleName ASC'	
	exec(@sqlQuery+@sqlQuery1)
	if(@TotalDays = 'IncludingOD')
	BEGIN
	   select Employee_Id,empName,BranchName,Designation,Gender,[Total Days Worked],[Total Days Worked1] from #Tempfinal
	END
	else if(@TotalDays = 'ExcludingOD')
	BEGIN
	  create table #Temp_OD 
	  (
		Employee_Code_Id nvarchar(15),
		ManualTimeEntry_InDate datetime,
		ManualTimeEntry_InTime varchar(15),
		ManualTimeentry_OutDate datetime,
		ManualtimeEntry_OutTime varchar(15),
		Shift_FirstHalf_StartTime varchar(15),
		Shift_FirstHalf_Endtime varchar(15),
		Shift_SecondHalf_StartTime varchar(15),
		Shift_SecondHalf_EndTime varchar(15),
		TotalDays decimal(18,1)
	 )
	 set @sqlTempProcessedData1=	
	 'insert into #Temp_OD select E.Employee_Code_Id,MTE.ManualTimeEntry_InDate,MTE.ManualTimeEntry_InTime,
	 MTE.ManualTimeentry_OutDate,MTE.ManualtimeEntry_OutTime,S.Shift_FirstHalf_StartTime,
	 S.Shift_FirstHalf_Endtime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,
	 case [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''FN'',S.Shift_StartTime,S.Shift_SecondHalf_StartTime,S.Shift_Endtime,E.isFlexible,S.Shift_id,pd.HRSWORK)
	 when '' (On Duty) '' then 0.5 else 0 end +
	 case [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''AN'',S.Shift_StartTime,S.Shift_SecondHalf_StartTime,S.Shift_Endtime,E.isFlexible,S.Shift_id,pd.HRSWORK)
	 when '' (On Duty) '' then 0.5 else 0 end
	 from TA_Tbl_ManualTimeEntry MTE
	 inner join TA_Tbl_Employee E  on E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id
	 inner join #Tempfinal on #Tempfinal.Employee_Id = E.Employee_Code_Id
	 inner join #TempProcessedData PD on PD.Employee_Code_Id = E.SwipeCardNo and PD.Date = MTE.ManualTimeEntry_InDate
	 inner join TA_Tbl_Shift S on S.Shift_Id = PD.Shift_Id
	 where IsOnDuty=1 and MTE.ManualTimeEntry_Status=''Approved'''
	 Execute(@sqlTempProcessedData1)
	 update #Tempfinal set #Tempfinal.[Total Days Worked] = (#Tempfinal.[Total Days Worked] - A.TotalDays)
	 from (select Employee_Code_Id,sum(TotalDays) as TotalDays from #Temp_OD 
     group by employee_Code_Id) as A
     inner join #Tempfinal on A.Employee_Code_Id = #Tempfinal.Employee_Id
     select * from #Tempfinal
     drop table #Temp_OD
	END   
--Remove the temporary tables here   
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
drop table #TempEmployee
drop table #Tempfinal
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalHoursList]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec Proc_TA_RptTotalHoursList '','01/Apr/2014','02/May/2014','id1','','107',0,0,'SuperAdmin','0',0,'0',107
-- exec Proc_TA_RptTotalHoursList @MinWorkHours='',@FromDate='01/Apr/2012',@ToDate='16/Apr/2013',@EmployeeID='',@EmployeeName='',@LevelID='3,5,11',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName='SuperAdmin',@GradeLevel='3',@EmpAutoId=0,@BreakLate = 0
CREATE  PROCEDURE [dbo].[Proc_TA_RptTotalHoursList]
(
@MinWorkHours as varchar(10),
@FromDate VarChar(50), 
@ToDate VarChar(50), 
@EmployeeID VarChar(50), 
@EmployeeName varchar(50),
@LevelID VarChar(1000),
@EmployeeCategory int,
@EmployeeType int,
@UserGroupName varchar(20),
@GradeLevel varchar(20),
@EmpAutoId bigint,
--@LateHrs VARCHAR(5) = '00:00',
@BreakLate VARCHAR(1) = '1',
@ParentID INT,
--Added newly for PRODUCT Migration by Manjula.P on 06-May-2014
@DesignationID int,
@Gender varchar(10)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level Indexes
--Index was grouped by manikandan.R on 08-05-2014
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	Declare @SelectSQL As Varchar(MAX)
	Set @EmployeeName = @EmployeeName + '%'
	Set @SelectSQL = ' '  
--Covert Minimum hours into Minutes
		declare @pos as int
		set @pos = charindex(':',@MinWorkHours)
		declare @TotalMin as int
		set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)
	Set @SelectSQL = @SelectSQL + ' SELECT Process_Rec_ID, CardNo, [Employee Name], Designation, [Level Name], [Date], Shift_StartTime, InTime, OutTime,LateBy, LateInMins, BreakOut, BreakIn, '
	--Set @SelectSQL = @SelectSQL + ' CAST(CAST((CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''00:00'', [LunchHrs]))/ 60 AS VARCHAR)) < 0 THEN ''0'' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''00:00'', [LunchHrs]))/ 60 AS VARCHAR)) END) + '':'' + (CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''00:00'', [LunchHrs]))% 60 AS VARCHAR)) < 0 THEN ''0'' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''00:00'', [LunchHrs]))% 60 AS VARCHAR)) END) AS TIME) AS VARCHAR(5)) AS BreakLate, '
	Set @SelectSQL = @SelectSQL + '  BreakLate,BreakLateMins, '
	--Set @SelectSQL = @SelectSQL + ' (CASE WHEN BreakLateMins != 0 THEN BreakLateMins 
	--									  WHEN (BreakLateMins - ([LunchHrsMins])) < 0 THEN 0 
	--                                      ELSE (BreakLateMins - ([LunchHrsMins])) END) AS BreakLateMins, '
	--Set @SelectSQL = @SelectSQL + ' (CASE WHEN BreakLateMins = 0 THEN TotalLate ELSE (CAST(CAST((CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''00:00'', [LunchHrs]))/ 60 AS VARCHAR)) < 0 THEN ''0'' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''00:00'', [LunchHrs]))/ 60 AS VARCHAR)) END) + '':'' + (CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''00:00'', [LunchHrs]))% 60 AS VARCHAR)) < 0 THEN ''0'' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''00:00'', [LunchHrs]))% 60 AS VARCHAR)) END) AS TIME) AS VARCHAR(5))) END) AS TotalLate, '
	Set @SelectSQL = @SelectSQL + ' (CASE WHEN BreakLateMins = 0 THEN TotalLate ELSE cast(cast(DATEADD(mi, ((TotalLateMins)), ''00:00'') as time) as varchar(5)) end) AS TotalLate, '
	Set @SelectSQL = @SelectSQL + '  TotalLateMins '
	Set @SelectSQL = @SelectSQL + ' FROM ( '
	Set @SelectSQL = @SelectSQL + ' SELECT PD.Process_Rec_ID,ED.SwipeCardNo AS CardNo, '
	Set @SelectSQL = @SelectSQL + ' ED.Employee_FirstName + '
	Set @SelectSQL = @SelectSQL + ' case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) else '' '' end + ED.Employee_LastName AS ''Employee Name'', '
   	Set @SelectSQL = @SelectSQL + ' T.TitleName AS Designation, '
	set @SelectSQL = @SelectSQL + ' Ta_Tbl_levelDetails.name AS ''Level Name'','	   	
	Set @SelectSQL = @SelectSQL + ' Date AS Date,Sft.Shift_StartTime,InTime,OutTime,LateIn as LateBy,LateInMins,Right(PD.BreakOut,11) as BreakOut,Right(PD.BreakIn,11) as BreakIn, PD.BreakLate,PD.BreakLateMins, PD.TotalLate, PD.TotalLateMins, PD.LateEntryReason, '
	Set @SelectSQL = @SelectSQL + ' CAST(CAST(DATEADD(MI, DATEDIFF(MI, CAST(CAST(DATEADD(MI, DATEDIFF(MI, Sft.Shift_BreakStartTime2, Sft.Shift_BreakEndTime2), ''00:00'') AS TIME) AS VARCHAR(5)) ,ISNULL(SS.MaxLunchHours, ''00:40'')), ''00:00'') AS TIME) AS VARCHAR(5)) AS [LunchHrs], '
	Set @SelectSQL = @SelectSQL + ' DATEDIFF(MI, ISNULL(SS.MaxLunchHours, ''00:40''),CAST(CAST(DATEADD(MI, DATEDIFF(MI, Sft.Shift_BreakStartTime2, Sft.Shift_BreakEndTime2), ''00:00'') AS TIME) AS VARCHAR(5)) ) AS [LunchHrsMins] '
	Set @SelectSQL = @SelectSQL + ' FROM TA_Tbl_Employee ED '
	--Set @SelectSQL = @SelectSQL + ' CONVERT(varchar,Date ,106) AS Date,Sft.Shift_StartTime,InTime,LateIn as LateBy,LateInMins,Right(PD.BreakOut,11) as BreakOut,Right(PD.BreakIn,11) as BreakIn,PD.BreakLate,PD.BreakLateMins,PD.TotalLate,PD.TotalLateMins,PD.LateEntryReason FROM TA_Tbl_Employee ED '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON ED.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON ED.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN dbo.TA_Tbl_Title T ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = T.TitleId '
	set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId '
	set @SelectSQL = @SelectSQL + ' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId '		
	Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_ProcessedData PD ON ED.Employee_code_Id = PD.Employee_Code_Id ' 
	Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_Shift Sft ON PD.shift_id = Sft.Shift_Id '
    Set @SelectSQL = @SelectSQL + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON Sft.Level_Id = SS.CompanyId '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
   --set @sqlQuery = @sqlQuery + ' And (#EmpLevel.levelId In (' + @LevelID + '))'  
	set @SelectSQL = @SelectSQL + ' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId '
	Set @SelectSQL = @SelectSQL + ' Where (ED.Isdeleted = 0) AND (ED.Employee_Code_Id <> ''18000000'') and  ED.report_exclude=0 and ED.employee_status=1 '
	Set @SelectSQL = @SelectSQL + ' AND PD.TotalLate <> ''00.00'' And PD.TotalLate <> ''00:00'' And PD.TotalLate is not null And PD.TotalLate <> ''0'' '
	Set @SelectSQL = @SelectSQL + ' AND (PD.FNAttendanceCode =''Present'' or PD.ANAttendanceCode=''Present'') '
--	set @SelectSQL = @SelectSQL + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
--	set @SelectSQL = @SelectSQL + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
--	set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
--  set @SelectSQL = @SelectSQL + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'	    
	IF (@MinWorkHours <> '')
	BEGIN
		SET @SelectSQL = @SelectSQL + ' and PD.TotalLateMins >= ' + cast(@TotalMin as nvarchar(8))  
	END
	IF(@UserGroupName <> 'SuperAdmin')
	BEGIN
		SET @SelectSQL = @SelectSQL + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel 
		--+ ' AND (ED.Reporting_To =''' + cast(@EmpAutoId as varchar(30)) + ''' or ED.Leave_Sanc_Authority=''' + cast(@EmpAutoId as varchar(30)) +''') '
	END
	IF NOT (@EmployeeId = '' Or @EmployeeId = '0')
	BEGIN
		SET @SelectSQL = @SelectSQL + ' And ED.Employee_code_Id = ''' + @EmployeeID + ''' '
	END
	IF NOT (@EmployeeName = '') 
	BEGIN
		SET @SelectSQL = @SelectSQL + ' and (ED.Employee_FirstName + isnull(ED.Employee_LastName,'''') like ''' + cast(@EmployeeName + '%' as nvarchar(100)) + ''') '
	END
	IF NOT (@EmployeeCategory = 0)
	BEGIN
		SET @SelectSQL = @SelectSQL + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))
	END
	IF NOT (@EmployeeType = 0)
	BEGIN
		SET @SelectSQL = @SelectSQL + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))
	END
	--Adding Designationid and Gender filters as like from product : By Manjula.P on 06-May-2014
	if(isnull(@DesignationID,0)<>0)
		begin
			set @SelectSQL = @SelectSQL + ' and #EmpDesignation.DesignationId = ' + cast(@DesignationID as nvarchar(8))
		end
	if(isnull(@Gender,'Both')<>'Both')
		begin
			set @SelectSQL = @SelectSQL + ' and ED.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
	end
	--**************************************************************
	IF (@FromDate <> '')
	BEGIN
		SET @SelectSQL = @SelectSQL + ' And PD.Date >= ''' + @FromDate + ''' '
	END
	IF (@ToDate <> '')
	BEGIN
		SET @SelectSQL = @SelectSQL + ' And PD.Date <= ''' + @ToDate + ''' '
	END
	--IF(@EmpAutoId = 0)
	--BEGIN 
	--	IF  NOT (@LevelID ='' OR @LevelID = '0')  
	--	BEGIN
	--	   SET @SelectSQL = @SelectSQL + ' And (#EmpLevel.levelId In (' + @LevelID + ')) '  
	--	END
	--END
	IF(@EmpAutoId > 0)
    BEGIN
		SET @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
    END
	SET @SelectSQL = @SelectSQL + ' ) Tbl '
	--SET @SelectSQL = (CASE WHEN @BreakLate = '1' THEN @SelectSQL + ' WHERE (CASE WHEN (BreakLateMins - [LunchHrsMins]) < 0 THEN 0 ELSE (BreakLateMins - [LunchHrsMins]) END) != 0 ' ELSE @SelectSQL END)
		SET @SelectSQL = (CASE WHEN @BreakLate = '1' THEN @SelectSQL + ' WHERE (CASE WHEN (BreakLateMins) > 0 THEN 1 ELSE 0 END) != 0 ' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs != '00:00' OR @LateHrs != '00:00' THEN @SelectSQL + ' WHERE ' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs = '00:00' THEN @SelectSQL ELSE @SelectSQL + ' ((CAST(CAST(DATEADD(MI,DATEDIFF(MI, BreakOut, BreakIn),''00:00'') AS TIME) AS VARCHAR(5)))) >= ''' + @BreakLateHrs + '''' END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs != '00:00' AND @LateHrs != '00:00' THEN @SelectSQL + ' AND ' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @LateHrs = '00:00' THEN @SelectSQL ELSE (@SelectSQL + ' LateBy >= ''' + @LateHrs + '''') END)
	SET @SelectSQL = @SelectSQL + ' order by Date , Intime'
	EXEC(@SelectSQL)
	DROP TABLE #EmployeeIds
	drop table #LevelRights
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalWorkingDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		:	Manjula.P
Created Date	:	08-Jan-2014
Descriptions	:	Procedure created for newly genrated report for taking working days count
	Proc_TA_RptTotalWorkingDays '','E016','2024/03/01','2024/03/30','0',0,0,'SuperAdmin','0','',0,0,'Both',41
	or FNAttendanceCode=''RH''
*/
CREATE proc [dbo].[Proc_TA_RptTotalWorkingDays]
(
@employeeName nvarchar(max),
@EmployeeId varchar(max),
@FromDate datetime,
@ToDate datetime,
@levelId varchar(8000),
@employeeCategory int,
@employeeType int,
@UserGroupName varchar(250),
@GradeLevel varchar(20),
@EmpSwipeCard varchar(20),
@ParentId int,
@DesignationID int,
@Gender varchar(10),
@EmpAutoID int
)
as
begin
	--Declaring variables 
	SET NOCOUNT ON;
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''
	declare @LeaveType as nvarchar(max)
	SELECT @LeaveType =COALESCE(@LeaveType + ',''','''')+LeaveType+'''' FROM TA_Tbl_LeaveType 
	set @LeaveType=COALESCE(@LeaveType + ',''','''')+'Comp Off'+''''+',''BL'+''''+',''LOP'+''''+',''RH'+''''
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''
	if(@EmployeeId is not null and @EmployeeId <> '')
	BEGIN
		CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
		INSERT INTO #EmployeeID
		SELECT * from SplitupEmployeeCode(@EmployeeId)
	end
	if(@EmployeeName is not null and @EmployeeName <> '')
	BEGIN
		CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
		INSERT INTO #EmployeeName
		SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
	end
	if(@Gender<>'Both')  
	begin  
		set @sqlCommon = @sqlCommon + ' and Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '  
	end	
	set @sqlEmpLevel=
	'insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 '
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,'''+cast(@ToDate as nvarchar(50))+''', 102) and EL.LevelId is not null'	
	If Not (@EmployeeId = '')  
	BEGIN  
		SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id '
	End
	If Not (@EmployeeName = '')  
	BEGIN  
		SET @sqlEmpLevel = @sqlEmpLevel + ' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.SwipeCardNo '
	End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @ToDate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @ToDate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @ToDate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--Created temp table for getting below dynamic query
	create table #TempTotalWorkingDays
	(
		Employee_Code_Id nvarchar(50),
		UserName nvarchar(50),
		Weekday float,
		WeeklyOff float,
		Holiday float,
		Leave float,
		LeaveType nvarchar(10),
		name nvarchar(500)
	)
	set @sqlQuery='select E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '' '') + SPACE(1) + ISNULL(E.Employee_LastName, '' '') AS UserName, '
	--Weekday count
	set @sqlQuery=@sqlQuery+'isnull(
	sum(case
	when  FNAttendanceCode=''Present'' and ANAttendanceCode=''Present'' and LPD.WeekDays=1 then 1 
	when FNAttendanceCode=''Present'' and ANAttendanceCode<>''Present'' and LPD.WeekDays=1 then 0.5
	when FNAttendanceCode<>''Present'' and ANAttendanceCode=''Present'' and LPD.WeekDays=1 then 0.5
	when FNAttendanceCode<>''Present'' and ANAttendanceCode<>''Present'' and LPD.WeekDays=1 then 0
	end),0) as Weekday,'
	--Weekly Off Count
	set @sqlQuery=@sqlQuery+'isnull(sum(case
	when  FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and LPD.WeekOff=1 then 1
	when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode<>''Weekly Off'' and LPD.WeekOff=1 then 0.5
	when FNAttendanceCode<>''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and LPD.WeekOff=1 then 0.5
	when FNAttendanceCode<>''Weekly Off'' and ANAttendanceCode<>''Weekly Off'' and LPD.WeekOff=1 then 0
	end ),0) as WeeklyOff,'
	--Holiday count
	set @sqlQuery=@sqlQuery+'isnull(sum(case
	when  (FNAttendanceCode=''Holiday'' ) and (ANAttendanceCode=''Holiday'' ) and LPD.Holidays=1 then 1
	when (FNAttendanceCode=''Holiday'' ) and (ANAttendanceCode<>''Holiday'')  and LPD.Holidays=1 then 0.5
	when (FNAttendanceCode<>''Holiday'' ) and (ANAttendanceCode=''Holiday'' )  and LPD.Holidays=1 then 0.5
	when (FNAttendanceCode<>''Holiday'' ) and (ANAttendanceCode<>''Holiday'')  and LPD.Holidays=1 then 0
	end ),0) as Holiday,'
	--Leave Count
	set @sqlQuery=@sqlQuery+'isnull(sum(case
	when  (FNAttendanceCode in ('+cast(@LeaveType as nvarchar(max))+') ) and (ANAttendanceCode in ('+cast(@LeaveType as nvarchar(max))+') )  and LPD.Leave=1 then 1
	when (FNAttendanceCode in ('+cast(@LeaveType as nvarchar(max))+') ) and (ANAttendanceCode not in ('+cast(@LeaveType as nvarchar(max))+') )  and LPD.Leave=1 then 0.5
	when (FNAttendanceCode not in ('+cast(@LeaveType as nvarchar(max))+') ) and (ANAttendanceCode in ('+cast(@LeaveType as nvarchar(max))+') )   and LPD.Leave=1 then 0.5
	when (FNAttendanceCode not in ('+cast(@LeaveType as nvarchar(max))+') ) and (ANAttendanceCode not in ('+cast(@LeaveType as nvarchar(max))+') )  and LPD.Leave=1 then 0
	end ),0) as Leave,'	
	--Leave type and joins tables
	set @sqlQuery=@sqlQuery+'LT.LeaveType,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name from TA_Tbl_ProcessedData P inner join TA_Tbl_Employee E on E.Employee_Code_Id=P.Employee_Code_Id
	inner join TA_Tbl_Emp_LeavePolicy EL on EL.EmployeeId=E.Employee_Id  
	and  CONVERT(DATETIME, ''' +cast( @FromDate as nvarchar(50))   + ''', 102) between EL.fromDate and EL.ToDate
	and  CONVERT(DATETIME, ''' +cast( @ToDate as nvarchar(50))   + ''', 102) between EL.FromDate and EL.ToDate
	inner join TA_Tbl_Emp_LeavePolicyDetails ELP on ELP.Emp_LeavePolicyId=EL.Emp_LeavePolicyId inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELP.Policy_ID
	inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=LP.Policy_Id and ELP.LeaveType_Id=LPD.LeaveType_Id inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LPD.LeaveType_Id and LT.CountFactor=1'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' WHERE ((E.Employee_Status = 1)	
	or(E.Employee_Status = 0 and  convert(varchar(11), E.InActiveDate,102)	>= 	convert(varchar(11),P.Date,102)))	AND (E.Isdeleted = 0) AND (E.report_exclude = 0)'
	set @sqlQuery = @sqlQuery + ' and ProcessFlag=1 and Date between CONVERT(DATETIME, ''' +cast( @FromDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast( @ToDate as nvarchar(50))   + ''', 102)' 
	--Checking whether the gender is both or others (Male,Female)
	if(@UserGroupName<>'SuperAdmin')
	begin
		set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	--Checking whether the employee code is empty or not  
	set @sqlQuery=@sqlQuery+' group by E.Employee_Code_Id,E.Employee_FirstName,E.Employee_LastName,LT.LeaveType,Ta_Tbl_levelDetails.name '
	Select @sqlQuery
	insert into #TempTotalWorkingDays
	exec(@sqlQuery);

	select Employee_Code_Id,UserName,Weekday,WeeklyOff,Holiday,LeaveType,Leave,(Weekday+WeeklyOff+Holiday+Leave) as TotalWorkingDays,name from #TempTotalWorkingDays
	--group by Employee_Code_Id,UserName,Weekday,WeeklyOff,Holiday,Leave
	drop table #TempTotalWorkingDays
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmployeeIds
	--drop table #EmpPay
	drop table #LevelRights	 
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWagesReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Senthil
-- Create date: 21-Apr-08
-- Description:	Wages Report
-- Proc_TA_RptWagesReport '26','','','','',''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptWagesReport]
	@MonthClosureID as nvarchar(5),
	@EmployeeId nvarchar(100),	
	@EmployeeName nvarchar(50),
	@EmpCategory nvarchar(50),
	@EmpType nvarchar(50),
	@LevelID nvarchar(1000)		
AS
BEGIN
	Declare @ToDate as DateTime
	set @ToDate = (select MonthClosure_EndDate from ta_tbl_monthclosure where MonthClosure_ID=@MonthClosureID)
	declare @sqlQuery as varchar(7000)
	set @sqlQuery = 'select TA_Tbl_Title.TitleName,TA_Tbl_PayrollProcessDetails.PayrollProcess_Id, TA_Tbl_PayrollProcessDetails.MonthClosure_Id, Ta_Tbl_Employee.Employee_Code_ID,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as EmployeeName,'
--	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.MonthlyWages + Isnull(TA_Tbl_PayrollProcessDetails.DA,0) as MonthlyWages,TA_Tbl_PayrollProcessDetails.WorkingDays,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.MonthlyWages ,TA_Tbl_PayrollProcessDetails.WorkingDays,'
--	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.AbsentDays + TA_Tbl_PayrollProcessDetails.LeaveDays as AbsentDays , TA_Tbl_PayrollProcessDetails.PaidHolidays, '
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.LeaveDays as AbsentDays , TA_Tbl_PayrollProcessDetails.PaidHolidays, '
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.PresentDays as WorkedDays, TA_Tbl_PayrollProcessDetails.Wages,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.Incentive,TA_Tbl_PayrollProcessDetails.GrossWages,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.PF, TA_Tbl_PayrollProcessDetails.ESI,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.Mess,TA_Tbl_PayrollProcessDetails.OtherDeductions,'
	set @sqlQuery = @sqlQuery + ' isnull(TA_Tbl_PayrollProcessDetails.Mess,0) + isnull(TA_Tbl_PayrollProcessDetails.OtherDeductions,0) + isnull(TA_Tbl_PayrollProcessDetails.PF,0) + isnull(TA_Tbl_PayrollProcessDetails.ESI,0) as TotalDeduction,'
	set @sqlQuery = @sqlQuery + ' TA_Tbl_PayrollProcessDetails.NetWages,'
	set @sqlQuery = @sqlQuery + ' RoundUp = Case (Cast(TA_Tbl_PayrollProcessDetails.NetWages as int)%10) when 0 Then TA_Tbl_PayrollProcessDetails.NetWages Else (TA_Tbl_PayrollProcessDetails.NetWages + (10 - (Cast (TA_Tbl_PayrollProcessDetails.NetWages as int) %10))) End'
	set @sqlQuery = @sqlQuery + ' from Ta_Tbl_employee inner join ta_tbl_payrollprocessDetails on Ta_Tbl_Employee.SwipeCardNo=ta_tbl_payrollprocessDetails.Employee_ID'
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on Ta_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
	set @sqlQuery = @sqlQuery + ' where (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0)'
    set @sqlQuery = @sqlQuery + ' And (ta_tbl_payrollprocessDetails.MonthClosure_ID=' + @MonthClosureID + ')'
	set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ta_tbl_Employee.Employee_Id and  EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
    set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
	if not(@EmpCategory='' or @EmpCategory='0')
	begin
		set @sqlQuery = @sqlQuery + 'and TA_Tbl_Employee.EmpCategory =''' + @EmpCategory + ''' '
	end
	if not(@EmpType='' or @EmpType='0')
	begin
		set @sqlQuery = @sqlQuery + 'and TA_Tbl_Employee.EmpType =''' + @EmpType + ''' '
	end
	if not(@EmployeeName='' or @EmployeeName='0')
	begin
		set @sqlQuery = @sqlQuery + 'and TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''' '
	end	
	if not (@EmployeeId='' or @EmployeeId='0')
	begin
		set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
	end
	if not(@LevelID='' or @LevelID='0')
	begin			
		set @sqlQuery = @sqlQuery + ' And (TA_Tbl_EmployeeLevel.levelId IN (' + @LevelID  + '))'
	end	
	exec(@sqlQuery)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 
exec Proc_TA_RptWeeklyWorkHours @FromDate=N'01/DEC/2023',@ToDate=N'20/DEC/2023',@EmployeeName=N'',
@LevelID=N'0',@EmployeeID=N'',@EmployeeCategory=0,@EmployeeType=0,@DesignationID=0,@Gender=N'BOTH',@UserGroupName=N'SuperAdmin',
@GradeLevel=N'0',@EmpSwipeCard=N'',@ParentId=0,@shift=0,@EmpAutoID=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours] 
@EmployeeId varchar(50),
@FromDate datetime, 
@ToDate datetime, 
@EmployeeName varchar(50), 
@LevelID varchar(8000),
@employeeCategory int,
@employeeType int,
@DesignationID INT,
@Gender VARCHAR(10),
@UserGroupName varchar(200),
@GradeLevel varchar(20), 
@EmpSwipeCard varchar(20),
@ParentId int,
@shift int = 0,
@EmpAutoID int
AS 
BEGIN 
	set nocount on
	IF(@EmployeeId IS NOT NULL AND @EmployeeId <> '')
	BEGIN
		CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
		INSERT INTO #EMPLOYEEID
		SELECT * FROM SPLITUPEMPLOYEECODE(@EmployeeId)
	END 
	IF(@EmployeeName IS NOT NULL AND @EmployeeName <> '')
	BEGIN
		CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
		INSERT INTO #EMPLOYEENAME
		SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EmployeeName,',')
	END	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID 
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType 
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory 
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @ToDate,@EmployeeId 
		declare @GetLevelID as int
		set @GetLevelID=(select top 1 LevelId from #EmpLevel)
		declare @Highlevel int
		DECLARE @childID INT 
		 ;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
			WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
		SELECT TOP 1 @Highlevel=p.id
		FROM ParentLevel r
		inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
		ORDER BY lvl DESC
		if(@Highlevel is null)
		begin
			set @Highlevel=@GetLevelID
		end
	create table #TempAttendanceDetails
	(
		SlNo int identity(1,1),
		WeekOrder nvarchar(50),
		WeekOrder1 nvarchar(50),
		WeekDayOrder int,
		Day nvarchar(50),
		FNAttendanceCode nvarchar(15),
		ANAttendanceCode nvarchar(15),
		Employee_Code_Id nvarchar(10),
		EmployeeName nvarchar(250),
		LevelName nvarchar(250),
		Designation nvarchar(250),
		Date datetime,
		InTime varchar(20),
		OutTime varchar(20),
		HrsWork varchar(20),
		TotalMinsWorked decimal(18,1),
		Shift_ShortName varchar(100),
		ShiftId int,
		shift_TotalWorkingHours nvarchar(50),
		Shift_FirstHalfWorkingHours nvarchar(50),
		Shift_SecondHalfWorkingHours nvarchar(50),
		LateIn varchar(50),
		LateInMins decimal(18,2),
		EarlyExit varchar(50),
		EarlyOutMins decimal(18,2),
		LessHrs nvarchar(50),
		DefinedWorkHours decimal(18,1), 
		CategoryId int, 
		CategoryName NVARCHAR(50), 
		MinWorkHours decimal(18,1),
		DailyWorkHrs nvarchar(18)
	)
	declare @sqlQuery_Detailed as nvarchar(MAX) 
	set @sqlQuery_Detailed='' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + 'select 
	case when DATEPART(dw,pd.date)= ss.CumulativeWeekStartDay then 
	convert(varchar(10),DATEPART(WEEK,pd.date)) 
	end ,
	convert(varchar(10),DATEPART(YEAR,date))+ ''Week''+convert(varchar(10),DATEPART(WEEK,date)) as ''WeekOrder'',DATEPART(dw,date)''WeekDayOrder'',DATENAME(DW,date) as ''Day'','
	set @sqlQuery_Detailed = @sqlQuery_Detailed + 'pd.fnAttendanceCode + case when Status is null then '''' else ''(BL)'' end as FNAttendanceCode,pd.anAttendanceCode + case when Status is null then '''' else ''(BL)'' end as ANAttendanceCode,'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + 'e.Employee_Code_Id,isnull(e.Employee_FirstName,'''') + space(1) + isnull(e.Employee_LastName,'''') as EmployeeName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as LevelName,replace(T.TitleName,''&amp;'',''&'') as Designation,'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + 'pd.date as Date,CASE when isnull(pd.InTime,''00:00'')=''00:00'' then ''-'' else pd.InTime end as ''InTime'',CASE when isnull(pd.OutTime,''00:00'')=''00:00'' then ''-'' else pd.OutTime end as ''OutTime'',ISNULL(pd.HrsWork, ''-'') as ''HrsWork'', ((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))) as TotalMinsWorked ,(shf.Shift_ShortName + '' ('' + shf.Shift_StartTime + '' - '' + shf.Shift_EndTime + '')'') as Shift_ShortName,'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + 'pd.shift_id as ShiftID,shf.shift_TotalWorkingHours,Shift_FirstHalfWorkingHours ,Shift_SecondHalfWorkingHours,pd.LateIn,pd.LateInMins,pd.EarlyOut as EarlyExit,pd.EarlyOutMins,pd.HrsLess,TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours,TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,DATEDIFF(MI, ''00:00'',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0)), ''.'', '':'')) as ''MinWorkHours'',TA_Tbl_Category.WeekDay_WorkHrs'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' from Ta_Tbl_Employee e '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeCategory on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'
	Set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner JOIN TA_Tbl_ShiftSettings SS ON ss.CompanyID=' + cast(@Highlevel as nvarchar(2)) + ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpType on #EmpType.EffectiveDate=ET.EffectiveDate and #EmpType.employeeid=ET.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ' 
	IF NOT (@EmployeeId = '') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner Join #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=#EmpLevel.Employee_Code_Id '
	END
	IF NOT (@EmployeeName = '') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner Join #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=#EmpLevel.Employee_Code_Id '
	END
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and ((pd.date >= CONVERT(DATETIME, ''' + cast(@FromDate as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@ToDate as nvarchar(11)) + ''', 102)))
	' 
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel 
	end 
	IF(@GENDER<>'BOTH') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + ' AND e.Gender = ''' + CAST(@GENDER AS NVARCHAR(8)) + ''' ' 
	END 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery_Detailed = @sqlQuery_Detailed + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If Not (@EmpSwipeCard = '') 
	Begin 
		Set @sqlQuery_Detailed = @sqlQuery_Detailed + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' ' 
	End
	if(@shift<>0) 
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And pd.Shift_Id=' + cast (@shift as nvarchar(50)) 
	end 
	if(@employeeCategory<>0)
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And ET.TypeId = ' + cast(@employeeType as nvarchar(8)) 
	end
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' and 
	(
	DATEPART(dw,pd.date) between 
	(
	case when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	when ss.CumulativeWeekStartDay<CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	when ss.CumulativeWeekStartDay=CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	end
	) 
	and 
	(
	case 
	when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then 7
	when ss.CumulativeWeekStartDay<CumulativeWeekEndDay then CumulativeWeekEndDay
	when ss.CumulativeWeekStartDay=CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	end
	)
	or 
	DATEPART(dw,pd.date) between 
	(
	case when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then 1
	end
	) 
	and 
	(
	case 
	when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then CumulativeWeekEndDay
	end
	)
	)
	' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' order by e.Employee_FirstName,cast(pd.date as datetime)' 
	-- exec(@sqlQuery_Detailed) 
	insert into #TempAttendanceDetails 
	exec(@sqlQuery_Detailed) 
	Create table #temptesting(id int identity(1,1),Weekdate int,Startdate datetime)
	insert into #temptesting
	select distinct WeekOrder,Date from #TempAttendanceDetails where WeekOrder is not null 
	Declare @count int
	Declare @StartDate datetime
	Declare @WeekNumber varchar(20)
	Declare @PreviousWeekNumber varchar(20)
	Declare @NextDate datetime
	set @count=(select COUNT(*) from #TempTesting) 
	Declare @i int
	set @i=1
	while @count>=@i
	begin 
		set @StartDate=(select convert(datetime,Startdate) from #TempTesting where id=@i) 
		set @WeekNumber=(select Weekdate from #TempTesting where id=@i) 
		if @i=1
		begin
			set @PreviousWeekNumber=@WeekNumber-1 
		end
		set @NextDate=(select convert(datetime,Startdate) from #TempTesting where id=@i+1) 
		if @StartDate is not null and @NextDate is not null
		begin 
			update #TempAttendanceDetails set WeekOrder=@WeekNumber where convert(datetime,Date) between
			@StartDate and dateadd(d,-1,@NextDate)
		end
		else
		begin 
			update #TempAttendanceDetails set WeekOrder=@WeekNumber from #TempAttendanceDetails where Date>=@StartDate
		end
		set @i=@i+1
	end
	update #TempAttendanceDetails set WeekOrder=@PreviousWeekNumber from #TempAttendanceDetails where WeekOrder is null
	SELECT
	WeekOrder,
	WeekDayOrder,
	Day,
	FNAttendanceCode,
	ANAttendanceCode,
	Employee_Code_Id,
	EmployeeName,
	LevelName,
	Designation,
	Date,
	InTime,
	OutTime,
	HrsWork as WorkingHours,
	TotalMinsWorked,
	Shift_ShortName,
	ShiftId,
	shift_TotalWorkingHours,
	Shift_FirstHalfWorkingHours ,
	Shift_SecondHalfWorkingHours ,
	LateIn,
	LateInMins,
	EarlyExit,
	EarlyOutMins,
	LessHrs,
	DefinedWorkHours, 
	CategoryId, 
	CategoryName, 
	MinWorkHours
	FROM #TempAttendanceDetails where ShiftId<>-1 and (fnAttendanceCode in ('Present','Absent') or anAttendanceCode in ('Present','Absent'))
	create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),DurWorkHrs decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATETIME)
	INSERT INTO #TempAttendanceSummary
	SELECT
	TA.Employee_Code_Id,
	TA.EmployeeName,
	TA.DefinedWorkHours,
	0,
	SUM(
	((
	(CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off')) THEN 1 ELSE 0.0 END)*
	((substring(isnull(TA.Shift_FirstHalfWorkingHours,'00:00'),0,3)*60) + (substring(isnull(ta.Shift_FirstHalfWorkingHours,'00:00'),4,2)))
	+ 
	(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off')) THEN 1 ELSE 0.0 END)*
	((substring(isnull(TA.Shift_SecondHalfWorkingHours,'00:00'),0,3)*60) + (substring(isnull(ta.Shift_SecondHalfWorkingHours,'00:00'),4,2)))
	))
	),
	0,
	SUM(CAST(TA.totalMinsWorked AS INT)),0,TA.CategoryName,CAST(MAX(TA.[Date]) AS DATETIME)
	FROM #TempAttendanceDetails TA
	INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
	GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName,C.WeekDay_WorkHrs
	update #TempAttendanceSummary set SupposedToWorkHours = DefinedWorkHours - (Convert(Decimal(18,1),Convert( Varchar(10), (cast(HoursToDeduct as INT)/60))+ '.' + Convert( Varchar(10),(cast(HoursToDeduct as INT)%60))))
	update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	select 
	Employee_Code_Id,
	EmployeeName,
	DefinedWorkHours,
	HoursToDeduct,
	SupposedToWorkHours,
	CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN '0' + cast((ActualWorkHours/60) as varchar(25)) ELSE cast((ActualWorkHours/60) as varchar(25)) END + ':' + CASE WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN '0' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
	CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN '0' + cast((LessHours/60) as varchar(25)) ELSE cast((LessHours/60) as varchar(25)) END + ':' + CASE WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN '0' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
	CategoryName,
	(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN '0' + CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END + '.' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid
	from #TempAttendanceSummary
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptMonthlyAttendance  
Created By		:	A.K.T.MOORTHI
Created on		:	05-Aprl-2013
Description		:	To Get the weekly work hours 
Updated By		:	A.K.T.MOORTHI
Updated on		:	26-Aug-2013
Description		:	To Get Daily ARMIS Work Hours 
exec [Proc_TA_RptWeeklyWorkHours_Angler] @FromDate=N'01/oct/2015',@ToDate=N'26/oct/2015',@EmployeeName=N'',@LevelID=N'904',@EmployeeID=N'',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N'SuperAdmin',@GradeLevel=N'1',@EmpSwipeCard=N'',@EmpAutoId=359,@ParentId=107,@shift=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]  
@FromDate datetime,  
@ToDate datetime,  
@EmployeeName varchar(50),  
@LevelID varchar(8000),
@EmployeeId varchar(50),
@employeeCategory int,
@employeeType int,
--Changed usergroup datatype length is 200 from 20 for data not loading : Bug : 0023839 
@UserGroupName varchar(200),
@GradeLevel varchar(20),	   
@EmpSwipeCard varchar(20),
@EmpAutoId bigint,
@ParentId int,
@shift int = 0
AS  
BEGIN  
	set nocount on
	--Get current date time format 
		DECLARE @dateFormat as int
		DECLARE @date as nvarchar(25)			
		SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
		IF(@date='dd/MM/yyyy')
			BEGIN
				SET @dateFormat = 103
			END
		ELSE IF(@date='MM/dd/yyyy')
			BEGIN
				SET @dateFormat = 101
			END
		ELSE
			BEGIN
				SET @dateFormat = 106
			END	
	--end
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)
	create table #LevelRights(LevelId int)
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
		[EffectiveDate],[PayId],[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
	select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
	inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpBpay
	inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
	AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EPay.PayId is not null
	DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
	create table #TempAttendanceDetails (FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),LevelName nvarchar(250),Designation nvarchar(250),Date VARCHAR(20),InTime varchar(20),OutTime varchar(20),HrsWork varchar(20),
	TotalMinsWorked varchar(20),Shift_ShortName varchar(100),ShiftId int,shift_TotalWorkingHours nvarchar(50),LunchHours varchar(50),DefinedWorkHours varchar(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId int, CategoryName NVARCHAR(50),thirdSat bit,DinnerHours varchar(50),
	ArmisMin BIGINT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10), MinWorkHours BIGINT, ToolTip VARCHAR(MAX))
	--Create table #TempLowergradeEmpDetails(id int identity(1,1),swipeCardNo varchar(50))
	--insert into #TempLowergradeEmpDetails 
	--select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0 and Employee_Id=@EmpAutoId
	--insert into #TempLowergradeEmpDetails
	--select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0 and(Reporting_To=@EmpAutoId or Leave_Sanc_Authority=@EmpAutoId)	
	--DECLARE @List VARCHAR(max)
	--SELECT @List = COALESCE(@List + ', ' + swipeCardNo, swipeCardNo)FROM #TempLowergradeEmpDetails
	--Declare @count int
	--Declare @Start int
	--set @Start=1
	--Declare @GetEmployeeid varchar(max)
	--if(@UserGroupName not in('Superadmin','Dy. Manager - HR'))
	--	begin
	--		set @count=(select count(*) from #TempLowergradeEmpDetails)			
	--		while @count>=@Start
	--			begin
	--				set @GetEmployeeid=(select swipeCardNo from #TempLowergradeEmpDetails where id=@Start)
	--				INSERT INTO @ArmisData
	--				SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) 
	--				FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, @GetEmployeeid)		
	--				set @Start=@Start+1
	--			end
	--	end
	--else
	--	begin
	--		INSERT INTO @ArmisData
	--		SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) 
	--		FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, null)
	--	end
	INSERT INTO @ArmisData
	SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) 
	FROM [ProjectManagementV3July16].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, NULL)
	--select * from @ArmisData
    declare @sqlQuery_Detailed as varchar(MAX)  
  	set @sqlQuery_Detailed=''  
  	set @sqlQuery_Detailed = 'select	pd.fnAttendanceCode + case  when Status is null then '''' else ''(BL)'' end as FirstSession,
  										pd.anAttendanceCode + case  when Status is null then '''' else ''(BL)'' end  as SecondSession, 
  										e.Employee_Code_Id as Employee_Id,
  										isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,replace(T.TitleName,''&amp;'',''&'') as Designation,case when '+CONVERT(varchar,@dateFormat) +'=106 then
									REPLACE(CONVERT(VARCHAR, pd.Date,'+CONVERT(varchar,@dateFormat)+'),'' '',''-'') 
									else CONVERT(VARCHAR, pd.Date, '+CONVERT(varchar,@dateFormat)+') end as Date,ISNULL(pd.InTime, ''-''),ISNULL(pd.OutTime, ''-''),ISNULL(pd.HrsWork, ''-''), ((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))) as TotalMinsWorked'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' ,(shf.Shift_ShortName + '' ('' + shf.Shift_StartTime + '' - ''  + shf.Shift_EndTime + '')'') as Shift_ShortName,pd.shift_id as ShiftID,shf.shift_TotalWorkingHours,ISNULL(pd.BreakHours, ''-'') as LunchHours, TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours, DATENAME(DW,pd.date), (CASE WHEN ((DATENAME(DW,pd.date) != ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END)'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' ,(CASE WHEN ISNULL(Pd.BreakIn, '''') <> '''' AND ISNULL(Pd.BreakOut, '''') <> '''' AND (DATEDIFF(MI, ISNULL(SS.MaxLunchHours, ''00:40''), ISNULL(REPLACE(pd.BreakHours, ''-'', ''''), ''00:00'')) > 0) THEN 1 ELSE 0 END),TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,0,DinnerHours, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')), ''00:00'', TBH.TotalBreakmin, (CASE WHEN (DATENAME(DW,pd.date) != ''Saturday'') THEN DATEDIFF(MI, ''00:00'',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0)), ''.'', '':'')) ELSE DATEDIFF(MI, ''00:00'',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''.5'', ''.3''), 0.0)), ''.'', '':'')) END), NULL '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' from Ta_Tbl_Employee e '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id'    	
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join ta_tbl_TotalBreakHours TBH on TBH.Employee_Code_Id=pd.Employee_Code_Id and TBH.Shiftdate=pd.date'  
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '	
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'   
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId'
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'
	Set @sqlQuery_Detailed = @sqlQuery_Detailed + ' LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpType on #EmpType.EffectiveDate=ET.EffectiveDate and #EmpType.employeeid=ET.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #EmpPay on #EmpPay.EffectiveDate=EP.EffectiveDate and #EmpPay.employeeid=EP.EmployeeId '
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '		
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and((pd.date >= CONVERT(DATETIME, ''' + cast(@FromDate as nvarchar(11)) + ''', 102) and pd.date <= CONVERT(DATETIME, ''' + cast(@ToDate as nvarchar(11)) + ''', 102)))'  
	if(@UserGroupName<>'SuperAdmin')
	begin
	SET @sqlQuery_Detailed = @sqlQuery_Detailed + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end	 
	if not(@EmployeeName='')  
		begin  
			set @sqlQuery_Detailed = @sqlQuery_Detailed + 'and (e.Employee_FirstName + '' '' +isnull(e.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end 
	if not(@EmployeeId='')  
		begin  
			set @sqlQuery_Detailed = @sqlQuery_Detailed + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
		end 
	If Not (@EmpSwipeCard = '')  
			 Begin  
			  Set @sqlQuery_Detailed = @sqlQuery_Detailed + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
			 End
	if(@shift<>0) 
			begin
				set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And pd.Shift_Id=' + cast (@shift as nvarchar(50))  
			end 
	if(@employeeCategory<>0)
		begin
			set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And ET.TypeId = ' + cast(@employeeType as nvarchar(8)) 
		end
  --  if(@EmpAutoId = 0)
	 --   BEGIN
		--	if not(@LevelID='' or @LevelID='0')  
		--	begin  
		--	   set @sqlQuery_Detailed = @sqlQuery_Detailed + ' And (#EmpLevel.levelId In (' + @LevelID + '))'  
		--	End
		--END
		--ELSE
		if(@EmpAutoId > 0)
			BEGIN
			   set @sqlQuery_Detailed = @sqlQuery_Detailed + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
			END
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ' order by e.Employee_FirstName,cast(pd.date as datetime)'   
	 insert into #TempAttendanceDetails exec(@sqlQuery_Detailed) 	
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins), 
			REPLACE(REPLACE((SELECT ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')' + (CASE WHEN LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')') < 160 THEN SPACE(160 - LEN(ISNULL(EntranceName, '') + ' ' + ISNULL(EntranceType, '') + ' (' + ISNULL(EntranceTime, '') + ') <=: [' + ISNULL(PunchDifference, '') + '] :=> ' + ISNULL(FloorName, '') + ' ' + ISNULL(FloorType, '') + ' (' + ISNULL(FloorTime, '') + ')')) ELSE '' END) FROM TA_VW_FirstInPunchDifference TT WHERE TT.EmployeeCodeId = FIP.EmployeeCodeId AND TT.[Date] = FIP.[Date] FOR XML PATH('')), '&gt;', '>'), '&lt;', '<') ToolTip
		FROM TA_VW_FirstInPunchDifference FIP WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date] 
	 HAVING SUM(PunchDifferenceMins) > 0
	Update #TempAttendanceDetails SET
		HrsWork =Case when ISNULL(AD.BreakHours,0)>0 THEN CASE WHEN LEN(CAST(((AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25))) = 1 THEN '0'+ CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25)) END Else HrsWork End,
	    TotalMinsWorked=Case When (ISNULL(AD.BreakHours,0)>0) Then AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT) Else TotalMinsWorked End	,
	    ValidWorkHrs = (CASE WHEN (ISNULL(AD.BreakHours,0)>0) THEN (CASE WHEN (ISNULL(MinWorkHours, 0)) > (AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT)) THEN 1 ELSE ValidWorkHrs END) ELSE ValidWorkHrs END),
		BreakHours=CASE WHEN LEN(CAST((BreakHours/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((BreakHours/60) AS VARCHAR(25)) ELSE  CAST((BreakHours/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((BreakHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((BreakHours%60) AS VARCHAR(25)) ELSE CAST((BreakHours%60) AS VARCHAR(25)) END
	From #TempAttendanceDetails AD
	UPDATE #TempAttendanceDetails SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN '00:00' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN '0' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN '0' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
		ExceptionHours = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN LEN(CAST((EH.TotalHrs/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((EH.TotalHrs/60) AS VARCHAR(25)) ELSE  CAST((EH.TotalHrs/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((EH.TotalHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((EH.TotalHrs%60) AS VARCHAR(25)) ELSE CAST((EH.TotalHrs%60) AS VARCHAR(25)) END) ELSE ExceptionHours END),
		ValidWorkHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN (ISNULL(MinWorkHours, 0)) > (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) THEN 1 ELSE ValidWorkHrs END) ELSE ValidWorkHrs END),
		ToolTip = EH.ToolTip
	FROM #TempAttendanceDetails AD
		RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
	 UPDATE #TempAttendanceDetails SET ValidWorkHrs = 0 where ValidWorkHrs = 1 and 
	 ((FNAttendanceCode not in ('Present','Absent','Holiday','Weekly Off') and ANAttendanceCode = 'Present')
	 or (ANAttendanceCode not in ('Present','Absent','Holiday','Weekly Off') and FNAttendanceCode = 'Present'))
	 and TotalMinsWorked >= 240
	 update #TempAttendanceDetails set ValidWorkHrs = 0 where HrsWork = '-' 
	 UPDATE #TempAttendanceDetails SET ArmisMin = ISNULL(AD.TotalMin, 0) FROM #TempAttendanceDetails TAD
		INNER JOIN @ArmisData AD ON AD.Employee_Code_Id = TAD.Employee_Code_Id AND CAST(AD.[Date] AS DATE) = CAST(TAD.[Date] AS DATE)
	 SELECT 
		FNAttendanceCode,
		ANAttendanceCode,
		Employee_Code_Id,
		EmployeeName,
		LevelName,
		Designation,
		[Date],
		InTime,
		OutTime,
		HrsWork,
		TotalMinsWorked,
		Shift_ShortName,
		ShiftID,
		shift_TotalWorkingHours,
		LunchHours,
		DefinedWorkHours,
		Day,
		ValidLunchHrs,
		ValidWorkHrs,
		ISNULL(DinnerHours,'-') AS DinnerHours,
		CASE WHEN LEN(CAST((ArmisMin/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((ArmisMin/60) AS VARCHAR(25)) ELSE  CAST((ArmisMin/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((ArmisMin%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisMin%60) AS VARCHAR(25)) ELSE CAST((ArmisMin%60) AS VARCHAR(25)) END AS ArmisHrs,
		ISNULL(ExceptionHours, '00:00') ExceptionHours,
		ISNULL(BreakHours, '-') BreakHours,
		ToolTip
	FROM #TempAttendanceDetails 
		WHERE [Day] != 'Sunday'
	 /*
	 To find Third saturday.
	 */
	 Declare @firstsat date
	 Declare @ThirdSat date
	 Select  @firstsat= dateadd(dd,(datediff(dd,-53685,dateadd(mm,datediff(mm,0,@ToDate),6))/7)*7,-53685)
	 Select @ThirdSat=DATEADD(dd,14,@firstsat)
	 Update #TempAttendanceDetails set thirdSat=1 where  #TempAttendanceDetails.Day='Saturday' and #TempAttendanceDetails.Date=@ThirdSat
	 create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATE, ArmisHrs BIGINT)
	 INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.DefinedWorkHours,
			SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
			0,
			SUM(CAST(TA.totalMinsWorked AS INT)),
			0,
			TA.CategoryName,
			CAST(MAX(TA.[Date]) AS DATE),
			SUM(ArmisMin)
		FROM #TempAttendanceDetails TA
			INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != 'Sunday'
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
	 update #TempAttendanceSummary set SupposedToWorkHours = (DefinedWorkHours - (HoursToDeduct))
	 update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	 update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	 select 
		Employee_Code_Id,
		EmployeeName,
		DefinedWorkHours,		
		HoursToDeduct,
	    SupposedToWorkHours,
		CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN '0' +  cast((ActualWorkHours/60) as varchar(25)) ELSE  cast((ActualWorkHours/60) as varchar(25)) END  + ':' + CASE  WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN '0' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
		CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN '0' +  cast((LessHours/60) as varchar(25)) ELSE  cast((LessHours/60) as varchar(25)) END  + ':' + CASE  WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN '0' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
		CategoryName,
		(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN '0' +  CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END  + '.' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid,
		CASE WHEN LEN(CAST((ArmisHrs/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((ArmisHrs/60) AS VARCHAR(25)) ELSE  CAST((ArmisHrs/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((ArmisHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisHrs%60) AS VARCHAR(25)) ELSE CAST((ArmisHrs%60) AS VARCHAR(25)) END AS ArmisHrs
	 from #TempAttendanceSummary
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpPay 
	drop table #EmpProcessedData
	drop table #EmployeeIds
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptYearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_RptYearClosure  '',4,'1','',0,0,'SuperAdmin','0','',4,0,'Both'
Tables  : TA_Tbl_Employee, TA_Tbl_YearClosure 
Created By : Prabakaran  
Created on : 15-Oct-07    
Modified by : sashma
Modified on : 12-May-2011 
-- Modified By : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description: Sql Query Optimization 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptYearClosure]  
(  
 @EmployeeName varchar(max),  
 @LevelID varchar(8000),
 @Year_SettingID varchar(20),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoId bigint
)		
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @toDate datetime
	set @toDate=GETDATE()
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @toDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @toDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @toDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @toDate,@EmployeeId	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
			if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''  
	set @sqlQuery = 'select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'')  as BranchName,replace(T.TitleName,''&amp;'',''&'')  as Designation,ys.StartMonth + space(1) + cast(ys.StartYear as nvarchar(4)) + ''-'' +  ys.EndMonth + space(1) + cast(ys.EndYear as nvarchar(4)) as YearSettingYear,lt.LeaveType,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Leave_Taken,yc.Available_Leaves,
    yc.Encashment,e.Gender,yc.LeaveTypeID,e.Employee_Id from Ta_Tbl_Employee e inner join ta_tbl_YearClosure yc  on e.Employee_Id=yc.Employee_Id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'   
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_YearSetting ys ON ys.YearSettings_Id=yc.Year_SettingID'  
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_LeaveType lt ON lt.LeaveType_Id=yc.LeaveTypeID'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '
	set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	If Not (@EmployeeName = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id '
		End
						If Not (@EmployeeId = '')  
		Begin  
			SET @sqlQuery = @sqlQuery + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id '
		End
	set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and lt.Isdeleted=0'  
	--If Not (@EmpSwipeCard = '')  
	--	Begin  
	--		Set @sqlQuery = @sqlQuery + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	--	End
	--if(@DesignationID<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + ' and EDesig.DesignationId = ' + cast(@DesignationID as nvarchar(8))
	--	end	
	--if not(@EmployeeId='')  
	--	begin  
	--		set @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id=''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
	--	end
	if(@Gender<>'Both')
		begin
			set @sqlQuery = @sqlQuery + ' and e.Gender = ''' + cast(@Gender as nvarchar(8)) + ''' '
		end  
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	if not(@Year_SettingID='' or @Year_SettingID='0')  
		begin  
			set @sqlQuery = @sqlQuery + ' And (ys.YearSettings_ID In (' + cast(@Year_SettingID as nvarchar(10)) + '))'  
		End
	--if(@employeeCategory<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
	--	end
	--if(@employeeType<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
	--	end
	set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName'   
	Create table #final(Employee_Id nvarchar(200),
		empName nvarchar(200),BranchName nvarchar(200),Designation nvarchar(200),YearSettingYear nvarchar(200),LeaveType nvarchar(20),Carry_PrevYear decimal(18,1),
		Current_Quota decimal(18,1),Borrow_NextYear decimal(18,1),Leave_Taken decimal(18,1),Available_Leaves decimal(18,1),Encashment decimal(18,1),Gender varchar(6),LeaveTypeID int,EmployeeAutoId int)
	insert into #final exec(@sqlQuery) 
	update #final set Available_Leaves=RemainingNoOfLeaves,Leave_Taken=a.numberofdayAvailed from #final 
	inner join(
	Select yc.Employee_Id,(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		,yc.LeaveTypeID,ISNULL(sum(la.NumberOfDays),0.0)as numberofdayAvailed from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id and la.Status<>'Rejected' and la.IsDeleted=0
		Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,yc.Employee_Id
		)
		as a on #final.EmployeeAutoId=a.Employee_Id and #final.LeaveTypeID =a.LeaveTypeID
select * from #final
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RstoreOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
create PROCEDURE [dbo].[Proc_TA_RstoreOtType]   
 @OtTypeID as int,   
 @EmpId as int  
AS  
BEGIN   
 update  TA_Tbl_OtType set   
   IsDeleted=0,     
   EmpID=@EmpID  
  where OtTypeID=@OtTypeID  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SaveorupdateEmployeedetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- 
/***

Proc_Ta_SaveorupdateEmployeedetails @tag='DHEXUB',
@TableXML=
'
<NewDataSet>
  <Table>
    <EmployeeCode>3</EmployeeCode>
    <Employee_FirstName>Sankar</Employee_FirstName>
    <Date>2021-11-24T00:00:00+05:30</Date>
  </Table>
  <Table>
    <EmployeeCode>4</EmployeeCode>
    <Employee_FirstName>Gopal</Employee_FirstName>
    <Date>2021-11-24T00:00:00+05:30</Date>
  </Table>
  <Table>
    <EmployeeCode>6</EmployeeCode>
    <Employee_FirstName>Gnanaprakash</Employee_FirstName>
    <Date>2021-11-24T00:00:00+05:30</Date>
  </Table>
</NewDataSet>
'

**/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SaveorupdateEmployeedetails]
	-- Add the parameters for the stored procedure here
	@tag nvarchar(10),
	@TableXML XML =NULL
	--,
	--@EmployeeCode nvarchar(200)=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	
	begin
		declare @TempEmployeeDetails1 table
		(
			id bigint identity(1,1),
			EmployeeCodeID nvarchar(200)
		)

		DECLARE @Index1 INT 
		set @Index1= 0
		declare @Error1 nvarchar(Max)
		EXEC sp_xml_preparedocument @Index1 OUTPUT, @TableXML

		INSERT INTO @TempEmployeeDetails1 (EmployeeCodeID)
		select * from OPENXML(@Index1, '/NewDataSet/Table',2)
		WITH
		(
			EmployeeCode nvarchar(150)
		) AS Employee	
			
		--SELECT * FROM @TempEmployeeDetails1
		--RETURN;
		Declare @TotalRecord int
		declare @startRecord int
		set @startRecord=1
		select @TotalRecord= COUNT(*) from @TempEmployeeDetails1
		Declare @EmployeeCodeID varchar(20)
		while @startRecord<=@TotalRecord
		begin
			set @EmployeeCodeID=''
			select @EmployeeCodeID=EmployeeCodeID from @TempEmployeeDetails1 where id=@startRecord
			--select @EmployeeCodeID
			if Exists(select EmployeeCard from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID)
			begin
				if(@tag='7P')
				BEGIN
					update Ta_tbl_BlockedEmployees set DayWise=1,WhenBlocked_Daywise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
					update Ta_tbl_BlockedEmployeesHistory set DayWise=1,WhenBlocked_Daywise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
				END
				else if(@tag='7A')
				BEGIN
					update Ta_tbl_BlockedEmployees set ContinuousDayWise=1,WhenBlocked_Daywise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
					update Ta_tbl_BlockedEmployeesHistory set ContinuousDayWise=1,WhenBlocked_Daywise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
				END
				else if(@tag='WWHB')
				BEGIN
					update Ta_tbl_BlockedEmployees set WeekWise=1,WhenBlocked_weekWise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
					update Ta_tbl_BlockedEmployeesHistory set WeekWise=1,WhenBlocked_weekWise=GETDATE()
					where EmployeeCard=@EmployeeCodeID
				END
				else if(@tag='QOTB')
				BEGIN
					update Ta_tbl_BlockedEmployees set QuarterWise=1,WhenBlocked_Daily=GETDATE()
					where EmployeeCard=@EmployeeCodeID
					update Ta_tbl_BlockedEmployeesHistory set QuarterWise=1,WhenBlocked_Daily=GETDATE()
					where EmployeeCard=@EmployeeCodeID
				END
				else if(@tag='DHEXB')
				BEGIN
					update Ta_tbl_BlockedEmployees set Daily=1,WhenBlocked_Daily=GETDATE()
					where EmployeeCard=@EmployeeCodeID
					update Ta_tbl_BlockedEmployeesHistory set Daily=1,WhenBlocked_Daily=GETDATE()
					where EmployeeCard=@EmployeeCodeID
				END
				else if(@tag='7PUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and 
					WhenBlocked_Daywise<getdate() and daywise=1 and weekwise=0			
				END
				else if(@tag='DHEXUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and WhenBlocked_Daily<getdate() 
					and daily=1 and weekwise=0 and daywise=0
				END
				else if(@tag='WWHUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and WhenBlocked_WeekWise<getdate() 
					and weekwise=1 
				END
			END
			ELSE
			BEGIN
				
				if(@tag='7P')
				BEGIN
					Insert into Ta_tbl_BlockedEmployees(DayWise,WhenBlocked_Daywise,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
					Insert into Ta_tbl_BlockedEmployeesHistory(DayWise,WhenBlocked_Daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
				END
				else if(@tag='7A')
				BEGIN
					Insert into Ta_tbl_BlockedEmployees(ContinuousDayWise,WhenBlocked_Daywise,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
					Insert into Ta_tbl_BlockedEmployeesHistory(ContinuousDayWise,WhenBlocked_Daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
				END
				else if(@tag='WWHB')
				BEGIN
					Insert into Ta_tbl_BlockedEmployees(WeekWise,WhenBlocked_weekWise,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
					Insert into Ta_tbl_BlockedEmployeesHistory(WeekWise,WhenBlocked_weekWise,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
				END
				else if(@tag='QOTB')
				BEGIN
					Insert into Ta_tbl_BlockedEmployees(QuarterWise,WhenBlocked_Daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
					Insert into Ta_tbl_BlockedEmployeesHistory(QuarterWise,WhenBlocked_Daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
				END
				else if(@tag='DHEXB')
				BEGIN
					Insert into Ta_tbl_BlockedEmployees(Daily,WhenBlocked_daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
					Insert into Ta_tbl_BlockedEmployeesHistory(QuarterWise,WhenBlocked_daily,EmployeeCard) 
					select 1,GETDATE(),EmployeeCodeID from @TempEmployeeDetails1
				END
				else if(@tag='7PUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and 
					WhenBlocked_Daywise<getdate() and daywise=1 and weekwise=0			
				END
				else if(@tag='DHEXUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and WhenBlocked_Daily<getdate() 
					and daily=1 and weekwise=0 and daywise=0
				END
				else if(@tag='WWHUB')
				BEGIN
					delete from Ta_tbl_BlockedEmployees where EmployeeCard=@EmployeeCodeID and WhenBlocked_WeekWise<getdate() 
					and weekwise=1 
				END
			end
			set @startRecord=@startRecord+1
		end
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ScriptEntryForDiscrepancy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------
CREATE procedure [dbo].[Proc_TA_ScriptEntryForDiscrepancy]
as 
Begin
	declare @YearID as int
	set @YearID = (select YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1)
---------Out Entry--------------
	insert into Ta_Tbl_ManualTimeEntry (
						ManualTimeEntry_Date,
						ManualTimeEntry_Employee_Id,					
						ManualTimeEntry_OutDate,
						ManualTimeEntry_OutTime,
						ManualTimeEntry_OutPunchType,
						ManualTimeEntry_OutReaderID,
						ManualTimeEntry_Reason,
						Clk_Process,
						ManualTimeEntry_Status,
						YearSettings_Id,
						Isdeleted
				)
	select Convert(varchar(15),getDate(),101) as manualEntryDate,emp.employee_code_id,	
	OutClockDate=
	case 
		when right (shf.Shift_StartTime,2)='PM' then
			case 
				when right (shf.Shift_EndTime,2)='AM' then  dateadd(day,1,clk.clk_date)
			end
		else 
			clk.clk_indate
	end,
	shf.Shift_EndTime as OutClockTime,
	'Out' as PunchType,
	dbo.Func_TA_SelectMatchingDevice(clk.clk_IndeviceID , 'Out') as OutDevice,
	'Script Entry'  as Remarks,
	'N'as Clk_ProcessFlag,
	'Approved' as status,
	@YearID as YearSettingID,
	0 as Isdeleted
	from ta_tbl_clockdetails clk
	inner join ta_tbl_processeddata pd 
		on clk.clk_empid= pd.employee_code_id    and
		   clk_date = pd.date
	inner join ta_tbl_shift shf 
			on shf.shift_Id=pd.shift_ID
	inner join ta_tbl_employee emp
		on emp.swipecardno = clk.clk_empId
	where clk.clk_Outdate is null and clk.clk_Outtime is null
	and
		clk.clk_Indate is not null and clk.clk_Intime is not null
	and
		emp.isdeleted=0 and emp.employee_status=1
	and
		datediff(mi,clk.clk_intime, cast(shf.shift_starttime as datetime))<=30
	and
		datediff(mi,clk.clk_intime, cast(shf.shift_starttime as datetime))>=-30
---------Out Entry--------------
insert into Ta_Tbl_ManualTimeEntry (
						ManualTimeEntry_Date,
						ManualTimeEntry_Employee_Id,					
						ManualTimeEntry_InDate,
						ManualTimeEntry_InTime,
						ManualTimeEntry_InPunchType,
						ManualTimeEntry_InReaderID,
						ManualTimeEntry_Reason,
						Clk_Process,
						ManualTimeEntry_Status,
						YearSettings_Id,
						Isdeleted
				)
	select 
		Convert(varchar(15),getDate(),101) as manualEntryDate,emp.employee_code_id,	
		clk.clk_date as InClockDate,
		shf.Shift_StartTime as InClockTime,
		'In' as PunchType,
		dbo.Func_TA_SelectMatchingDevice(clk.clk_OutdeviceID , 'In') as InDevice,
		'Script Entry'  as Remarks,
		'N'as Clk_ProcessFlag,
		'Approved' as status,
		@YearID as YearSettingID,
		0 as Isdeleted
		from ta_tbl_clockdetails clk
		inner join ta_tbl_processeddata pd 
			on clk.clk_empid= pd.employee_code_id    and
			   clk_date = pd.date
		inner join ta_tbl_shift shf 
				on shf.shift_Id=pd.shift_ID
		inner join ta_tbl_employee emp
			on emp.swipecardno = clk.clk_empId
		where clk.clk_Outdate is not null and clk.clk_Outtime is not null
		and
			clk.clk_Indate is null and clk.clk_Intime is null
		and
			emp.isdeleted=0 and emp.employee_status=1
		and
			datediff(mi,
				cast (convert (varchar(15),clk.clk_outdate,101) + ' '+  convert(varchar(8),clk.clk_outtime ,108) as datetime), 		
				cast (convert (varchar(15),clk.clk_outdate,101) + ' '+  convert(varchar(8),shf.Shift_EndTime ,108) as datetime)	
			)<=30
		and
			datediff(mi,
				cast (convert (varchar(15),clk.clk_outdate,101) + ' '+  convert(varchar(8),clk.clk_outtime ,108) as datetime), 
				cast (convert (varchar(15),clk.clk_outdate,101) + ' '+  convert(varchar(8),shf.Shift_EndTime ,108) as datetime)
			)>=-30
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SearchShiftExchange]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : [Proc_TA_SearchShiftExchange]   
Description : To Search the Shift Exchange Employee Details
Tables Included : TA_Tbl_Employee,Ta_Tbl_ShiftExchange,ta_tbl_shift
Created By : Sasireka  
Created On : 13-Jan-2009 
Modified By :  
Modified On :  
*/  
--exec [Proc_TA_SearchShiftExchange] '','','','','','SuperAdmin','1','',''
CREATE PROCEDURE [dbo].[Proc_TA_SearchShiftExchange]
(
	@EmployeeId nvarchar(20),
	@EmployeeName nvarchar(50),
	@EmployeeType int,
	@EmployeeCategory int,
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@FromDate datetime,
	@ToDate datetime
)
AS
Declare @sql as varchar(8000)
set @sql=''
BEGIN
set @sql = @sql + 'select ta_tbl_shiftExchange.date,e1.Employee_Code_Id + space(1) + e1.employee_Firstname as Employee1Name,'
set @sql = @sql + 's1.shift_name,e2.Employee_Code_Id + space(1) + e2.employee_Firstname as Employee2Name,s2.Shift_Name'
set @sql = @sql + ' from ta_tbl_shiftExchange ' 
set @sql = @sql + 'inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id'
set @sql = @sql + ' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id'
set @sql = @sql + ' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift'
set @sql = @sql + ' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift'
set @sql = @sql + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
set @sql = @sql + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
set @sql = @sql + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
set @sql = @sql + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
set @sql = @sql + ' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId'
set @sql = @sql + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
set @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID'	 
set @sql = @sql + ' where (Ta_Tbl_ShiftExchange.Date >= CONVERT(DATETIME, ''' + cast(@fromDate as nvarchar(20)) + ''', 102)) '
set @sql = @sql + ' AND (dbo.Ta_Tbl_ShiftExchange.Date <= CONVERT(DATETIME,''' + cast(@todate as nvarchar(50))  + ''', 102)) '
if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel  
	end
if not(@EmployeeName='' or @EmployeeName='0')
	begin
		set @sql = @sql + 'and dbo.TA_Tbl_Employee.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''''
	end
	if(@employeeCategory<>0)
	begin
		set @sql = @sql +' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sql = @sql + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='' or @EmployeeId='0')
	begin
		--set @sqlQuery = @sqlQuery + ' and ta_tbl_processedData.Employee_Code_Id = ''' + cast (@empId as nvarchar(50)) + ''' '
			set @sql = @sql + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
	end
	if not(@LevelID='' or @LevelID='0')
	begin
		set @sql = @sql + ' and TA_Tbl_EmployeeLevel.LevelId IN (' + @LevelID  + ') ' 
	end
	exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_Select](@Type char(1),@CompanyId int=0)
AS
DECLARE @Del BIT
SET @Del=1
--Select All Records 
if(@Type='A')
BEGIN
SELECT Company_Id,Company_Address1 FROM TA_Tbl_CompanyDetails WHERE IsDeleted=@Del
END
if(@Type='P')
BEGIN
SELECT * FROM TA_Tbl_CompanyDetails WHERE IsDeleted=@Del AND Company_Id=@CompanyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_LeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_Select_LeaveType]
(
	@LeaveDescription nvarchar(20) OUTPUT 
)
as
SELECT @LeaveDescription = LeaveDescription from tbl_TA_LeaveType
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_TerminalforView]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 July 2007
-- Description:	Select Terminal details for view
-- Modified By : Kumuthini.L
-- Modifi
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Select_TerminalforView] 
(
-- Add the parameters for the stored procedure here
  @TerminalID INT
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
             -- Insert statements for procedure here
	SELECT T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,T.IsDeleted
	FROM TA_Tbl_Terminal T
	INNER JOIN TA_tbl_TerminalDatatype TD
	ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
	WHERE T.Terminal_Id=@TerminalID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_UserGroupName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Senthil
-- ALTER  date: 15-May-08
-- Description:	Select usergroup name by id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Select_UserGroupName]
	@GroupID as int
AS
BEGIN
	select groupName,hasSpecialRights,isnull(ReportsBasedOn,0)ReportsBasedOn,IndividualUsers from Ta_tbl_usergroup where groupId=@GroupID
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectAbsentRecords]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- [proc_ta_SelectAbsentRecords] '02/Jan/2000','14/Mar/2020','',0,'','0',0,0,'SuperAdmin','0','',1,1
CREATE PROCEDURE [dbo].[proc_ta_SelectAbsentRecords]  
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @empId varchar(100),  
	 @shift int,  
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000),  
	 @employeeCategory int,  
	 @employeeType int,  
	 @UserGroupName varchar(250),  
	 @GradeLevel varchar(20) ,  
	 @EmpSwipeCard varchar(20),
	 @CompanyId int,
	 @ParentId int  
)  
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table's creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),InReaderId varchar(20),OutReaderId varchar(20))
			
	--Employee Level insert in Temporary table  
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId) ELevel  
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null  
	--select * from #EmpLevel  
	--Employee Designation insert in Temporary table  
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EDesig  
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null  
	--select * from #EmpDesignation  
	--Employee Type insert in Temporary table  
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EmpType  
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null  
	--select * from #EmpType  
	--Employee Category insert in Temporary table  
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
	--select * from #EmpCategory  
	create table #TempFinal
	(
		Employee_Code_Id nvarchar(15),
		EmployeeAutoId int,
		EmpName nvarchar(150),
		InReaderID nvarchar(20),
		InTerminalName nvarchar(50),
		InDate nvarchar(20),
		InTime nvarchar(20),
		InPunchType nvarchar(25) null,
		OutReaderID nvarchar(20),
		OutTerminalName nvarchar(50),
		OutDate nvarchar(20),
		OutTime nvarchar(20),
		OutPunchType nvarchar(25) null,
		ClockDate varchar(20),
		CLK_EmpID nvarchar(20),
		CLK_ID int,
		DiscrepancyType varchar(2),
		Reason varchar(255),
		MaxHoursBeforeShift nvarchar(50),
		Shift_Id int,
		WeeklyOffStartHours nvarchar(5),
		ShiftInDateTime nvarchar(20),
		Shift_StartTime nvarchar(10),
		Shift_EndTime nvarchar(10),
		--ShiftOutDateTime nvarchar(20),
		ManualEntryAlreadyExists varchar(5)
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	
	insert into  #TempProcessedData 
	select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.FNAttendanceCode,TA_Tbl_ProcessedData.ANAttendanceCode,'',''
	from #TempEmployee  
	INNER JOIN TA_Tbl_ProcessedData ON  TA_Tbl_ProcessedData.Shift_Id <>0 and (TA_Tbl_ProcessedData.InTime is null or TA_Tbl_ProcessedData.InTime='00:00')
	and (TA_Tbl_ProcessedData.OutTime is null or TA_Tbl_ProcessedData.OutTime='00:00') and TA_Tbl_ProcessedData.FNAttendanceCode='Absent' 
	and TA_Tbl_ProcessedData.ANAttendanceCode='Absent' and #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id 
	and Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	
	create table #EmpSwipeCardNo(EmpSwipeCardNo nvarchar(20),ReaderId varchar(20),OutReaderId varchar(20))
	insert into #EmpSwipeCardNo select SwipeCardNo,dbo.Func_TA_SelectInReaderId(SwipeCardNo,'In'),dbo.Func_TA_SelectInReaderId(SwipeCardNo,'Out') from TA_Tbl_Employee where SwipeCardNo in(select distinct Employee_Code_Id from #TempProcessedData)
	
	update #TempProcessedData set InReaderId=T1.ReaderId,OutReaderID=T1.OutReaderId from #EmpSwipeCardNo T1
	inner join #TempProcessedData on #TempProcessedData.Employee_Code_Id=T1.EmpSwipeCardNo
	
	Declare @InReaderAutoID nvarchar(10)
	Declare @OutReaderAutoID nvarchar(10)
	set @InReaderAutoID =''
	set @OutReaderAutoID =''
	---added this condition newly on 13-Feb-2020
	if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID='787')
	begin
		select @InReaderAutoID=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID='787'
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReaderAutoID
		if(@CountReader>1)
		begin
			set @InReaderAutoID=787
			set @OutReaderAutoID=787
		end
		else
		begin
			set @InReaderAutoID=787
			set @OutReaderAutoID=788
		end
	end
	--select * from #TempProcessedData
	declare @sqlQuery as varchar(8000) 
	declare @sqlQuery1 as varchar(8000)  
	set @sqlQuery = '' 
	set @sqlQuery1 = ''
	SET @sqlQuery = @sqlQuery + 'insert into #TempFinal SELECT ta_tbl_Employee.employee_code_id AS Employee_Code_Id,ta_tbl_Employee.employee_id AS EmployeeAutoId, '        
	SET @sqlQuery = @sqlQuery + 'ta_tbl_Employee.Employee_FirstName + '        
	SET @sqlQuery = @sqlQuery + ' '' '' + isnull(ta_tbl_Employee.Employee_LastName,'''') AS ''EmpName'', ' 
	SET @sqlQuery = @sqlQuery + ' case when '''+CONVERT(varchar(20),@InReaderAutoID) +'''!='''' then '''+CONVERT(varchar(20),@InReaderAutoID) +''' else #TempProcessedData.InReaderID end as InReaderID,CONVERT(nvarchar(50),'''') as InTerminalName,CONVERT(varchar(1),'''') as InDate,#TempProcessedData.InTime as InTime, '''', ' 
	SET @sqlQuery = @sqlQuery + ' case when '''+CONVERT(varchar(20),@OutReaderAutoID) +'''!='''' then '''+CONVERT(varchar(20),@OutReaderAutoID) +''' else #TempProcessedData.InReaderID end as OutReaderID,CONVERT(nvarchar(50),'''') as OutTerminalName,CONVERT(varchar(1),'''') as OutDate,#TempProcessedData.OutTime as OutTime,'''',CONVERT(VARCHAR,#TempProcessedData.Date,101) as ClockDate,ta_tbl_Employee.SwipeCardNo AS CLK_EmpId,CONVERT(int,'''') as CLK_ID' 
	SET @sqlQuery = @sqlQuery + ',CONVERT(varchar(1),''A'') as DiscrepancyType,CONVERT(varchar(255),'''') as Reason' 
	SET @sqlQuery = @sqlQuery + ',TA_Tbl_ShiftSettings.MaxHoursBeforeShift,#TempProcessedData.Shift_Id'
	SET @sqlQuery = @sqlQuery + ',TA_Tbl_ShiftSettings.WeeklyOffStartHours' 
	SET @sqlQuery = @sqlQuery + ' ,((CONVERT(VARCHAR,#TempProcessedData.Date,101)) + CONVERT(varchar(1),'' '') + TA_Tbl_Shift.Shift_StartTime) AS ShiftInDateTime'  
	set @sqlQuery = @sqlQuery + ' ,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime,''No'' as ManualEntryAlreadyExists from TA_Tbl_Employee'  
	SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'  
	SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'  
	SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId' 
	set @sqlQuery = @sqlQuery + ' INNER JOIN #TempProcessedData ON TA_Tbl_Employee.Employee_Id =#TempProcessedData.EmpAutoId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id' 
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_ShiftSettings on Ta_Tbl_ShiftSettings.CompanyId = ''' + cast(@CompanyId as nvarchar(11)) + ''''  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '  
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '  
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '  
	set @sqlQuery1 = @sqlQuery1 + ' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0)'  
	if(@UserGroupName<>'SuperAdmin')  
	begin  
		SET @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''  
	end  
	if not(@EmployeeName='')  
	begin  
		set @sqlQuery1 = @sqlQuery1 + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'  
	end  
	if not (@empId='')  
	begin  
		set @sqlQuery1 = @sqlQuery1 + ' And (TA_Tbl_Employee.Employee_code_id= ''' + @empId + ''' )'  
	end  
	If Not (@EmpSwipeCard = '')    
	Begin    
		Set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
	End   
	if(@employeeCategory<>0)  
	begin  
		set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))   
	end  
	if(@employeeType<>0)  
	begin  
		set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))   
	end  
	if(@shift<>0)  
	begin  
		Set @sqlQuery1 = @sqlQuery1 + ' And #TempProcessedData.shift_id= '+  cast (@shift as nvarchar(50))  
	end 
	exec(@sqlQuery + @sqlQuery1) 
	print(@sqlQuery + @sqlQuery1) 
	select * from #TempFinal order by Employee_Code_Id,EmpName,ClockDate asc  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #LevelRights   
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #EmpSwipeCardNo
	drop table #TempFinal
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights] 
	@AdditionalWeekOffId int
AS
BEGIN
	SET NOCOUNT ON;
	select WL.LevelId,Addl_WeekOff_Day,Addl_WeekOff_Week from TA_Tbl_Additional_WeeklyOff_Levels WL 
	inner join TA_Tbl_Additional_WeeklyOff W
	on WL.Addl_WeeklyOff_Id=W.Addl_WeeklyOff_Id where WL.Addl_WeeklyOff_Id= @AdditionalWeekOffId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAddlWeekOffDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_SelectAddlWeekOffDetails 'A',0,'SuperAdmin',0,'All','All'
CREATE   PROCEDURE [dbo].[Proc_TA_SelectAddlWeekOffDetails]
(
 @TYPE CHAR(1)='', 
 @AddlWeekOffID INT,
 @userGroupName nvarchar(25),
 @ParentId int=0,
 @WeekOffDay varchar(100)='All',
 @WeekOffWeek varchar(100)='All'
 )
AS
DECLARE @Isdeleted INT
SET @Isdeleted=0
declare @Query nvarchar(max);
declare @WhereQuery nvarchar(500)
declare @OrderByQuery nvarchar(max)
set @Query='';
set @WhereQuery='';
declare @LevelIds as varchar(250)
create table #Temp
(
LevelId varchar(250)
)
insert into #Temp
select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
select @LevelIds=  COALESCE(@LevelIds + ',', '') + LevelId FROM #Temp;
BEGIN
IF (@TYPE='A')
	IF(@userGroupName='SuperAdmin')
	begin		
		--iF @PARENTiD is not passing for Search
		if(@ParentId<=0)
		begin
			set @Query=' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day +'' - ''+ A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,
			A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week		
			FROM TA_Tbl_Additional_WeeklyOff A	
			inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
			LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.LevelId_Id=L.id '	
			set @WhereQuery=' where AL.LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','','')) ' 
			set @OrderByQuery=' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
			A.Addl_WeekOff_Week '
		end
		--If @ParentId is passing			
		else
		begin
			set @Query=' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day +'' - ''+ A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,
			A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
			FROM TA_Tbl_Additional_WeeklyOff A	
			inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
			LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id '
			set @WhereQuery=' where AL.LevelId in (select Value from dbo.Split('''+cast(@LevelIds as varchar(100))+''','','')) '
			set @OrderByQuery=' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted,  A.Addl_WeekOff_Day,
			A.Addl_WeekOff_Week ' 
		end		
	end	    		
	ELSE
		BEGIN
			if(@ParentId<=0)
			begin
				set @Query='SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day + '' - '' + A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,
				A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
				FROM TA_Tbl_Additional_WeeklyOff A	
				inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
				LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.levelId_Id=L.id '		
	    		set @WhereQuery=' WHERE A.Isdeleted='+cast(@Isdeleted as varchar(100))+' and AL.LevelId in (select Value from dbo.Split('''+cast(
	    		@LevelIds as varchar(100))+''','','')) '
	    		set @OrderByQuery=' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
	    		A.Addl_WeekOff_Week '
	    	end
	    	else
	    		begin
	    		set @Query='SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day + '' - '' + A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,
	    		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
				FROM TA_Tbl_Additional_WeeklyOff A	
				inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
				LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id '		
	    		set @WhereQuery= ' WHERE A.Isdeleted='+cast(@Isdeleted as varchar(100))+' and AL.LevelId in (select Value from dbo.Split('''+cast(
	    		@LevelIds as varchar(100))+''','','')) '
	    		set @OrderByQuery=' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
	    		A.Addl_WeekOff_Week '
	    		end
		END
ELSE IF (@TYPE='P')
	BEGIN
		set @Query=' SELECT * FROM TA_Tbl_Additional_WeeklyOff '
		set @WhereQuery=' WHERE Addl_WeeklyOff_Id='+cast(@AddlWeekOffID as varchar(100))+' AND IsDeleted='+cast(@Isdeleted as varchar(100))+' '
	END
ELSE If (@TYPE='I')
	BEGIN
	if(@ParentId<=-0)
	begin
		set @Query=' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day,A.Addl_WeekOff_Week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,L.Name, L.id AS LevelId,
		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week			
		FROM TA_Tbl_Additional_WeeklyOff A
		inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
		LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.levelId_Id=L.id '
		set @WhereQuery=' WHERE Addl_WeeklyOff_Id='+cast(@AddlWeekOffID as varchar(100))+' '
	end
	else
	begin
		set @Query=' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day,A.Addl_WeekOff_Week,case when A.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,L.Name, L.id AS LevelId,
		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week			
		FROM TA_Tbl_Additional_WeeklyOff A
		inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
		LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id '
		set @WhereQuery=' WHERE A.Addl_WeeklyOff_Id='+cast(@AddlWeekOffID as varchar(100))+' and L.id='+cast(@ParentId as varchar(100))+' '
	end
	END
	--Checking wher condition query
	if(@WeekOffDay<>'All')
		begin
			if(@WhereQuery!='')
			begin
				set @WhereQuery=@WhereQuery + ' and A.Addl_WeekOff_Day='''+cast(@WeekOffDay as nvarchar(500))+''' '
			end
			else
			begin
				set @WhereQuery=@WhereQuery + ' where A.Addl_WeekOff_Day='''+cast(@WeekOffDay as nvarchar(500))+''' '
			end
		end
		if(@WeekOffWeek<>'All')
		begin
			if(@WhereQuery!='')
			begin
				set @WhereQuery=@WhereQuery + ' and A.Addl_WeekOff_Week='''+cast(@WeekOffWeek as nvarchar(500))+''' '
			end
			else
			begin
				set @WhereQuery=@WhereQuery + ' where A.Addl_WeekOff_Week='''+cast(@WeekOffWeek as nvarchar(500))+''' '
			end
		end
	SET @Query=@Query+@WhereQuery+@OrderByQuery;
	EXEC (@Query);	
	DROP TABLE #Temp
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditColumnNames]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllAuditColumnNames] 
	-- Add the parameters for the stored procedure here
	@tableId decimal
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_AuditField WHERE TableID = @tableId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditTableNames]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllAuditTableNames] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_AuditTable WHERE Status = 1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllColumnNames]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectAllColumnNames  
Description : select congigured Field Name's description for respective tables
Tables Included : sysobjects, sysproperties, syscolumns
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllColumnNames]
	-- Add the parameters for the stored procedure here
	@tableId decimal
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		DECLARE @version as nvarchar(50)
		SET @version = ''
		SET @version = (SELECT left(@@version,26))
		if (@version='Microsoft SQL Server  2000')
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4
				ORDER BY o.id, p.smallid
			END
		else
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0
				ORDER BY o.id, p.minor_id
			END		
	--	SELECT DISTINCT(p.smallid), CAST(p.Value AS varchar(50)) AS 'Description' from syscolumns c
	--	inner join sysproperties p on c.id = p.id  where c.id=@tableId AND  p.type = 4 ORDER BY p.smallid
	--SELECT * from syscolumns  where id=@tableId and autoval is null  and  name not in ('TimeStamp','emp_id','employee_id','employeeid','empid','Time_Stamp','IsDeleted')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllNews]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllNews] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_NewsEvents order by newsEvent_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllTableNames]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_SelectAllTableNames  
Description : select congigured Table Name's description 
Tables Included : sysobjects, sysproperties
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllTableNames]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		DECLARE @version as nvarchar(50)
		SET @version = ''
		SET @version = (SELECT left(@@version,26))
		if (@version='Microsoft SQL Server  2008')
		begin
			SELECT o.id AS 'id',
			CAST(o.Name AS varchar(75)) AS 'TableName', 
			CAST(p.Value AS varchar(75)) AS 'Description'
			FROM sysobjects o
			INNER JOIN sysproperties p
			ON o.id = p.id
			WHERE p.type = 3
			AND p.smallid = 0 AND o.xtype<>'V'
			ORDER BY o.id, o.Name
		end
		else
		BEGIN
			SELECT o.id AS 'id',
			CAST(o.Name AS varchar(75)) AS 'TableName', 
			CAST(p.Value AS varchar(75)) AS 'Description'
			FROM sysobjects o
			INNER JOIN sys.extended_properties p
			ON o.id = p.major_id
			WHERE p.minor_id = 0 AND o.xtype<>'V'
			ORDER BY o.id, o.Name		
		END
	--	SELECT o.name AS name, o.id AS id, CAST(p.Value AS varchar(50)) AS 'Description' from sysobjects o 
	--	INNER JOIN sysproperties p on o.id = p.id
	--	WHERE p.type = 3 AND p.smallid = 0 AND
	--	o.xtype='U' and o.name not in ('dtproperties','localization','LookupStatic','Old_TA_tbl_LeaveType','Results','Sheet1$','TA_TBL_EmailScripts','TA_Tbl_Page','TA_Tbl_ParentIDs','TA_Tbl_Results','TA_tbl_TerminalDatatype1','TA_Tbl_userRights','TA_Tbl_WindowsServiceFlag','Tbl_Sample','tblEmployee$','TempShift','tempshift2','test_arbic','testsample','testsample1','TA_Tbl_Additional_WeeklyOff','TA_Tbl_AuditOperation','Ta_Tbl_Branding','TA_Tbl_ChangePassword','TA_Tbl_ClockDetails','TA_Tbl_YearSetting','TA_Tbl_YearClosure','TA_Tbl_WindowsServiceFlag','TA_Tbl_Usergroup','TA_Tbl_Transportation_Mapping','TA_Tbl_TitleMapping','TA_Tbl_Title','TA_Tbl_TerminalMapping','TA_tbl_TerminalDatatype','TA_Tbl_TempShiftAllocation','TA_Tbl_TemporaryShiftAllocation','TA_Tbl_ShiftSettings','TA_Tbl_ShiftRoaster','TA_Tbl_ShiftPattern','TA_Tbl_Shift','TA_Tbl_RouteMaster','TA_Tbl_Results','TA_Tbl_PunchTypes','TA_Tbl_ProcessedData','TA_Tbl_Permission','TA_Tbl_PermanentShiftAllocation','TA_Tbl_PayrollProcessLeaveDetails','TA_Tbl_PayrollProcessDetails','TA_Tbl_Page','TA_Tbl_MultiLingual','TA_Tbl_MonthClosure','TA_Tbl_ManualTimeEntry','TA_Tbl_Lookup','TA_Tbl_Login','Ta_Tbl_levelDetails','TA_Tbl_Level','TA_Tbl_LeaveType','TA_Tbl_LeavePolicyDetails','TA_Tbl_LeavePolicy','TA_Tbl_LeaveApplication','TA_Tbl_HolidaySettings','TA_Tbl_Holiday','TA_Tbl_GroupDetails','TA_Tbl_GlobalWeekdaySettings','TA_Tbl_ErrLog','TA_Tbl_Encashment','TA_Tbl_EmployeeLingual','TA_Tbl_Employee','TA_Tbl_EmpChildrenDetails','TA_Tbl_Emp_LeavePolicyDetails','TA_Tbl_Emp_LeavePolicy','TA_TBL_EmailScripts','TA_Tbl_Temweekday','TA_Tbl_Clk_RawData','TA_Tbl_ConcurrentUser','TA_Tbl_DateandTimeFormat','TA_Tbl_AuditField','TA_Tbl_Transportation')
	--SELECT name,id from sysobjects WHERE xtype='U' and name not in ('dtproperties','localization','LookupStatic','Old_TA_tbl_LeaveType','Results','Sheet1$','TA_TBL_EmailScripts','TA_Tbl_Page','TA_Tbl_ParentIDs','TA_Tbl_Results','TA_tbl_TerminalDatatype1','TA_Tbl_userRights','TA_Tbl_WindowsServiceFlag','Tbl_Sample','tblEmployee$','TempShift','tempshift2','test_arbic','testsample','testsample1','TA_Tbl_Additional_WeeklyOff','TA_Tbl_AuditOperation','Ta_Tbl_Branding','TA_Tbl_ChangePassword','TA_Tbl_ClockDetails','TA_Tbl_YearSetting','TA_Tbl_YearClosure','TA_Tbl_WindowsServiceFlag','TA_Tbl_Usergroup','TA_Tbl_Transportation_Mapping','TA_Tbl_TitleMapping','TA_Tbl_Title','TA_Tbl_TerminalMapping','TA_tbl_TerminalDatatype','TA_Tbl_TempShiftAllocation','TA_Tbl_TemporaryShiftAllocation','TA_Tbl_ShiftSettings','TA_Tbl_ShiftRoaster','TA_Tbl_ShiftPattern','TA_Tbl_Shift','TA_Tbl_RouteMaster','TA_Tbl_Results','TA_Tbl_PunchTypes','TA_Tbl_ProcessedData','TA_Tbl_Permission','TA_Tbl_PermanentShiftAllocation','TA_Tbl_PayrollProcessLeaveDetails','TA_Tbl_PayrollProcessDetails','TA_Tbl_Page','TA_Tbl_MultiLingual','TA_Tbl_MonthClosure','TA_Tbl_ManualTimeEntry','TA_Tbl_Lookup','TA_Tbl_Login','Ta_Tbl_levelDetails','TA_Tbl_Level','TA_Tbl_LeaveType','TA_Tbl_LeavePolicyDetails','TA_Tbl_LeavePolicy','TA_Tbl_LeaveApplication','TA_Tbl_HolidaySettings','TA_Tbl_Holiday','TA_Tbl_GroupDetails','TA_Tbl_GlobalWeekdaySettings','TA_Tbl_ErrLog','TA_Tbl_Encashment','TA_Tbl_EmployeeLingual','TA_Tbl_Employee','TA_Tbl_EmpChildrenDetails','TA_Tbl_Emp_LeavePolicyDetails','TA_Tbl_Emp_LeavePolicy','TA_TBL_EmailScripts','TA_Tbl_Temweekday','TA_Tbl_Clk_RawData','TA_Tbl_ConcurrentUser','TA_Tbl_DateandTimeFormat','TA_Tbl_AuditField','TA_Tbl_Transportation','TA_Tbl_AuditTable')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllType]
	@UserType as nvarchar(100)		
AS
BEGIN
	Create table #TempType(TypeName nvarchar(100),TypeId bigint,isdeleted nvarchar(10),IsFlexible bit,flag int)
	if (@UserType='SuperAdmin')
		Begin
			insert into #TempType
			select TypeName,TypeId,case when IsDeleted=1 then 'True' else 'False' end IsDeleted,IsFlexible,0 From Ta_tbl_Type order by TypeName	
		End
	Else
		Begin
			insert into #TempType
			select TypeName,TypeId,case when IsDeleted=1 then 'True' else 'False' end IsDeleted,IsFlexible,0 From Ta_tbl_Type where isdeleted=0 order by TypeName	
		End
	Update #TempType set flag=1 from #TempType TT inner join ta_tbl_employeeType ET on TT.TypeId=ET.TypeId 
	select * from #TempType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllYearSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectAllYearSetting]  
AS  
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + ' - ' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting ,* 
from Ta_Tbl_Yearsetting  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectApprovalSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name		:	Proc_TA_SelectApprovalSettings
Description			:	select the companies
Tables Included		:	TA_Tbl_ApprovalSettings
Created By			:	Prabakaran.P
Created On			:	11-Sep-09
Modified By	:
Modified On	:
Proc_TA_SelectApprovalSettings 1
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectApprovalSettings]
-- Add the parameters for the stored procedure here
@intCompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry, Approval, 
	webClockInOut=isnull(webClockInOut,0),ShiftRequisition from TA_Tbl_ApprovalSettings where CompanyId=@intCompanyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectAttandanceCode 5,'No','',''
CREATE PROCEDURE [dbo].[Proc_TA_SelectAttandanceCode]
	@AttandanceID as int,
	@All as varchar(3),
	@UserGroup as varchar(250),
	@UserLevels as varchar(2000),
	@ParentID int		
AS
BEGIN	
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroup,@ParentID) as LevelId   
	declare @Query as varchar(7000)
	if (@All='All')
	Begin	
		if (@UserGroup='SuperAdmin')
		BEGIN
			--select * from TA_Tbl_AttandanceCode order by AttandanceCode
			set @Query= 'select TA_Tbl_AttandanceCode.AttandanceID, TA_Tbl_AttandanceCode.CompanyID, TA_Tbl_AttandanceCode.AttandanceCode, TA_Tbl_AttandanceCode.AttandanceValue, TA_Tbl_AttandanceCode.EmpID,case when TA_Tbl_AttandanceCode.IsDeleted=1 then ''True'' else ''False'' end isDeleted, TA_Tbl_AttandanceCode.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode'
			set @Query=@Query + ' inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id'
			set @Query=@Query + ' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_AttandanceCode.CompanyId'
			--set @Query=@Query + ' where TA_Tbl_AttandanceCode.CompanyId in (' +@UserLevels+ ')'
			set @Query=@Query + ' order by ta_tbl_leveldetails.name'
		End
		Else
		Begin
			--select * from TA_Tbl_AttandanceCode where isdeleted=0 order by AttandanceCode
			set @Query= 'select TA_Tbl_AttandanceCode.AttandanceID, TA_Tbl_AttandanceCode.CompanyID, TA_Tbl_AttandanceCode.AttandanceCode, TA_Tbl_AttandanceCode.AttandanceValue, TA_Tbl_AttandanceCode.EmpID,case when TA_Tbl_AttandanceCode.IsDeleted=1 then ''True'' else ''False'' end isDeleted, TA_Tbl_AttandanceCode.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode'
			set @Query=@Query + ' inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id'
			set @Query=@Query + ' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_AttandanceCode.CompanyId'
			--set @Query=@Query + ' where TA_Tbl_AttandanceCode.isdeleted=0 and TA_Tbl_AttandanceCode.CompanyId in (' +@UserLevels+ ')'
			set @Query=@Query + ' where TA_Tbl_AttandanceCode.isdeleted=0'
			set @Query=@Query + ' order by ta_tbl_leveldetails.name'
		End
	End
	Else
	Begin
		set @Query= 'select * from TA_Tbl_AttandanceCode where AttandanceId=' +cast(@AttandanceID as varchar(100))+ ' order by AttandanceCode'
	End
	exec(@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttendanceXtraGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAttendanceXtraGrid]
	-- Add the parameters for the stored procedure here
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LevelRights varchar(1000),
	@ParentId int,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
			set @sqlQuery = ''
			set @sqlQuery = @sqlQuery + 'SELECT TA_Tbl_EmployeeLevel.LevelID, TA_Tbl_EmployeeDesignation.DesignationId, TA_Tbl_Employee.Employee_Code_Id AS [Employee Code Id],' 
			set @sqlQuery = @sqlQuery + ' convert(varchar(10),TA_Tbl_ProcessedData.Date,103) AS [Date], TA_Tbl_ProcessedData.InTime, TA_Tbl_ProcessedData.OutTime, TA_Tbl_ProcessedData.LateIn, TA_Tbl_ProcessedData.EarlyOut, ta_tbl_processedData.NormOt as OverTime, isnull(TA_Tbl_Employee.Employee_FirstName,'''') + SPACE(1)+ isnull(TA_Tbl_Employee.Employee_LastName,'''') AS [Employee Name],' 
			set @sqlQuery = @sqlQuery + ' TA_Tbl_ProcessedData.Attendance, replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as [Designation],' 
			set @sqlQuery = @sqlQuery + ' replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as [Level Name], ta_tbl_shift.Shift_ShortName AS [Shift Short Name]'
			set @sqlQuery = @sqlQuery + ' FROM TA_Tbl_ProcessedData' 
			set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.SwipeCardNo'
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
			set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		    set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
			set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID' 
			set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId'
			set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
			set @sqlQuery = @sqlQuery + ' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID' 	
			set @sqlQuery = @sqlQuery + ' inner JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId' 	
	        set @sqlQuery = @sqlQuery + ' WHERE (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)'					
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
			set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
			--set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
			if(@UserGroupName<>'SuperAdmin')
				begin
					set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' '
				end
			if(@EmpAutoId = 0)
				BEGIN 
				  set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
				END
			ELSE
			   BEGIN
				  set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
			   END
			If (@FromDate <> '')      
			 Begin      
				Set @sqlQuery = @sqlQuery + 'And TA_Tbl_ProcessedData.Date >= ''' + @FromDate + ''' '      
			 End      
		 If (@ToDate <> '')      
			Begin      
				Set @sqlQuery = @sqlQuery + 'And TA_Tbl_ProcessedData.Date <= ''' + @ToDate + ''' '      
			End   
			EXEC (@sqlQuery)
			drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectBLDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_SelectBLDetailsForService 1,787,'2013-01-01','2014-11-11'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectBLDetailsForService]
	-- Add the parameters for the stored procedure here
	@intBonusLeaveAvailable int,
	@SwipeCardNo varchar(50),
	@FromDate datetime,
	@ToDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @sqlQuery varchar(max)
    set @sqlQuery='SELECT TOP '+ convert(varchar(20),@intBonusLeaveAvailable) + ' Process_Rec_Id FROM TA_Tbl_Processeddata WHERE Employee_Code_Id ='
	set @sqlQuery=@sqlQuery+''''+@SwipeCardNo+''' AND Attendance = ''Absent'' AND '
	set @sqlQuery=@sqlQuery+'(Date BETWEEN '''+ CONVERT(varchar(20),@FromDate)+''' AND ''' + convert(varchar(20),@ToDate)+''') ORDER BY Date ASC'
	execute(@sqlQuery)	 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategory]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	30-Mar-2013
-- Description		:	Select Three Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs) in Insert and update Query
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectCategory]
	@CategoryID INT
AS
BEGIN
	SELECT
		CategoryName,
		CategoryId,
		IsFlexible,
		ISNULL(MonToSat_WorkHrs, 0.0) MonToSat_WorkHrs,
		ISNULL(Sat_WorkHrs, 0.0) Sat_WorkHrs,
		ISNULL(WeekDay_WorkHrs, 0.0) WeekDay_WorkHrs,
		ISNULL(ARMIS_WorkHrs, 0.0) ARMIS_WorkHrs
	FROM Ta_tbl_Category
		WHERE CategoryId = @CategoryId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategoryDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_SelectCategoryDetails]      
(      
	@TYPE CHAR(1)='',
	@CategoryId INT,
	@UserGroupName nVarchar(250)
)      
AS            
BEGIN
	Create table #TempCategory(CategoryId bigint,CategoryName nvarchar(100),IsDeleted bit,IsFlexible bit,flag int)
	IF (@TYPE='A')          
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category  
				END  
			ELSE  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE IsDeleted=0      
				END  
		END
	-- P Refers Particular     
	ELSE IF (@TYPE='P')      
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE CategoryId=@CategoryId  
				END  
			ELSE  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE CategoryId=@CategoryId AND IsDeleted=0      
				END  
		END            
	ELSE If (@TYPE='I')            
		BEGIN
			insert into #TempCategory
			SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category  WHERE IsDeleted=0
		END  
	Update #TempCategory set flag=1 from #TempCategory TC inner join ta_tbl_employeeCategory EC on TC.CategoryId=EC.CategoryId
	select * from #TempCategory 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCCGroups]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 11-Oct-2010
-- Description:	Gets the Cc groups.
-- =============================================
--Proc_TA_SelectCCGroups 1,'a'
CREATE PROCEDURE [dbo].[Proc_TA_SelectCCGroups]
@SearchOption varchar(50),
@SearchText varchar(50)
AS
BEGIN
if(@SearchOption=1 and @SearchText<>'')
BEGIN
    select C.CCGroupId,L.name +' - '+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where L.name like '%'+ @SearchText +'%'
END
else if(@SearchOption=2 and @SearchText<>'')
BEGIN
    select C.CCGroupId,L.name +' - '+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where T.TitleName like '%' + @SearchText +'%'
END
else if(@SearchText<>'')
BEGIN
    select C.CCGroupId,L.name +' - '+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where T.TitleName like '%' + @SearchText +'%' or L.name like '%'+ @SearchText +'%'
	or L.name +' - '+ T.TitleName like '%'+ @SearchText +'%'
END
else
BEGIN
	select C.CCGroupId,L.name +' - '+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectChildrenDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectChildrenDetails]
(
@empID INT
)
AS
BEGIN
	SELECT ChildEmp_ID,Emp_ID,Name,CONVERT(NVARCHAR,DOB,101) AS DOB FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID=@empID AND Spouse_Child='C' AND Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name : Proc_TA_SelectClockDetailsByEmployeeId
--Tables Used         :TA_Tbl_ClockDetails
-- Author                  : Kumuthini.L
-- Created On          : 13-Sep-2007
-- Modified On         : 19-Feb-2008
CREATE PROCEDURE [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]
(
   @SwipeCardNo Varchar(15),
   @Date Varchar(15)
)
AS
SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId=@SwipeCardNo AND Clk_Date=@Date
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompany]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_SelectCompany
Description	:	select the companies
Tables Included	:	TA_Tbl_LevelDetails,TA_Tbl_Level
Created By	:	Christopher S
Created On	:	10-Jan-09
Modified By	:	Manikandan.RR
Modified On	:	29-10-2019 11:57 AM
Changed dynamic query to normal SQL query.
Proc_TA_SelectCompany 'SuperAdmin','1',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompany]
	-- Add the parameters for the stored procedure here
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentID int	
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	select ld.id as CompanyId,replace(ld.name,'&amp;','&') as CompanyName 
	from TA_Tbl_LevelDetails ld
	inner join TA_Tbl_Level l on l.LevelId=ld.LevelId
	inner join #LevelRights on #LevelRights.LevelId=ld.id
	where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 order by ld.id
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyForOverTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name    :     Proc_TA_SelectCompany
Description :     select the companies
Tables Included   :     TA_Tbl_LevelDetails,TA_Tbl_Level
Created By  :     Christopher S
Created On  :     10-Jan-09
Modified By :
Modified On :
Proc_TA_SelectCompanyForOverTime 'SuperAdmin','159',1
*/
Create PROCEDURE [dbo].[Proc_TA_SelectCompanyForOverTime]
      -- Add the parameters for the stored procedure here
      @UserGroupName nvarchar(250),
      @UserLevels nvarchar(2000),
      @ParentID int     
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @Query as varchar(7000)
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
    -- Insert statements for procedure here
      --if(@UserGroupName='SuperAdmin')
            BEGIN
                  set @Query = 'select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName' 
                  set @Query= @Query +' from TA_Tbl_LevelDetails ld'
                  set @Query= @Query +' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId'
                  set @Query= @Query +' inner join #LevelRights on #LevelRights.LevelId=ld.id inner join TA_Tbl_ShiftSettings S on ld.id=S.CompanyId'
                  --set @Query= @Query +' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in ('+ @UserLevels +')'
                  set @Query= @Query +' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0'
            END
      /* else
            BEGIN
                  set @Query = 'select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName' 
                  set @Query= @Query +' from TA_Tbl_LevelDetails ld'
                  set @Query= @Query +' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId'
                  set @Query= @Query +' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in ('+ @UserLevels +')'
            END */
            exec (@Query)
            drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyGroup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompanyGroup]
AS
BEGIN
	select  CompanyGroup from Ta_tbl_CompanyGroup
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_SelectCompanyWithApprovalSettings
Description	:	select the companies
Tables Included	:	TA_Tbl_LevelDetails,TA_Tbl_Level
Created By	:	Christopher S
Created On	:	10-Jan-09
Modified By	:
Modified On	:
[Proc_TA_SelectCompanyWithApprovalSettings] 'SuperAdmin','70',0,'P'
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]
	-- Add the parameters for the stored procedure here
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int,
	@Type varchar(2)	
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(7000)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- R = Shift Roaster
	if(@Type='R')
		BEGIN
			set @Query = 'select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName' 
			set @Query= @Query +' from TA_Tbl_LevelDetails ld'
			set @Query= @Query +' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId'
			set @Query= @Query +' inner join TA_Tbl_ApprovalSettings aps on aps.CompanyId=ld.Id'
			set @Query= @Query +' inner join #LevelRights on #LevelRights.LevelId=ld.id'
			--set @Query= @Query +' where aps.PatternRoster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in ('+ @UserLevels +')'
			set @Query= @Query +' where aps.Roster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0'
		END
		-- P = Shift pattern
       ELSE if(@Type='P')
		BEGIN
			set @Query = 'select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName' 
			set @Query= @Query +' from TA_Tbl_LevelDetails ld'
			set @Query= @Query +' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId'
			set @Query= @Query +' inner join TA_Tbl_ApprovalSettings aps on aps.CompanyId=ld.Id'
			set @Query= @Query +' inner join #LevelRights on #LevelRights.LevelId=ld.id'
			--set @Query= @Query +' where aps.PatternRoster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in ('+ @UserLevels +')'
			set @Query= @Query +' where aps.Pattern=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0'
		END
		exec (@Query)
		drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select * from ta_tbl_compensation where Employee_id='3232' and FromDate='09/18/2011' 
-- Proc_TA_SelectCompensation '','788','05/01/2017',73
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompensation]     
	@EmployeeName varchar(20),    
	@Employee_Id varchar(20),
	@FromDate varchar(20),
	@CompOffID bigint,
	@Remarks nvarchar(250)
AS    
BEGIN    
	SET NOCOUNT ON;    
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat()	
	-- Insert statements for procedure here    
	if(@EmployeeName ='')    
	begin    
		select	C.Compensation_Id,
				C.Employee_Id,
				isnull(e.Employee_FirstName,'') +  space(1) + isnull(e.Employee_LastName,'') as Employee_FirstName,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ApplicationDate,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.ApplicationDate, @dateFormat) 
				end AS ApplicationDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.FromDate,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.FromDate, @dateFormat) 
				end AS FromDate ,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ToDate,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.ToDate, @dateFormat) 
				end AS ToDate,
				case C.Type when '1.0' then 'FullDay' when '0.5' then 'HalfDay' 
				end as Type,
				C.Remarks,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ExpiredDate,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.ExpiredDate, @dateFormat) 
				end AS ExpiryDate,
				C.Quota,
				case	when C.ExpiredDate >= CONVERT(DATETIME,cast(getdate() as nvarchar(50)),102) then
						0  else 1 
				end as Expiredstatus,
				case	when C.InTime<>'00:00' then	case	when (@TimeFormat) ='hh:mm' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.InTime,0)), 114) 
															else	SUBSTRING(C.InTime,13,5)+' ' + SUBSTRING(C.InTime,18,2)
													end 
						else ''
				end	InTime,
				case	when C.OutTime<>'00:00' then case	when (@TimeFormat) ='hh:mm' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.OutTime,0)), 114) 
															else	SUBSTRING(C.InTime,13,5)+' ' + SUBSTRING(C.OutTime,18,2) 
													 end 
						else '' 
				end	OutTime,
				C.WorkedHours,
				C.DayWorked,
				C.Status as Comp_Status,
				C.Comments 
		from TA_Tbl_Compensation C
		inner join ta_tbl_Employee E on C.Employee_Id=E.Employee_Code_Id 
		where	C.Compensation_Id=@CompOffID	order by Compensation_Id desc
	end    
	else    
	begin 
		if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1  and Compensation_Id=@CompOffID)
		begin
			if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1 and status <> 'Expired' and Compensation_Id=@CompOffID)
			begin
				if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1 and status <> 'Availed' and Compensation_Id=@CompOffID)
				begin
					--delete from TA_Tbl_Compensation 
					UPDATE TA_Tbl_Compensation SET Isdeleted=1,status='Cancelled',Remarks=@Remarks
					WHERE Employee_Id=@Employee_Id and Isdeleted <>1 and Compensation_Id=@CompOffID
					select '1'
				end
				else
				begin
					select 'Availed'
				end
			end
			else
			begin
				select 'Expired'
			end
		end
		else
		begin
			select'2'
		end
	end   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensationbyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select * from ta_tbl_compensation where Employee_id='3232' and FromDate='09/18/2011' 
-- Proc_TA_SelectCompensationbyID 358
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompensationbyID]   
	@CompOffID bigint
AS    
BEGIN    
	SET NOCOUNT ON;    
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat()	
	begin    
		select	C.ExtraTime_Id 'Compensation_Id',
				E.Employee_Code_Id as 'Employee_Id',C.Employee_Id as E_Employee_Id,
				isnull(e.Employee_FirstName,'') +  space(1) + isnull(e.Employee_LastName,'') as Employee_FirstName,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ApplicationDate,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.ApplicationDate, @dateFormat) 
				end AS ApplicationDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.Date,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.Date, @dateFormat) 
				end AS FromDate ,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.Date,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.Date, @dateFormat) 
				end AS ToDate,
				case C.NoOfDays when '1.0' then 'FullDay' when '0.5' then 'HalfDay' 
				end as Type,
				C.Reason,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.DateToExpired,@dateFormat),' ','-') 
						else CONVERT(VARCHAR, C.DateToExpired, @dateFormat) 
				end AS ExpiryDate,
				C.NoOfDays as 'Quota',
				case	when C.DateToExpired >= CONVERT(DATETIME,cast(getdate() as nvarchar(50)),102) then
						0  else 1 
				end as Expiredstatus,
				case	when C.InTime<>'00:00' then	case	when (@TimeFormat) ='hh:mm' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.InTime,0)), 114) 
															else	InTime
													end 
						else ''
				end	InTime,
				case	when C.OutTime<>'00:00' then case	when (@TimeFormat) ='hh:mm' then  CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.OutTime,0)), 114)
															else	OutTime
													 end 
						else '' 
				end	OutTime,
				C.HrsExtra as 'WorkedHours',
				C.DaysWorked as 'DayWorked',
				C.OverTimeStatus as Comp_Status,
				C.Process_RecID
		from TA_Tbl_OverTimeStatus C
		inner join ta_tbl_Employee E on C.Employee_Id=E.Employee_Id 
		where	C.ExtraTime_Id=@CompOffID order by C.ExtraTime_Id desc
	end    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectConveyanceAllowance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Select * From TA_Tbl_PF_ESIDetails

--Select * From Ta_Tbl_levelDetails

-- Proc_TA_SelectConveyanceAllowance 'A',7,'SuperAdmin'
CREATE Procedure [dbo].[Proc_TA_SelectConveyanceAllowance]
(
	@Type char(3),
	@Policy_Id INT=0,  
	@UserGroupName nVarchar(250)
)
As 

Begin
	SET NOCOUNT ON;
	IF (@Type='A')
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT CA.C_Id,CA.Con_type,CA.ConPolicyName,CA.conPercentage,CA.LimitAmount, CA.conAmount, CA.CompanyId, CA.EmployeeCategory,CA.EmployeeType, CA.Created_Date, CA.Created_BY,CA.Gender,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempCAPolicy 
					FROM TA_Tbl_ConveyanceAllowance CA
					Left Outer join Ta_Tbl_levelDetails LD on CA.companyId=LD.id
					--Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempCAPolicy	
					
					--Drop Table #tempPFESIPolicy	
				END
			ELSE
				BEGIN
					SELECT CA.C_Id, CA.ConPolicyName,Con_type,CA.conPercentage,CA.LimitAmount, CA.conAmount, CA.CompanyId, CA.EmployeeCategory,CA.EmployeeType, CA.Created_Date, CA.Created_BY,CA.Gender,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempCAPol1 FROM TA_Tbl_ConveyanceAllowance CA
					Left Outer join Ta_Tbl_levelDetails LD on CA.CompanyId=LD.id
					WHERE CA.isDeleted=0 
					--Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
				END  
		END
	ELSE IF (@Type='P')  
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT CA.C_Id, CA.ConPolicyName,CA.conPercentage,Con_type,CA.LimitAmount,CA.conAmount, CA.CompanyId, CA.EmployeeCategory,CA.EmployeeType, CA.Created_Date, CA.Created_BY,CA.Gender,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempCAPol2 
					FROM TA_Tbl_ConveyanceAllowance CA
					Left Outer join Ta_Tbl_levelDetails LD on CA.companyid=LD.id
					where CA.C_Id=@Policy_Id
					--Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempCAPol2	
					
					--Drop Table #tempCAPol2
					
				END
			ELSE
				BEGIN
					SELECT CA.C_Id, CA.ConPolicyName,CA.conPercentage, CA.conAmount,CA.LimitAmount, CA.CompanyId, CA.EmployeeCategory,CA.EmployeeType, CA.Created_Date, CA.Created_BY,CA.Gender,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempPFESIPol3 FROM TA_Tbl_ConveyanceAllowance CA
					Left Outer join Ta_Tbl_levelDetails LD on CA.companyid=LD.id
					WHERE CA.isDeleted=0 And CA.C_Id=@Policy_Id
					--Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					--select * from #tempPFESIPol	
				END  
		END  



	Else if(@Type='S')
	Begin
		
		Select * From TA_Tbl_Employee emp inner Join TA_Tbl_ConveyanceAllowance CA on CA.C_Id=emp.CA

	End
End

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDashBoardRightsDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-10-2016>
-- Description:	<Select Board Rights Details>
-- [Proc_TA_SelectDashBoardRightsDetails]'5'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDashBoardRightsDetails]
	@UsergroupId int
AS
BEGIN
	SET NOCOUNT ON;
	if exists(select BoardId from ta_tbl_DashboardUserrights where Usergroupid=@UsergroupId)
    begin
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0)ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId		
		where Usergroupid=@UsergroupId and BoardParentName='AttendanceData'
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0) ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId
		where Usergroupid=@UsergroupId and BoardParentName='ApprovalData'
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0)ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId
		where Usergroupid=@UsergroupId and BoardParentName='ExceptionData'	
		select top 1 Dashboard,Gridview,Chart from ta_tbl_DashboardUserrights DUR
		where Usergroupid=@Usergroupid 
		select groupName from ta_tbl_usergroup where groupid=@UsergroupId
	end
	else
	begin
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName='AttendanceData'
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName='ApprovalData'
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName='ExceptionData'
		select top 1 Dashboard,Gridview,Chart from ta_tbl_DashboardUserrights DUR		
		where Usergroupid=@Usergroupid
		select groupName from ta_tbl_usergroup where groupid=@UsergroupId
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
/* Proc_TA_SelectDetails  1 */
CREATE PROCEDURE [dbo].[Proc_TA_SelectDetails]
	@loginEmployeeId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @loginEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetailsForShiftRequisitionAddonGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_SelectDetailsForShiftRequisitionAddonGrid]


 @Monthyear nvarchar(100) ='APR-2023',
 @CompanyID int = 24

AS
BEGIN
	declare @Year nvarchar(100)
	declare @StartDate nvarchar(100)
	declare @EndDate nvarchar(100)
	declare @FromDate nvarchar(100)
	declare @month nvarchar(100)
	Create table #SHIFTtEMP(EmpID INT,EmployeeId VARCHAR(50),EmployeeName NVARCHAR(50),LoginEmployeeId INT,Year NVARCHAR(50),Month	NVARCHAR(50),
	Day1Shift NVARCHAR(50)	,Day2Shift NVARCHAR(50),Day3Shift NVARCHAR(50),Day4Shift NVARCHAR(50),Day5Shift NVARCHAR(50),Day6Shift NVARCHAR(50),
	Day7Shift NVARCHAR(50),Day8Shift NVARCHAR(50),Day9Shift NVARCHAR(50),Day10Shift NVARCHAR(50),Day11Shift NVARCHAR(50),Day12Shift NVARCHAR(50),
	Day13Shift NVARCHAR(50),Day14Shift NVARCHAR(50),Day15Shift NVARCHAR(50)	,Day16Shift NVARCHAR(50),Day17Shift	NVARCHAR(50),Day18Shift	NVARCHAR(50),
	Day19Shift	NVARCHAR(50),Day20Shift	NVARCHAR(50),Day21Shift	NVARCHAR(50),Day22Shift	NVARCHAR(50),
	Day23Shift	NVARCHAR(50),Day24Shift	NVARCHAR(50),Day25Shift	NVARCHAR(50),Day26Shift	NVARCHAR(50),
	Day27Shift	NVARCHAR(50),Day28Shift	NVARCHAR(50),Day29Shift	NVARCHAR(50),Day30Shift	NVARCHAR(50),Day31Shift	NVARCHAR(50),Emp_Id	NVARCHAR(50))


	 SET @Year = SUBSTRING(@Monthyear,5,8);
	 SET @month = SUBSTRING(@Monthyear,1,3);
	 set @StartDate = '01'
	 SET @FromDate= @StartDate + '-' + @Monthyear

	 DECLARE @ADate DATETIME
DECLARE @DaysInMonth INT
SET @ADate = @FromDate
SET @DaysInMonth = DAY(EOMONTH(@ADate)) 

	--insert into #SHIFTtEMP
	SELECT EmpID,TA_Tbl_TempShiftAllocation.EmployeeId,EmployeeName,LoginEmployeeId, 
	@Year as Year,@month as Month,'1' as Day1Shift, '1' as Day2Shift,
	'1' as Day3Shift,'1' as Day4Shift,'1' as  Day5Shift,'1' as Day6Shift,'1' as Day7Shift,'1' as Day8Shift,
	'1' as Day9Shift,'1' as Day10Shift,'1' as Day11Shift,'1' as Day12Shift,'1' as Day13Shift,'1' as Day14Shift,
	'1' as Day15Shift,'1' as Day16Shift,'1' as Day17Shift,'1' as Day18Shift,'1' as  Day19Shift	,'1' as  Day20Shift	,
	'1' as  Day21Shift	,'1' as  Day22Shift	,'1' as  Day23Shift	,'1' as  Day24Shift	,'1' as  Day25Shift	,'1' as  Day26Shift	,
	'1' as Day27Shift,'1' as  Day28Shift, 
	
	CASE WHEN @DaysInMonth >28 THEN '1'  ELSE '0'  END AS Day29Shift , 
	CASE WHEN @DaysInMonth >29 THEN '1'  ELSE '0'  END AS Day30Shift ,
	CASE WHEN @DaysInMonth >30 THEN '1'  ELSE '0'  END AS Day31Shift  ,'1' as Emp_Id
	FROM TA_Tbl_TempShiftAllocation
--	Year,Month,Day1Shift,Day2Shift,Day3Shift,
--Day4Shift,Day5Shift,Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,
--Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,Day26Shift,
--Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
	

	--select * from TA_Tbl_TempShiftAllocation

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetailsGroupPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****************************************************************************************/            
-- Name    : Proc_TA_SelectDetailsGroupPolicy           
-- Desc    : To select the enties from TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : P.Santhosh Raj            
-- Date    : 25-Mar-2009            
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectDetailsGroupPolicy]
@loginEmployeeId int       
AS      
BEGIN
	SET NOCOUNT ON;      
	SELECT EmpID,EmployeeId, EmployeeName,LoginEmployeeId,convert(nvarchar(20),DateOfJoining,101) as DateOfJoining,LevelID     
	FROM TA_Tbl_TempGroupPolicyAllocation Where LoginEmployeeId = @loginEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDevice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDevice]
AS
BEGIN
	select DeviceID,DeviceType from ta_tbl_deviceType order by DeviceType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDeviceDetails]
	@DeviceID as int
AS
BEGIN
		SELECT [DeviceID]
		  ,[DeviceType]
		  ,[ConnectionString]
		  ,[TableName]
		  ,[ReaderNo]
		  ,[CardNo]
		  ,[EmployeeID]
		  ,[DateField]
		  ,[DateFormat]
		  ,[TimeField]
		  ,[TimeFormat]
		  ,[DateTimeField]
		  ,[DateTimeFormat]
		  ,[DateTimeOption]
		  ,[Encrypt]
		  ,[PunchType]
		  ,[TransactionIdentFlag]
		  ,[TransactionIdentField]
		  ,[TransactionIdentValue]
		  ,[Flag]
	  FROM  [TA_Tbl_DeviceType]
			Where  [DeviceID]=@DeviceID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceFromBiostar]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.Karthikeyan.
-- Create date: 04-03-2016
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in Terminal sync
-- Proc_TA_SelectDeviceFromBiostar
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDeviceFromBiostar]
	@ConnString as nvarchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	DECLARE @sql2 varchar(8000)
	DECLARE @sql1 varchar(8000)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	SET @ConnectionString=@ConnString
	IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
		BEGIN
			INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
			SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=2
			UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=3)
			UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
			UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
			UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=4)
			UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=5)				
			UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
			--select * from  Ta_tbl_DeviceServerDetails
			UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
		END			
	SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
	if not exists(select * from sys.servers where name = N''+@ServerName+'')
	begin
		EXEC sp_addlinkedserver @server=@ServerName
	end
	declare @suser_sname nvarchar(256) 
	set @suser_sname= suser_sname()
	EXEC master.dbo.sp_addlinkedsrvlogin 
	@rmtsrvname=@ServerName,
	@useself=N'False',
	@locallogin=@suser_sname,
	@rmtuser=@UserId,
	@rmtpassword=@Password
	CREATE TABLE #test(exist int,TableName varchar(500))
	Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
	set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''TB_READER'')'
	Insert into #test exec(@sql)			
		if exists(select COUNT(*) from #test where TableName ='TB_READER')
		begin
			set @sql2='select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0) as DataType,getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where 
			convert(varchar(20),nReaderIdn) not in('
			set @sql2=@sql2+ ' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )'
			Exec (@sql2)
		end
	delete from Ta_tbl_DeviceServerDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDiscrepancy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [Proc_TA_SelectDiscrepancy] '788','09/02/2014'
--	Modified by		:	Manjula.P
--	ModifiedOn		:	10-May-2014
--	Descriptinos	:	Changing this procedure for PRODUCT Migration from angler timecheckv1.5
CREATE    PROCEDURE [dbo].[Proc_TA_SelectDiscrepancy]      
(
	@EmployeeID VarChar(50), 	
	@Date VarChar(50)
)      
AS      
BEGIN  
	SET NOCOUNT ON;
    create table #TempProcessedData(Shift_Id int,Date datetime,Employee_Code_Id varchar(20))
    insert into  #TempProcessedData 
	select TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
	from TA_Tbl_ProcessedData where Date = CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102)
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
		 Declare @SelectSQL As Varchar(6000)      
		 Set @SelectSQL = ' '        
		 Set @SelectSQL = @SelectSQL + 'SELECT ED.employee_code_id AS CardNo,ED.employee_id AS EmployeeAutoId, '      
		 Set @SelectSQL = @SelectSQL + 'ED.Employee_FirstName + '      
		 Set @SelectSQL = @SelectSQL + ' '' '' + isnull(ED.Employee_LastName,'''') AS ''EmpName'', '      
		Set @SelectSQL = @SelectSQL + 'CD.Clk_InDeviceId as InReaderID,ITer.Terminal_Name as InTerminalName,
		case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, Clk_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, Clk_InDate, '+cast(@dateFormat as varchar(100))+') end
		as InDate, 
		case	when ('''+@TimeFormat+''')=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Clk_InTime,0)), 114)
			    else	substring(convert(varchar(20),Clk_InTime),13,5)+'' '' + substring(convert(varchar(20),Clk_InTime),18,2) 					
		end as InTime ,'
		Set @SelectSQL = @SelectSQL + 'CD.Clk_OutDeviceId as OutReaderID,OTer.Terminal_Name as OutTerminalName,
			case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, Clk_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, Clk_OutDate, '+cast(@dateFormat as varchar(100))+') end as OutDate, 
	case	when ('''+@TimeFormat+''')=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Clk_OutTime,0)), 114)
			    else	substring(convert(varchar(20),Clk_OutTime),13,5)+'' '' + substring(convert(varchar(20),Clk_OutTime),18,2) 					
		end
	as OutTime,
			case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, Clk_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, Clk_Date, '+cast(@dateFormat as varchar(100))+') end  ClockDate,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime FROM TA_Tbl_Employee ED '      
        Set @SelectSQL = @SelectSQL + ' INNER JOIN TA_Tbl_ClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
        set @SelectSQL = @SelectSQL + ' inner join #TempProcessedData on #TempProcessedData.Employee_Code_Id = ED.SwipeCardNo and #TempProcessedData.Date = CD.CLK_Date'  
        set @SelectSQL = @SelectSQL + ' left join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id' 
		Set @SelectSQL = @SelectSQL + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID '       
		Set @SelectSQL = @SelectSQL + ' Where CD.IsVoid = 0 AND ED.IsDeleted = ''0'' and ED.report_exclude=0'
		 If Not (@EmployeeId = '' Or @EmployeeId = '0')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + 'And ED.swipecardno = ''' + @EmployeeId + ''' '      
		 End      
		 If (@Date <> '')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + 'And CD.Clk_Date = ''' + @Date + ''' '      
		 End      
		  Set @SelectSQL = @SelectSQL + ' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc'      
 	Exec (@SelectSQL)            
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectDiscrepancyEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from 
-- [proc_ta_SelectDiscrepancyEmployee] '2012/01/01','2012/11/24','S787',0,'','0',0,0,'NormalUser','3','',0,0,15
CREATE  PROCEDURE [dbo].[proc_ta_SelectDiscrepancyEmployee]  
(  
 @fromDat datetime,  
 @ToDat datetime,  
 @empId varchar(100),  
 @shift int,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),  
 @employeeCategory int,  
 @employeeType int,  
 @UserGroupName varchar(250),  
 @GradeLevel varchar(20) ,  
 @EmpSwipeCard varchar(20),
 @CompanyId int,
 @ParentID int,
 @LoginEmployeeAutoId int 
)  
AS  
BEGIN   
-- SET NOCOUNT ON added to prevent extra result sets from  
-- interfering with SELECT statements.  

SET NOCOUNT ON;  
--Temporary table's creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(50))
CREATE TABLE #TempClockDetails
(
    Clk_Id int,
	Clk_CompId varchar(10),
	Clk_EmpId nvarchar(20),
	Clk_InDeviceId nvarchar(20),
	Clk_InDate datetime,
	Clk_InTime datetime,
	Clk_InPunchType nvarchar(25),
	Clk_OutDeviceId nvarchar(20),
	Clk_OutDate datetime,
	Clk_OutTime datetime,
	Clk_OutPunchType nvarchar(25),
	Clk_Process nvarchar(1) ,
	Clk_Remarks nvarchar(500),
	Clk_User nvarchar(20),
	Clk_Date datetime,
	Clk_Status char(1),
	IsVoid bit
)
create table #TempFinal
(
Employee_Code_Id nvarchar(15),
EmployeeAutoId int,
EmpName nvarchar(200),
InReaderID nvarchar(20),
InTerminalName nvarchar(50),
InDate nvarchar(20),
InTime nvarchar(20),
InpunchType nvarchar(50),
OutReaderID nvarchar(20),
OutTerminalName nvarchar(50),
OutDate nvarchar(20),
OutTime nvarchar(20),
OutPunchtype nvarchar(50),
ClockDate varchar(20),
CLK_EmpID nvarchar(20),
CLK_ID int,
DiscrepancyType varchar(2),
Reason varchar(255),
MaxHoursBeforeShift nvarchar(50),
Shift_Id int,
WeeklyOffStartHours nvarchar(5),
ShiftInDateTime nvarchar(20),
Shift_StartTime nvarchar(10),
Shift_EndTime nvarchar(10),
--ShiftOutDateTime nvarchar(20),
ManualEntryAlreadyExists varchar(5)
)
-- #TempProcessedData Indexes  
 /****** Object:  Index [IDX_EmpAutoId]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmpAutoId] ON [dbo].[#TempProcessedData]   
(  
 [EmpAutoId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData]   
(  
 [Date] ASC  
) ON [PRIMARY]  
-- #TempClockDetails Indexes   
/****** Object:  Index [IDX_Clk_EmpId]    Script Date:******/  
CREATE NONCLUSTERED INDEX [IDX_Clk_EmpId] ON [dbo].[#TempClockDetails]   
(  
 [Clk_EmpId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_Clk_Date]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Clk_Date] ON [dbo].[#TempClockDetails]   
(  
 [Clk_Date] ASC  
) ON [PRIMARY]  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId 
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId 
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null  
--select * from #EmpLevel  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--select * from #EmpDesignation  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--select * from #EmpType  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--select * from #EmpCategory 
create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
/****** Object:  Index [IDX_EmpSwipeCardNo]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmpSwipeCardNo] ON [dbo].[#TempEmployee]   
(  
 [EmpSwipeCardNo] ASC  
) ON [PRIMARY]  
insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
where SwipeCardNo is not null
--select * from #TempEmployee
insert into  #TempProcessedData 
select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
from #TempEmployee  
INNER JOIN TA_Tbl_ProcessedData ON #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id and Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--select * from  #TempProcessedData
insert into #TempClockDetails
select Clk_Id,Clk_CompId,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Remarks,Clk_User,Clk_Date,Clk_Status,IsVoid
from  ta_tbl_clockdetails
inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo = ta_tbl_clockdetails.Clk_EmpId
where Clk_Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
and (clk_inTime is null or clk_outTime is null) AND IsVoid = 0
--select * from  #TempClockDetails
 Declare @finalCompanyId int
 if exists(select * from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	begin
		set @finalCompanyId=@CompanyId
	end
else
	begin
		set @finalCompanyId =-1
	end
 declare @IndividualUserStatus int
 set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
 declare @sqlQuery as varchar(8000)  
 declare @sqlQuery1 as varchar(8000) 
 set @sqlQuery = ''  
  set @sqlQuery1 = ''
 SET @sqlQuery = @sqlQuery + 'insert into #TempFinal SELECT ta_tbl_Employee.employee_code_id,ta_tbl_Employee.employee_id AS EmployeeAutoId, '        
 SET @sqlQuery = @sqlQuery + 'ta_tbl_Employee.Employee_FirstName + '        
 SET @sqlQuery = @sqlQuery + ' '' '' + isnull(ta_tbl_Employee.Employee_LastName,'''') AS ''EmpName'', '        
 SET @sqlQuery = @sqlQuery + '#TempClockDetails.Clk_InDeviceId as InReaderID,ITer.Terminal_Name as InTerminalName,CONVERT(VARCHAR,#TempClockDetails.Clk_InDate,101) as InDate, convert(varchar,#TempClockDetails.Clk_InTime,108) as InTime ,case #TempClockDetails.Clk_InPunchType when ''I'' then ''F_In'' else #TempClockDetails.Clk_InPunchType end as Clk_InPunchType,'        
 SET @sqlQuery = @sqlQuery + '#TempClockDetails.Clk_OutDeviceId as OutReaderID,OTer.Terminal_Name as OutTerminalName,CONVERT(VARCHAR,#TempClockDetails.Clk_OutDate,101) as OutDate, convert(varchar,#TempClockDetails.Clk_OutTime,108) as OutTime,case #TempClockDetails.Clk_OutPunchType when ''O'' then ''F_Out'' else #TempClockDetails.Clk_OutPunchType end as Clk_OutPunchType,CONVERT(VARCHAR,#TempClockDetails.Clk_Date,101) as ClockDate,#TempClockDetails.CLK_EmpID as CLK_EmpID, '        
 SET @sqlQuery = @sqlQuery + ' #TempClockDetails.CLK_Id as CLK_ID, (case when #TempClockDetails.Clk_InDate is null then CONVERT(varchar(1),''I'') when #TempClockDetails.Clk_OutDate is null then CONVERT(varchar(1),''O'') end) as DiscrepancyType,'  
 SET @sqlQuery = @sqlQuery + ' CONVERT(varchar(255),'''') as Reason '
 SET @sqlQuery = @sqlQuery + ',TA_Tbl_ShiftSettings.MaxHoursBeforeShift,#TempProcessedData.Shift_Id'
 SET @sqlQuery = @sqlQuery + ',TA_Tbl_ShiftSettings.WeeklyOffStartHours'
 SET @sqlQuery = @sqlQuery + ' ,((CONVERT(VARCHAR,#TempProcessedData.Date,101)) + CONVERT(varchar(1),'' '') + TA_Tbl_Shift.Shift_StartTime) AS ShiftInDateTime'  
 set @sqlQuery = @sqlQuery + ' ,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime,''No'''  
 set @sqlQuery = @sqlQuery + ' from TA_Tbl_Employee'  
 set @sqlQuery = @sqlQuery + ' INNER JOIN #TempClockDetails ON TA_Tbl_Employee.SwipeCardNo = #TempClockDetails.Clk_EmpId'  
 SET @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON #TempClockDetails.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON #TempClockDetails.Clk_InDeviceId = ITer.Terminal_ReaderID '         
 set @sqlQuery = @sqlQuery + ' inner join #TempProcessedData on #TempProcessedData.EmpAutoId = TA_Tbl_Employee.Employee_Id and #TempProcessedData.Date = #TempClockDetails.CLK_Date'  
 SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'  
 SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'  
 SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'  
 set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId' 
 set @sqlQuery = @sqlQuery + ' left join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id' 
 set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_ShiftSettings on Ta_Tbl_ShiftSettings.CompanyId = ''' + cast(@finalCompanyId as nvarchar(11)) + ''''
 set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id '  
 set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'  
 set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '  
 set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '  
 set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '  
 set @sqlQuery1 = @sqlQuery1 + ' where ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0'  
 if(@IndividualUserStatus  = 1)
 	BEGIN
 	  set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_Employee.Employee_Id = ''' + cast(@LoginEmployeeAutoId as varchar(25)) + ''' '
 	END
 if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
 if(@UserGroupName<>'SuperAdmin')  
 begin  
  SET @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''  
 end  
 if not(@EmployeeName='')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ' and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'  
 end 
 if not (@empId='')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ' And (TA_Tbl_Employee.Employee_code_id = ''' + @empId + ''' )'  
 end  
 If Not (@EmpSwipeCard = '')    
    Begin    
    Set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_Employee.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
 End   
 if(@employeeCategory<>0)  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8))   
 end  
 if(@employeeType<>0)  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8))   
 end 
 if(@shift<>0)  
 begin  
  Set @sqlQuery1 = @sqlQuery1 + ' And #TempProcessedData.shift_id= '+  cast (@shift as nvarchar(50))  
 end  
 exec(@sqlQuery + @sqlQuery1)
 select distinct * from #TempFinal order by Employee_Code_Id,EmpName,ClockDate,InDate,InTime,OutDate,OutTime asc  
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #LevelRights  
drop table #TempProcessedData
drop table #TempClockDetails
drop table #TempFinal
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_SelectEmailByEmpId
Description	:	Get Email Id of Employees Based on their Employee_Code_Id
Tables Included	:	TA_TBL_Employee
Created By	:	Prabakaran
Created On	:	23-June-07
Modified By	:
Modified On	:
*/
CREATE  procedure [dbo].[Proc_TA_SelectEmailByEmpId]
@EmployeeCodeId nvarchar(50)
as
begin
select EmailId,Employee_FirstName,Employee_code_ID from TA_TBL_Employee 
where Employee_Code_Id=@EmployeeCodeId and employee_status=1
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailIDByLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmailIDByLevel] 
	@id as int
AS
BEGIN
	select TomailIds, CcMailIDs from ta_tbl_leveldetails where id=@id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectEmailOfReportingToByEmpId
Description		:	Get Email Id of Reporting_To of Employees Based on their Employee_Id
Tables Included	:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]
@Employee_Id nvarchar(50)
as
select Employee_Id,EmailId from TA_TBL_Employee 
where Employee_Id =(select Reporting_To from TA_TBL_Employee where Employee_Id=@Employee_Id)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_SelectEmailOfSanctionAuthorityByEmpId
Description		:	Get Permisssion Details of Employees Based on their Employee_Id
Tables Included	:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	21-Jul-07
Modified By		:
Modified On		:
*/
--Proc_TA_SelectEmailOfSanctionAuthorityByEmpId 304
CREATE  procedure [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]
@Employee_Id bigint
as
select Employee_Id,EmailId from TA_TBL_Employee 
where Employee_Id =(select Leave_Sanc_Authority from TA_TBL_Employee where Employee_Id=@Employee_Id)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_SelectEmailScheduleBasedOnId 19
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]
(
  @ScheduleId int = '1'
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @ToEmailList VARCHAR(8000)
	DECLARE @CCEmailList VARCHAR(8000)
	SELECT @ToEmailList = COALESCE(@ToEmailList + ';', '') + CAST(EmailID AS VARCHAR(100))
	FROM   TA_tbl_MailIdsForTriggeringEmail
	WHERE  ScheduleId = @ScheduleId and MailType = 'To'
	SELECT @CCEmailList = COALESCE(@CCEmailList + ';', '') + CAST(EmailID AS VARCHAR(100))
	FROM   TA_tbl_MailIdsForTriggeringEmail
	WHERE  ScheduleId = @ScheduleId and MailType = 'CC'
	
	Declare @reportId int
	select @reportId=ReportId from TA_Tbl_EmailSchedule where ScheduleId=@ScheduleId
	if(@reportId=248 or @reportId=249)
	BEGIN
		select ES.*,ET.*,F.*,E.*,@ToEmailList as ToEmailList,@CCEmailList as CCEmailList ,
		p.pageId,displayName=case when @reportId=248 then 'Leave Approval' else 'Onduty Approval' end, path, parentId, orderBy, ParentIdForSubMenu
		from TA_Tbl_EmailSchedule ES
		inner join TA_Tbl_EmailTemplate ET on ES.ScheduleId = ET.ScheduleId
		inner join TA_Tbl_EmailScheduleFilters F on ES.ScheduleId = F.ScheduleId
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner Join TA_Tbl_Employee E on E.Employee_Id=ES.EmployeeId
		where ES.ScheduleId = @ScheduleId
	END
	ELSE
	BEGIN
		select *,@ToEmailList as ToEmailList,@CCEmailList as CCEmailList from TA_Tbl_EmailSchedule ES
		inner join TA_Tbl_EmailTemplate ET on ES.ScheduleId = ET.ScheduleId
		inner join TA_Tbl_EmailScheduleFilters F on ES.ScheduleId = F.ScheduleId
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner Join TA_Tbl_Employee E on E.Employee_Id=ES.EmployeeId
		where ES.ScheduleId = @ScheduleId
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
 =============================================    
 Author:  Arun vinoth    
 ALTER  date: 30/07/2007    
 Description: select Emp Leave Policy details  
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Procedure Name	:	Proc_TA_SelectEmp_LeavePolicyDetais 5
Description	:	Display Employee Leave Policy of active year Based on employee Leave
			Policy Year Setting Id
 =============================================    
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]    
 -- Add the parameters for the stored procedure here    
@EmpID INT    
AS    
BEGIN    
 SET NOCOUNT ON;    
SELECT ELP.LeavePolicy_Id,LP.PolicyName,CONVERT(NVARCHAR,ELP.FromDate,101) AS FromDate,CONVERT(NVARCHAR,ELP.ToDate,101) AS ToDate   
FROM TA_Tbl_Emp_LeavePolicy ELP  
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id   
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND YS.Isactive=1  order by ELP.Emp_LeavePolicyId 
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpDemo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmpDemo] 
AS
BEGIN
	select * from ta_tbl_employee where employee_id !=1 order by employee_firstname
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	Proc_TA_SelectEmployee '45','SuperAdmin','9',45
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
exec [Proc_TA_SelectEmployee] 22,'SuperAdmin', 0, 22
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployee]
(
	@Employee_ID int,
    @LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@ParentId int	
)      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
 DECLARE @sql AS VARCHAR(5000)      
 DECLARE @CurrentDate AS NVARCHAR(30)
 SET @CurrentDate = GetDate()
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
-- Comment By Manikandan.R
-- ON 19-12-2013 4.52 for mantis bug 0020805
-- i have checked whether this procedure has been used into other modules or not. its not used.
--SELECT 
--	Employee_Id,
--	Employee_Code_Id,
--	Employee_FirstName + ' ' +  isnull(Employee_LastName,'') AS 'Employee Name',
--	TA_Tbl_Employee.CompOff_Eligible 
--FROM TA_Tbl_Employee 
--	INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
--	INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId
--	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId
--	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId
--	Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId
--	--Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId
--	--Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId
----WHERE TA_Tbl_Employee.Isdeleted=0 AND
----	TA_Tbl_Employee.Employee_Status=1 AND
----	Employee_Firstname<>'Administrator'
----ORDER BY Employee_Code_Id
--return
 IF(@LevelId = '')
    BEGIN
	SET @LevelId = '0'
    END
 --SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then ' ' + cast(Employee_MiddleName as varchar(50)) else ' ' end + Employee_LastName AS 'Employee Name' FROM TA_Tbl_Employee WHERE LevelID in(@LevelId) and Isdeleted=1      
 SET @sql ='SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + '' '' +  isnull(Employee_LastName,'''') AS ''Employee Name'',TA_Tbl_Employee.CompOff_Eligible FROM TA_Tbl_Employee'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
SET @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
SET @sql = @sql + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
SET @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
SET @sql = @sql + ' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 '
--SET @sql = @sql + ' AND #EmpLevel.LevelId in (' + @LevelId + ') '
--SET @sql = @sql + ' AND #EmpLevel.LevelId in (select * from #LevelRights) '
--SET @sql = @sql + ' AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,''' + @CurrentDate + ''', 102) order by EffectiveDate desc) AND'
--SET @sql = @sql + ' TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,''' + @CurrentDate + ''', 102) order by EffectiveDate desc) ' 
if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
	end
if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
SET @sql = @sql + ' AND Employee_Firstname<>''Administrator'' ORDER BY Employee_Code_Id'     
 EXEC(@sql)          
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Karthikeyan.R>
-- Create date: <15-12-2016>
-- Description:	<Get Employee Details using the employee code>
-- Proc_TA_SelectEmployeeCode '11','SuperAdmin',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeCode]
	-- Add the parameters for the stored procedure here
	@EmployeeCode nvarchar(20),
	@UserGroupName nvarchar(100),
	@EmpAutoID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @LevelId int
	--Get the Top level ID
	declare @today datetime =getdate()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @today,@EmployeeCode 
	CREATE TABLE #LevelRights(LevelId INT)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	declare @GetLevelID as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
	;WITH ParentLevel AS
	(
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
		WHERE id = @GetLevelID
		UNION ALL
		SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
		INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
	)
	SELECT TOP 1 @LevelId=p.id
	FROM ParentLevel r
	inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	if(@LevelId is null)
		begin
			set @LevelId=@GetLevelID
		end
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId 
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@LevelId) as LevelId 
	declare @SQLQuery as nvarchar(Max)
	set @SQLQuery =''
	set @SQLQuery =@SQLQuery + 'select '+ ISNULL(cast(@LevelId as nvarchar(10)),0) + ' as ''parentLevelID'',E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + '' '' + E.Employee_LastName as ''EmployeeName'' from TA_Tbl_Employee E '	
    set @SQLQuery =@SQLQuery +' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '
    set @SQLQuery =@SQLQuery +' inner join #LevelRights on #LevelRights.LevelId=EL.levelID '
    if(@isReportingto > 0)
    begin
		set @SQLQuery = @SQLQuery + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
    end
		set @SQLQuery =@SQLQuery + ' where Employee_Code_Id='''+ cast(@EmployeeCode as varchar(100)) + ''''
		exec(@SQLQuery)
		drop table #EmpLevel
		drop table #LevelRights
		drop table #EmployeeIds
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_SelectEmployeeDetails 361
-- Modified by : Prabakaran.P
-- Modified on : 26-Apr-08
--	Proc_TA_SelectEmployeeDetails 35
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetails] 
(  
	@EmployeeId INT=0 
)  
AS
BEGIN
	DECLARE @ActiveYearId INT
	DECLARE @EffectiveDate datetime
	DECLARE @EffectBPayDate datetime
	DECLARE @EffectLevelDate datetime
	DECLARE @EffectCategoryDate datetime
	DECLARE @EffectTypeDate datetime
	select @EffectiveDate=Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId
	select @EffectBPayDate=Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId
	select @EffectLevelDate=Max(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId
	select @EffectCategoryDate=Max(EffectiveDate) from TA_Tbl_EmployeeCategory where EmployeeId=@EmployeeId
	select @EffectTypeDate=Max(EffectiveDate) from TA_Tbl_EmployeeType where EmployeeId=@EmployeeId
	declare @ReportingToEmailID as nvarchar(100)
	declare @ApprovalAuthorityEmailID as nvarchar(100)
	select @ReportingToEmailID=EmailId from TA_Tbl_Employee where Employee_Id=(select Reporting_To from TA_Tbl_Employee where Employee_Id=@EmployeeId)
	select @ApprovalAuthorityEmailID=EmailId from TA_Tbl_Employee where Employee_Id=(select Leave_Sanc_Authority from TA_Tbl_Employee where Employee_Id=@EmployeeId)
	SELECT	E.Employee_Id,ELevel.LevelId,L.name AS LevelName,E.UserGroup_Id,g.groupName,EDesig.DesignationId as Designation_Id,EDesig.EffectiveDate as EDesigEffectDate,
			T.TitleName,E.Bus_Id,TV.Route_Name AS Bus,E.Employee_FirstName,E.Employee_MiddleName,isnull(E.Employee_LastName,'') as Employee_LastName, 
			E.Father_name,E.Mother_name,CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
			E.Blood_Group,E.EmailId,E.Contact_Address,E.Permanent_Address,E.Phone_Number,E.Mobile_Number,E.Gender,E.Marital_status,  
			E.Nationality,R.Name as Religion,R.ID as ReligionId,E.Photo,E.Personal_mailid,E.Passport_No,CONVERT(NVARCHAR,E.Passport_expirydate,101) AS Passport_expirydate,  
			E.Visa_No,CONVERT(NVARCHAR,E.Visa_expirydate,101) AS Visa_expirydate,E.Vehicle_Type,E.Vehicle_No,  
			CONVERT(NVARCHAR,E.Anniversary_Date,101) AS Anniversary_Date,E.Native_Place,Look.Title AS City,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,  
			E.Spouse_No,E.Children_No,E.Employee_Code_Id,CONVERT(NVARCHAR,E.DateOfJoining,101) AS DateOfJoining,E.Reporting_To,(Rep.Employee_FirstName + '' + isnull(Rep.Employee_LastName,'') + ' - ' + isnull(Rep.Employee_Code_id,'')) as Reporting,  
			E.Leave_Sanc_Authority,(Sanc.Employee_FirstName + '' + isnull(Sanc.Employee_LastName,'')+ ' - ' + isnull(Sanc.Employee_Code_id,'')) AS SancAuth, E.Prev_Experience,E.Basic_Salary as Basic_Salary,EPay.EffectiveDate as EPayEffectDate,E.Hostel,E.UserName,E.Emp_password,  
			E.Qual_JoiningTime,E.Qual_Employment,E.OutDoorJob,E.CompOff_Eligible,E.OT_Eligible,E.ESI_Eligible,E.PF_Eligible,   
			E.Report_Exclude,E.Employee_Status,E.SwipeCardNo,tblCat.CategoryName,tblCat.CategoryId,ECat.EffectiveDate as CategoryEffDate,tblType.TypeName,tblType.TypeId,EType.EffectiveDate as TypeEffDate,ELevel.EffectiveDate as LevelEffDate,E.Isdeleted,E.IsFlexible,convert(varchar(20),E.InActiveDate,110)as InActiveDate
			,E.CustomField1,E.CustomField2,E.CustomField3,E.CustomField4,E.CustomField5,ENT.Entrance_Name,@ReportingToEmailID as 'ReportingToEmailID',@ApprovalAuthorityEmailID as 'ApprovalAuthorityEmailID',
			E.penalty, E.MobileClockInOUt,E.SMSEnabled,E.IsPassportReminderRequired,E.PassportRemindDays,E.IsVisaReminderRequired,E.VisaRemindDays,mp.myprofileID,E.Tax_Policy,E.PF_Policy,pf.PFESI_PolicyName,E.CA,cv.ConPolicyName,E.HRA,E.MedicalAlllowance,E.CEDAllowance,E.Emp_Ctc
			
	FROM TA_Tbl_Employee E   
	left Outer join TA_Tbl_EmployeeEntrance EE On EE.Employee_Code_Id=E.Employee_Code_Id 
	left Outer  Join TA_Tbl_Terminal TER On TER.Terminal_ReaderID=EE.Device_Id
	left Outer  Join TA_Tbl_Entrance_INOUTDetails ED On ED.Reader_Id=TER.Terminal_Id
	left Outer  Join TA_Tbl_Entrance ENT On ENT.Entrance_Id=ED.Entrance_Id
	left Outer join ta_tbl_usergroup g on g.groupId = e.usergroup_id  
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ELevel ON ELevel.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=ELevel.LevelId 
	LEFT OUTER JOIN TA_Tbl_EmployeeCategory ECat ON ECat.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeeType EType ON EType.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId  
	LEFT OUTER JOIN TA_Tbl_RouteMaster TV ON TV.[Id]=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
	LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
	LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
	LEFT OUTER JOIN TA_Tbl_Employee Rep ON Rep.Employee_Id = E.Reporting_To  
	LEFT OUTER JOIN TA_Tbl_Employee Sanc ON Sanc.Employee_Id = E.Leave_Sanc_Authority 
	INNER JOIN TA_Tbl_Category tblCat ON tblCat.CategoryId= ECat.CategoryId
	INNER JOIN TA_Tbl_Type tblType ON tblType.TypeId= EType.TypeId
	LEFT OUTER JOIN Ta_Tbl_MyProfileDetails MP ON MP.Employee_Id = E.Employee_Id and MP.Status='Pending'
	LEFT OUTER JOIN TA_Tbl_Religion R on e.Religion=R.ID
	Left outer Join TA_Tbl_PF_ESIDetails pf on pf.PFESI_Id=E.PF_Policy
	Left Outer join TA_Tbl_ConveyanceAllowance cv on cv.C_Id=E.CA
	WHERE E.Employee_Id=@EmployeeId  AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate

END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>

-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Late Entry',15

-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Early Exit',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Less Hours Worked',7
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Absent - Single Day',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Continuous Absent',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Continuous Absent',3
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering 'Continuous Absent',4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]
	-- Add the parameters for the stored procedure here
	@TemplateName VARCHAR(50),
	@ShiftID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    DECLARE @FirstTriggeringTime DATETIME
    DECLARE @ShiftTiming DATETIME
    DECLARE @TriggeringTime DATETIME
    DECLARE @TemplateID int
    DECLARE @NextTriggeringTime DATETIME
    DECLARE @LessHrsLimitation VARCHAR(5)	
    DECLARE @lesshrsLimitationInMins INT
    DECLARE @TagName VARCHAR(50)
    SELECT @TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
    create table #TempFinal(id int identity(1,1),EmployeeName varchar(250),EmployeeId varchar(50),Hrs varchar(5),date datetime)    
	if(@TemplateName='Late Entry')
	begin
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@NextTriggeringTime=Second_TriggeringTime 		
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @NextTriggeringTime=@FirstTriggeringTime+@ShiftTiming+@NextTriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		Set @TagName='LateEntry'
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		--select @FirstTriggeringTime
		--select @TemplateID
		--select @ShiftTiming
		--  @TriggeringTime is the time after shift starttime, NextTriggeringTime is shift starttime + @TriggeringTime + @NextTriggeringTime
		--If shift start at 9, First triggger time is 01:00, next triegger is 00:30 it means First Trigger at 10 am and next trigger time is 10:30 am
		--select @TriggeringTime --
		--select @NextTriggeringTime
		if not exists(select top 1 logid from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and 
		TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))and Status=1 and ShiftId=@ShiftID)
		begin
			--10:00<=9.45
			--10:00<=10.00
			--10:00<=10.15
			if(@TriggeringTime<=GETDATE())
			begin
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,LateIn,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) 
				and 
				LateInMins>0 
				and InTime<>'00:00' 
				and  
				date+convert(datetime,InTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
		end
		else
		begin
			SELECT @NextTriggeringTime=max(NextTriggeringTime) from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
			and Status=1 and ShiftId=@ShiftID		
			set @TriggeringTime=@NextTriggeringTime
			SELECT @ShiftTiming=@NextTriggeringTime-CONVERT(datetime,First_TriggeringTime) from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			if(@TriggeringTime<=GETDATE())
			begin
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,LateIn,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				LateInMins>0 and InTime<>'00:00' and date+convert(datetime,InTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
				and PD.Employee_Code_Id not in(select Employeesids from TA_Tbl_SMSLogChild)
			end
			SELECT @NextTriggeringTime=@NextTriggeringTime+CONVERT(datetime,Second_TriggeringTime) from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			select @ShiftTiming=Shift_EndTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))from TA_Tbl_Shift 
			where Shift_Id=@ShiftID and Isdeleted=0
			if @NextTriggeringTime>@ShiftTiming
			begin
				return
			end
		end
	end	
	if(@TemplateName='Early Exit')
	begin
		if not exists(select status from TA_Tbl_SMSLogDetails where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))and status=1
		and ShiftId=@ShiftID and TemplateID=@TemplateID)
			begin	
				Set @TagName='EarlyExit'	
				SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where id=@TemplateID and Status=1
				select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
				set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming++CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
				if(@TriggeringTime<=GETDATE())
				begin
					Insert into #TempFinal
					select E.Employee_FirstName,E.SwipeCardNo,EarlyOut,Date from TA_Tbl_ProcessedData PD
					inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo and ProcessFlag=1
					where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
					EarlyOutMins>0 and OutTime<>'00:00' and (date+convert(datetime,OutTime) <= @TriggeringTime)
					and E.Isdeleted=0
				end
			end
	end
	if(@TemplateName='Less Hours Worked')
	begin
		Set @TagName='LessHours'		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@LessHrsLimitation=LessHrsLimitation 
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		--select @TriggeringTime,@ShiftTiming
		set @lesshrsLimitationInMins=SUBSTRING(@LessHrsLimitation,0,CHARINDEX(':',@LessHrsLimitation))*60+SUBSTRING(@LessHrsLimitation,CHARINDEX(':',@LessHrsLimitation)+1,len(@LessHrsLimitation))
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,HrsLess,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				LessHoursInMins>=@lesshrsLimitationInMins and OutTime<>'00:00' 
				--and date+convert(datetime,OutTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
	end
	if(@TemplateName='Absent - Single Day')
	begin
		Set @TagName='AbsentSingleDay'		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,'',date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				(InTime='' or InTime='00:00' or OutTime='' or OutTime='00:00')
				and (FNAttendanceCode='Absent' or ANAttendanceCode='Absent')
				--and date+convert(datetime,OutTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
	end
	if(@TemplateName='Continuous Absent')
	begin
		Set @TagName='AbsentContinuousDay'		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		Declare @ContinuousAbsentDays int
		select @ContinuousAbsentDays=Continue_AbsentDays from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select distinct E.Employee_FirstName,E.SwipeCardNo,'',CONVERT(datetime, CONVERT(varchar(10),getdate(),111))	from TA_Tbl_Employee E where E.SwipeCardNo in(
				select a.Employee_Code_Id from(
				select count(*)count,PD.Employee_Code_Id from TA_Tbl_ProcessedData PD				
				where(Date>=DATEADD(D,-@ContinuousAbsentDays,CONVERT(datetime, CONVERT(varchar(10),getdate(),111))) 
				and Date<=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))) 				
				and (FNAttendanceCode='Absent' and ANAttendanceCode='Absent')
				group by Employee_Code_Id having(count(*))>=@ContinuousAbsentDays)as a)
			end
	end
	Set @TagName='LessHours'
	Declare @TagCount int
	CREATE TABLE #TempTags(id INT IDENTITY(1,1),Tags VARCHAR(20))
	CREATE TABLE #TempTagPosition(id int identity(1,1),Tag varchar(20),position int)
	CREATE TABLE #TempTagPositionFinal(id int identity(1,1),Tag varchar(20),position int,ColumnNames varchar(40))
	INSERT INTO #TempTags
	SELECT Tags FROM Ta_Tbl_SMSTags WHERE TemplateName=@TagName and Tags!='{User Name}'
	set @TagCount=(select COUNT(*) from #TempTags)
	Declare @Tags varchar(20)
	declare @Start int
	set @Start=1	
	while @Start<=@TagCount
	begin		
		select @Tags=Tags from #TempTags where id=@Start
		--select @Tags
		insert into #TempTagPosition 
		select @Tags,CHARINDEX(@Tags,Tags) from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		and CHARINDEX(@Tags,Tags)!=0
		set @Start=@Start+1
	end	
	insert into #TempTagPositionFinal	
	select Tag,position,
	case	when Tag='{Employee ID}'	then 'EmployeeId'
			when Tag='{Employee Name}'	then 'EmployeeName'
			when Tag='{Late By Hrs}'	then 'Hrs'
			when Tag='{Date}'			then 'convert(varchar(20),Date,103)'
			when Tag='{Early Exit Hrs}'	then 'Hrs'
			when Tag='{Less Hours}'		then 'Hrs'
			when Tag='{Count}'			then 'Count'
	end
	from #TempTagPosition order by position	
	Declare @Totalrecord int
	set @Totalrecord=(select COUNT(*) from #TempFinal)
	--select * from #TempFinal
	declare @i int
	set @i=1
	Create table #FinalStringTable(id int identity(1,1),FinalString varchar(max))
	Declare @TagName1 varchar(40)
	Declare @TagName2 varchar(40)
	Declare @TagName3 varchar(40)
	Declare @TagName4 varchar(40)
	Declare @TagName5 varchar(40)
	select @TagName1=ColumnNames from #TempTagPositionFinal where id=1
	select @TagName2=ColumnNames from #TempTagPositionFinal where id=2
	select @TagName3=ColumnNames from #TempTagPositionFinal where id=3
	select @TagName4=ColumnNames from #TempTagPositionFinal where id=4
	select @TagName5=ColumnNames from #TempTagPositionFinal where id=5
	while @i<=@Totalrecord
	begin		
		Declare @DynamicSQL varchar(max)
		set @DynamicSQL=''		
		set @DynamicSQL=@DynamicSQL+'select '
		if(@TagName1!='')
		begin
			set @DynamicSQL=@DynamicSQL+@TagName1
		end
		if(@TagName2!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName2
		end
		if(@TagName3!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName3
		end
		if(@TagName4!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+'''-'''+'+'+@TagName4
		end
		if(@TagName5!='')
		begin
			set @DynamicSQL=@DynamicSQL+'+'+''','''+'+'+@TagName5
		end
		set @DynamicSQL=@DynamicSQL+' From #TempFinal where id='+CONVERT(varchar(max),@i)
		Insert into #FinalStringTable
		Execute(@DynamicSQL)		
		set @i=@i+1
	end
	--print @Totalrecord
	--select * from #FinalStringTable
	Declare @FinalString nvarchar(max)
	select @FinalString=coalesce(@FinalString+',',' ')+isnull(FinalString,'') from #FinalStringTable
	Declare @ExceptionReceivedEmployees nvarchar(max)
	select @ExceptionReceivedEmployees=coalesce(@ExceptionReceivedEmployees+',',' ')+isnull(EmployeeId,'') from #TempFinal
	--select @FinalString as concatString
	if(@FinalString!='')
	begin
		select Message+@FinalString as Message,@FinalString as ExceptionEmployees,@TemplateName as TemplateName,
		@ExceptionReceivedEmployees as ExceptionReceivedEmployees,@NextTriggeringTime as next
		from Ta_Tbl_SMSTemplates where id=@TemplateID and Status=1
	end
	else
	begin
		select 'NO' Message,'' ExceptionEmployees,@TemplateName as TemplateName,'' as ExceptionReceivedEmployees,@NextTriggeringTime 
		as next
	end
	select E.Employee_FirstName+' '+E.Employee_LastName as Receivers,E.SwipeCardNo,E.Mobile_Number,@TemplateID as TemplateID from TA_Tbl_Employee E where UserGroup_Id in(
	select Usergroupid from Ta_Tbl_SMSReceivers SR
	inner join Ta_Tbl_SMSTemplates ST on SR.TemplateId=ST.id
	where TemplateId=@TemplateID and ST.Status=1) and E.Isdeleted=0 and E.Employee_Status=1
	and E.SwipeCardNo!='18000000' and E.Mobile_Number!='' and E.SMSEnabled = 1 
	--and E.Employee_Code_Id = '8967661'
	drop table #TempFinal
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Manikandan.RR
-- Create date: 30-01-2014
-- Description:	To select the employee details
-- =============================================
CREATE PROCEDURE [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Employee 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsNew]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsNew]
(
@type CHAR(1),
@EmployeeId NVARCHAR(50),
@EmployeeName NVARCHAR(50)=''
)
AS
DECLARE @del BIT
SET @del=0
DECLARE @EffectiveDate datetime
DECLARE @EffectBPayDate datetime
set @EffectiveDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId)
set @EffectBPayDate=(select Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId)
--selecting all employee details
IF @type='A'
BEGIN
	SELECT Employee_Id,UserGroup_Id,EDesig.DesignationId,Bus_Id,Employee_FirstName,Employee_MiddleName,isnull(Employee_LastName,''),
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,State,Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo
	FROM TA_Tbl_Employee E
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	WHERE E.IsDeleted=@del and Employee_Firstname<>'Administrator' 
END
--selecting employee details based on id            
ELSE IF @type='P'
BEGIN
	SELECT Employee_Id,UserGroup_Id,EDesig.DesignationId,Bus_Id,Employee_FirstName,Employee_MiddleName,isnull(Employee_LastName,'') as Employee_LastName,
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,State,Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo,EL.LevelId
	FROM TA_Tbl_Employee E
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	WHERE E.IsDeleted=@del AND Employee_Id=@EmployeeId
END
--selecting employee using search option
ELSE IF @type='N'
BEGIN
	SELECT E.Employee_Id,Employee_FirstName,L.levelName AS Company_Name,T.TitleName AS TitleName,Employee_MiddleName,isnull(Employee_LastName,'') as Employee_LastName,
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,E.State,E.Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo
	 FROM TA_Tbl_Employee as E 
    INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	INNER JOIN TA_TBL_levelDetails as Ld2 on Ld2.id= EL.LevelId 
	INNER JOIN TA_TBL_levelDetails as Ld1 ON Ld1.id = ld2.parentid 
	 INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	INNER JOIN TA_TBL_level as L ON Ld2.Levelid=L.LevelId
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	WHERE E.IsDeleted=@del AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND Employee_FirstName LIKE @EmployeeName+'%'  --(substring(E.Employee_FirstName,1,len(@EmployeeName)) = @EmployeeName )
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_SelectEmployeeDetails 153
-- Modified by : Prabakaran.P
-- Modified on : 26-Apr-08
--select * from ta_tbl_employee
CREATE        PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsUpdated] 
(  
	@EmployeeId INT=0  
)  
AS            
BEGIN  
	DECLARE @del BIT  
	SET @del=0 
	DECLARE @ActiveYearId INT
	DECLARE @EffectiveDate datetime
	DECLARE @EffectBPayDate datetime
	DECLARE @EffectLevelDate datetime
	DECLARE @EffectCategoryDate datetime
	DECLARE @EffectTypeDate datetime
	set @EffectiveDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectBPayDate=(select Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectLevelDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectCategoryDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeCategory where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectTypeDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeType where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	--select @EffectiveDate,@EffectBPayDate,@EffectLevelDate,@EffectCategoryDate,@EffectTypeDate
	--selecting employee details based on id  
	SELECT E.Employee_Id,ELevel.LevelId,L.name AS LevelName,E.UserGroup_Id,g.groupName,EDesig.DesignationId as Designation_Id,EDesig.EffectiveDate as EDesigEffectDate,T.TitleName,  
	E.Bus_Id,TV.Route_Name AS Bus,  
	--E.Employee_FirstName + case when E.Employee_MiddleName ='' then ' ' else  ' ' + E.Employee_MiddleName end + case when E.Employee_LastName <> '' then ' ' + E.Employee_LastName end as Employee_FirstName, E.Father_name,E.Mother_name,  
	E.Employee_FirstName,E.Employee_MiddleName,isnull(E.Employee_LastName,'') as Employee_LastName, E.Father_name,E.Mother_name,  
	CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
	E.Blood_Group,E.EmailId,E.Contact_Address,E.Permanent_Address,E.Phone_Number,E.Mobile_Number,E.Gender,E.Marital_status,  
	E.Nationality,E.Religion,E.Photo,E.Personal_mailid,E.Passport_No,CONVERT(NVARCHAR,E.Passport_expirydate,101) AS Passport_expirydate,  
	E.Visa_No,CONVERT(NVARCHAR,E.Visa_expirydate,101) AS Visa_expirydate,E.Vehicle_Type,E.Vehicle_No,  
	CONVERT(NVARCHAR,E.Anniversary_Date,101) AS Anniversary_Date,E.Native_Place,Look.Title AS City,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,  
	E.Spouse_No,E.Children_No,E.Employee_Code_Id,CONVERT(NVARCHAR,E.DateOfJoining,101) AS DateOfJoining,E.Reporting_To,Rep.Employee_FirstName as Reporting,  
	E.Leave_Sanc_Authority,Sanc.Employee_FirstName AS SancAuth, E.Prev_Experience,EPay.BasicPay as Basic_Salary,EPay.EffectiveDate as EPayEffectDate,E.Hostel,E.UserName,E.Emp_password,  
	E.Qual_JoiningTime,E.Qual_Employment,E.OutDoorJob,E.CompOff_Eligible,E.OT_Eligible,E.ESI_Eligible,E.PF_Eligible,   
	E.Report_Exclude,E.Employee_Status,E.SwipeCardNo,tblCat.CategoryName,tblCat.CategoryId,ECat.EffectiveDate as CategoryEffDate,tblType.TypeName,tblType.TypeId,EType.EffectiveDate as TypeEffDate,ELevel.EffectiveDate as LevelEffDate,E.Isdeleted 
	FROM TA_Tbl_Employee E   
	left Outer join ta_tbl_usergroup g on g.groupId = e.usergroup_id  
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ELevel ON ELevel.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=ELevel.LevelId 
	LEFT OUTER JOIN TA_Tbl_EmployeeCategory ECat ON ECat.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeeType EType ON EType.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId  
	--LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle TV ON TV.VehicleId=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_RouteMaster TV ON TV.[Id]=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
	LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
	LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
	LEFT OUTER JOIN TA_Tbl_Employee Rep ON Rep.Employee_Id = E.Reporting_To  
	LEFT OUTER JOIN TA_Tbl_Employee Sanc ON Sanc.Employee_Id = E.Leave_Sanc_Authority 
	INNER JOIN TA_Tbl_Category tblCat ON tblCat.CategoryId= ECat.CategoryId
	INNER JOIN TA_Tbl_Type tblType ON tblType.TypeId= EType.TypeId
	WHERE  E.Employee_Id=@EmployeeId AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate
	--WHERE E.Employee_Id=@EmployeeId AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--   Proc_TA_SelectEmployeeDetailXtraGrid '11/jun/2008','04/Jul/2011','SuperAdmin',0,1,0
-- Proc_TA_SelectEmployeeDetailXtraGrid 'SuperAdmin','10','1,2,3,47,113,132,133,134,135,136',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]
	-- Add the parameters for the stored procedure here
	--@FromDate varchar(50),
	--@ToDate varchar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	
	@LevelRights varchar(1000),
	@ParentId int	,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT dbo.TA_Tbl_Employee.Employee_code_Id, isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as [Employee Name], Status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end,' 
		set @sqlQuery = @sqlQuery + ' convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as [Date Of Birth],convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as [Date Of Joining],'
		set @sqlQuery = @sqlQuery + ' Gender = case Gender when ''Male''  then ''Male''  when ''Female'' then ''Female'' end, TA_Tbl_Employee.Passport_No, convert(nvarchar(20),TA_Tbl_Employee.Passport_expirydate,101) as [Passport Expiry Date], TA_Tbl_Employee.Visa_No, convert(nvarchar(20),TA_Tbl_Employee.Visa_expirydate,101) as [Visa Expiry Date], replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as [Designation],replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as [Level Name],'		
		set @sqlQuery = @sqlQuery + ' TA_Tbl_Category.CategoryName as [Employee Category], TA_Tbl_Type.TypeName as [Employee Type] FROM dbo.TA_Tbl_Employee' 
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId' 
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'		
		--set @sqlQuery = @sqlQuery + ' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.report_exclude = 0)'
		set @sqlQuery = @sqlQuery + ' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'')' 
		set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
		set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
	    set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'	    
		--set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
		if(@EmpAutoId = 0)
			BEGIN 
			  set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
			END
		ELSE
		   BEGIN
			  set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
		   END
		if(@UserGroupName<>'SuperAdmin')
			begin
				set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' '
			end
		--if not(@FromDate='')		
		--begin
		--set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @FromDate as nvarchar(50))   + ''', 102)) '		
		--End
		--if not (@ToDate='')
		--	begin
		--	  set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102)) ' 		
		--	end
			set @sqlQuery=@sqlQuery+ 'order by dbo.TA_Tbl_Employee.Employee_code_Id'
		EXEC (@sqlQuery)		
drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeEmailId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_SelectEmployeeEmailId '0','','','SuperAdmin','0'
CREATE    PROCEDURE [dbo].[Proc_TA_SelectEmployeeEmailId]
(	
	@EmployeeName varchar(100),
	@EmployeeCodeId varchar(25),
 	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@ParentId int	
)      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
Declare @RowCountEmployeeID int
 Declare @RowCountEmployeeName int
    create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '')
		begin
			if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = ',')
			begin
				set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
			end
				insert into #EmployeeID
				select value from dbo.split(@EmployeeCodeID,',')
				select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID
	    end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = ',')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end 
				insert into #EmployeeName
				select value from dbo.split(@EmployeeName,',')
				--select * from #EmployeeName
				select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName
		end
 DECLARE @sql AS VARCHAR(8000)      
 DECLARE @CurrentDate AS NVARCHAR(30)
 SET @CurrentDate = GetDate()
 --Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
 --SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then ' ' + cast(Employee_MiddleName as varchar(50)) else ' ' end + Employee_LastName AS 'Employee Name' FROM TA_Tbl_Employee WHERE LevelID in(@LevelId) and Isdeleted=1      
 SET @sql ='SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end +  isnull(Employee_LastName,'''') AS ''Employee Name'','
 SET @sql = @sql + ' Employee_Code_Id + '' - '' + Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end +  isnull(Employee_LastName,'''')  AS ''EmpName'',EmailId,TitleName FROM TA_Tbl_Employee'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'
 SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
SET @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
SET @sql = @sql + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
SET @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	if(@RowCountEmployeeID >0)
		begin
			SET @sql = @sql + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		end
	if(@RowCountEmployeeName >0)
		begin
			SET @sql = @sql + ' Inner join #EmployeeName on #EmployeeName.EmployeeName=TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(Employee_LastName,'''') '
		end
 SET @sql = @sql + ' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1'
--IF(@EmployeeCodeId <> '')
--	BEGIN
--		--SET @sql = @sql + ' AND Employee_Code_Id LIKE ''' + @EmployeeCodeId + '%'''
--		SET @sql = @sql + ' AND Employee_Code_Id = ''' + @EmployeeCodeId + ''' '
--	END
--IF(@EmployeeName <> '')
--	BEGIN
--		SET @sql = @sql + ' AND Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end +  isnull(Employee_LastName,'''') LIKE ''' + cast('%' + @EmployeeName+'%' as nvarchar(100)) + ''''
--	END
if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=''' + @GradeLevel + ''''
	end
SET @sql = @sql + ' AND Employee_Firstname<>''Administrator'' ORDER BY Employee_Code_Id'     
EXEC(@sql)  
drop table #EmpLevel
drop table #EmpDesignation
drop table #LevelRights        
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeeFlexi]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- ALTER  date: 04August08   
-- Modified By	:	Prabakaran.P
-- Modified On	:	26-Mar-09
-- Proc_Ta_SelectEmployeeFlexi '','11/12/2014','','','1',0,0,3,'SuperAdmin',3,1
-- Description:	Report Employee Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectEmployeeFlexi]
	@fromDat varchar(50),
	@ToDat varchar(50),
	@EmployeeId varchar(100),
	--@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@Flexi int, -- 1 - get flexi , 0- get non flexi , 3- both
	--@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(250),
	@ParentId int,
	@isFlexible int,
	@EmpAutoID int
	--@GradeLevel varchar(20)	
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @CompanyId int
	set @CompanyId =@ParentId
	WHILE((SELECT Id from TA_tbl_LevelDetails where id=@CompanyId) <> '') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@CompanyId ) <> 1)
				begin	
					set @CompanyId = (select parentId from TA_tbl_LevelDetails where id=@CompanyId ) 
				END
			ELSE
				BEGIN
					BREAK
				END
		END	
	Declare @intFlexibeEnabled int
	Declare @FlexibleFlag int
	set @FlexibleFlag=(select FlexibleFlag from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	set @intFlexibeEnabled=(select IsFlexible from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
--/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
--(
--	[EffectiveDate] ASC
--) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
/*
select * from #EmpLevel
select * from #EmpDesignation
select * from #EmpType
select * from #EmpCategory
select * from #EmpPay
*/
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''
		set @sqlQuery = @sqlQuery + 'SELECT TA_Tbl_Employee.isFlexible, replace(dept.name,''&amp;'',''&'') as department, dbo.TA_Tbl_Employee.Employee_code_Id as employee_id,dbo.TA_Tbl_Employee.Employee_Id as empAutoId,status = case employee_status  when ''1''  then ''Active''  when ''0'' then ''Inactive'' end '
		set @sqlQuery = @sqlQuery + ' ,isnull(Employee_firstName,'''') + Space(1) + isnull(Employee_LastName,'''') as empname,convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as dateOfBirth,dbo.TA_Tbl_Employee.Nationality,'
		set @sqlQuery = @sqlQuery + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') as TitleName,replace(Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, Convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as dateJoin'		
		set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_Employee '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		--set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'	
		--set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN dbo.TA_Tbl_EmployeePay ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId '	
		set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
		set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
		--set @sqlQuery = @sqlQuery + ' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '
		set @sqlQuery = @sqlQuery + ' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''18000000'') '
--		if(@UserGroupName<>'SuperAdmin')
--		begin
--		set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' '
--		end
		if not(@fromDat='')		
		begin
		set @sqlQuery = @sqlQuery + ' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, ''' +cast( @fromDat as nvarchar(50))   + ''', 102)) '		
		End
		if not (@ToDat='')
		begin
		set @sqlQuery = @sqlQuery + ' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,''' + cast(@todat as nvarchar(50))  + ''', 102)) ' 		
		end
		if not(@EmployeeName='')
		begin
			set @sqlQuery = @sqlQuery + 'and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
		end
		if not (@EmployeeId='')
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.Employee_Code_Id = ''' + cast (@EmployeeId as nvarchar(50)) + ''' '
		end
		if not (@EmployeeCategory=0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeType.TypeId = ' + cast(@EmployeeType as nvarchar(8))
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
		--if not (@Flexi=3)
		--Begin
		--		set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.isFlexible = ' + cast(@Flexi as nvarchar(8))
		--End
		if(@intFlexibeEnabled=1)
			begin
				if(@FlexibleFlag=2)
					begin
						if (@isFlexible=1)
						Begin
								set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.isFlexible = 1'
						End
						if (@isFlexible=2)
						Begin
								set @sqlQuery = @sqlQuery + ' and TA_Tbl_Employee.isFlexible = 0'
						End
					end
			end
		set @sqlQuery = @sqlQuery + ' order by dbo.TA_Tbl_Employee.Employee_code_Id '
	exec(@sqlQuery)
--Remove the temporary tables here   
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
--drop table #EmpPay
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManual]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created by		:	Manjula.P
Created Date	:	05-Aug-2014
Descriptions	:	for selecting employees based on his shift date and shift name to put group manual entry
Proc_TA_SelectEmployeeForGroupManual 2014,8,6,1
*/
CREATE procedure [dbo].[Proc_TA_SelectEmployeeForGroupManual]
(
 @year VARCHAR(5),
 @month VARCHAR(5),
 @date VARCHAR(5),
 @shiftid bigint
)
as
begin
	DECLARE @query VARCHAR(2000)   
	CREATE TABLE #TempShift
	(
	Employee_Id bigint,
	Employee_Code_Id nvarchar(250),
	[Employee Name] nvarchar(500)
	)
	set @query=' SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + '' '' + isnull(Employee_LastName,'' '') AS ''Employee Name''		from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp 
	where psa.[Year]= '+@year+' and psa.[Month]= '+@month+' and psa.EmployeeId = emp.Employee_Id and emp.Isdeleted=0 and emp.Employee_Status=1 '
	if(@shiftid>0)
	begin
	 set @query=@query+' and (psa.Day'+@date+'Shift)='+cast(@shiftid as varchar(50))+'  '
	end
	insert into #TempShift
	exec(@query)
	select * from #TempShift
	drop table #TempShift
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	Proc_TA_SelectEmployeeForGroupManualEntry '3,5,11','SuperAdmin','0','','2011/09/01',0
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]
(
    @LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmployeeCodeID as varchar(30),
	@date datetime,
	@ShiftId int
)      
AS      
BEGIN      
	SET NOCOUNT ON;      
	DECLARE @sql AS VARCHAR(5000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	 IF(@LevelId = '')
		BEGIN
		SET @LevelId = '0'
		END
	 SET @sql ='SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end +  isnull(Employee_LastName,'''') AS ''Employee Name'' FROM TA_Tbl_Employee'
	 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	 SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
	 SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'
	 SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	 SET @sql = @sql + ' INNER JOIN TA_Tbl_PermanentShiftAllocation on TA_Tbl_Employee.Employee_Id=TA_Tbl_PermanentShiftAllocation.EmployeeId'
	 SET @sql = @sql + ' LEFT OUTER JOIN dbo.TA_Tbl_Shift ON TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@date) as nvarchar(10)) + 'Shift = dbo.TA_Tbl_Shift.Shift_Id'
	SET @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	SET @sql = @sql + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	SET @sql = @sql + ' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1  '
	if(@LevelId<>'0')
	Begin
		SET @sql = @sql + ' AND #EmpLevel.LevelId in (' + @LevelId + ') '
	End
	if(@EmployeeCodeID<>'')
	Begin
		SET @sql = @sql + ' AND Employee_Code_Id = '''+ @EmployeeCodeID  + ''' '     
	End
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	SET @sql = @sql + ' AND Employee_Firstname<>''Administrator'' ORDER BY Employee_Code_Id'     
	 EXEC(@sql)          
	drop table #EmpLevel
	drop table #EmpDesignation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 -- Proc_TA_SelectEmployeeForGroupPolicy 1,'50','SuperAdmin','0',null,'Male Policy',1,'','',0
 -- select * from testleavepolicy
 -- Delete from testleavepolicy

CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]   
	(
	 @Employee_ID int,
	 @LevelId varchar(1000)   = Null,          
	 @UserGroupName varchar(250)  = Null,          
	 @GradeLevel varchar(20)  = Null,           
	 @Designation varchar(20)  = Null, 
	 @LeavePolicyName varchar(100)  = Null,
	 @ParentId int,
	 @EmployeeID VarChar(max),
	 @EmployeeName varchar(max),
	 @isNotAllocated bit
	)	                
AS   
BEGIN                
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000)
	DECLARE @CurrentDate AS NVARCHAR(30)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,',')
		end
	--Create table #TempEmployeeDetails(Employee_Id bigint,Employee_Code_Id varchar(20),[Employee Name] varchar(500),DateOfJoining varchar(20),levelid bigint,categoryid int,typeid int,religion int)
	SET @CurrentDate = GetDate()          
	SET @sql ='SELECT Distinct (Employee_Id),Employee_Code_Id,Employee_FirstName + '' '' +  isnull(Employee_LastName,'''') AS ''Employee Name'',convert(nvarchar(20),DateOfJoining,101) as DateOfJoining,TA_Tbl_EmployeeLevel.LevelID,Categoryid,typeid,Ta_tbl_Employee.Religion FROM TA_Tbl_Employee'
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
	SET @sql = @sql + ' inner JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'
	SET @sql = @sql + ' inner JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	SET @sql = @sql + ' inner JOIN TA_Tbl_EmployeeCategory on TA_Tbl_EmployeeCategory.EmployeeId=TA_Tbl_Employee.Employee_Id'
	SET @sql = @sql + ' inner JOIN TA_Tbl_EmployeeType on TA_Tbl_EmployeeType.EmployeeId=TA_Tbl_Employee.Employee_Id'
	SET @sql = @sql + ' inner  JOIN #LevelRights on #LevelRights.LevelId=TA_Tbl_EmployeeLevel.LevelId'                  
	SET @sql = @sql + ' left outer  JOIN TA_Tbl_Religion R ON TA_Tbl_Employee.Religion=R.ID' 
	If Not (@EmployeeId = '')  
		Begin  
			SET @sql = @sql + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End
	If Not (@EmployeeName = '')  
		Begin  
			SET @sql = @sql + ' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		End	
	SET @sql = @sql + ' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 '
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	SET @sql = @sql + ' AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,''' + @CurrentDate + ''', 102) order by EffectiveDate desc) AND'          
	SET @sql = @sql + ' TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,''' + @CurrentDate + ''', 102) order by EffectiveDate desc) '           
	if (@LeavePolicyName!='' and @LeavePolicyName is not null)              
		Begin
			if((select EmployeeCategory from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin
					set @sql=@sql+'and ta_tbl_employee.employee_id in(select Employeeid from TA_Tbl_EmployeeCategory where Categoryid=(
					select EmployeeCategory from ta_tbl_leavepolicy where policyname='''+ @LeavePolicyName+''''+'))' 
				end
			if((select EmployeeType from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin
					set @sql=@sql+'and ta_tbl_employee.employee_id in(select Employeeid from TA_Tbl_EmployeeType where Typeid=(
					select EmployeeType from ta_tbl_leavepolicy where policyname='''+ @LeavePolicyName+''''+'))' 
				end
			if((select Religion from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin	
					set @sql=@sql+'and ta_tbl_employee.Religion in(select Religion from ta_tbl_leavepolicy where policyname='''+ @LeavePolicyName+''''+')' 
				end
			if((select Gender from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!='Both')
				begin	
					set @sql=@sql+'and ta_tbl_employee.Gender in(select Gender from ta_tbl_leavepolicy where policyname='''+ @LeavePolicyName+''''+')' 
				end
		End
	if (@Designation!='' and @Designation is not null)              
		Begin              
			set @sql= @sql +' AND TA_Tbl_EmployeeDesignation.DesignationId = '''+ @Designation+ ''''                
		End        
	if(@UserGroupName<>'SuperAdmin')          
		begin          
			SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''          
		end
	SET @sql = @sql + ' AND Employee_Firstname<>''Administrator'''
	if(@isNotAllocated=1)
	BEGIN
	SET @sql = @sql + ' and TA_Tbl_Employee.Employee_Id not in(
		select E.Employee_Id from TA_Tbl_Employee E
		inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
		inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=ELP.YearSettingId
		where YS.IsActive=1)'
	END
	else
	BEGIN
	SET @sql = @sql + ' and TA_Tbl_Employee.Employee_Id in(
		select E.Employee_Id from TA_Tbl_Employee E
		inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
		inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=ELP.YearSettingId
		where YS.IsActive=1)'
	END
	EXEC(@sql + ' order by 1')
	--if(@isNotAllocated=1)
	--BEGIN
	--	select * from #TempEmployeeDetails where Employee_Id not in(
	--	select E.Employee_Id from TA_Tbl_Employee E
	--	inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
	--	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=ELP.YearSettingId
	--	where YS.IsActive=1)
	--END
	--ELSE
	--BEGIN
	--	select * from #TempEmployeeDetails where Employee_Id in(
	--	select E.Employee_Id from TA_Tbl_Employee E
	--	inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
	--	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=ELP.YearSettingId
	--	where YS.IsActive=1)
	--END	
	drop table #LevelRights                  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForPopup]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	Proc_TA_SelectEmployeeForPopup '10','SuperAdmin','0',10,'100','',0,0
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForPopup]
(
	@Employee_ID int,
	@LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@ParentId int,
	@EmployeeId varchar(Max),
	@EmployeeName varchar(Max),
	@EmpCategoryShift int=0,
	@EmpTypeShift int=0,
	@isFrom nvarchar(100)
)
AS
BEGIN      
	-- SET NOCOUNT ON added to prevent extra result sets from      
	-- interfering with SELECT statements.      
	SET NOCOUNT ON;      
	DECLARE @sql AS VARCHAR(5000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId] ,[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @CurrentDate,@EmployeeId,''	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @CurrentDate,@EmployeeId,@EmpTypeShift	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @CurrentDate,@EmployeeId,@EmpCategoryShift
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	if(@EmployeeId is not null and @EmployeeId <> '')
		begin
			if(SUBSTRING(@EmployeeId,LEN(@EmployeeId),len(@EmployeeId)) = ',')
				begin
					set @EmployeeId=SUBSTRING(@EmployeeId,0,len(@EmployeeId))
				end	
			insert into #EmployeeID	select value from dbo.split(@EmployeeId,',')
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = ',')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end
			insert into #EmployeeName select value from dbo.split(@EmployeeName,',')
		end
	IF(@LevelId = '')
	BEGIN
		SET @LevelId = '0'
	END
	SET @sql ='SELECT E.Employee_Id,E.Employee_Code_Id,Employee_FirstName + '' '' +  isnull(Employee_LastName,'''') AS ''Employee Name'',
	CompOff_Eligible FROM TA_Tbl_Employee E'
	SET @sql = @sql + '	INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id '	
	SET @sql = @sql + '	INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id '
	SET @sql = @sql + '	INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId'
	SET @sql = @sql + '	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'	
	SET @sql = @sql + '	INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id '
	SET @sql = @sql + '	INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id '
	SET @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	if(@EmployeeId is not null and @EmployeeId <> '')
	begin
		SET @sql = @sql + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=E.Employee_Code_Id '
	end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			SET @sql = @sql + ' Inner join #EmployeeName on #EmployeeName.EmployeeName=E.Employee_FirstName + '' '' + isnull(Employee_LastName,'''') '
		end
	SET @sql = @sql + ' WHERE E.Isdeleted=0 AND E.Employee_Status=1 '
	if(@UserGroupName<>'SuperAdmin')
	begin
		SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
	end
	if(@isFrom='CompOff')
		begin
			set @sql = @sql + ' AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 '
		end
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	if(@EmployeeName is not null and @EmployeeName <> '')
	begin
		SET @sql = @sql + ' and (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
	end
	SET @sql = @sql + ' AND Employee_Firstname<>''Administrator'' ORDER BY Employee_Code_Id'     
	EXEC(@sql)          
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	[Proc_TA_SelectEmployeeForShiftAlloc] '26','SuperAdmin',0,null,26,'',0,0,1
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
Modified by	:	A.Amsaveni on 28/09/2013 to give a space between Employee firstname and lastname
Modified by	:	Manjula.P on 20-Aug-2014 for searching by employee type and employee category @EmpCategoryShift,@EmpTypeShift
select * from TA_Tbl_EmployeeLevel
*/
CREATE     PROCEDURE [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]
(
@Employee_ID int,
@LevelId varchar(8000),
@UserGroupName varchar(250),
@GradeLevel varchar(20)	,
@EmployeeCodeID as varchar(max),
@ParentId int,
@EmployeeName varchar(max),
@EmpCategoryShift int=0,
@EmpTypeShift int=0,
@Religion int
)      
AS      
BEGIN     
	SET NOCOUNT ON;
	Declare @RowCountEmployeeID int
	Declare @RowCountEmployeeName int
	DECLARE @sql AS VARCHAR(8000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '')
		begin
			if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = ',')
				begin
					set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
				end	
			insert into #EmployeeID	select value from dbo.split(@EmployeeCodeID,',')
			select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID
		end
	if(@EmployeeName is not null and @EmployeeName <> '')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = ',')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end
			insert into #EmployeeName select value from dbo.split(@EmployeeName,',')
			select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName
		end
	SET @CurrentDate = GetDate()
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId],[EffectiveDate] ASC
	) ON [PRIMARY]	
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	IF(@LevelId = '')
		BEGIN
			SET @LevelId = '0'
		END
	SET @sql ='SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + '' '' + isnull(Employee_LastName,'' '') AS ''Employee Name'' FROM TA_Tbl_Employee'
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId'
	SET @sql = @sql + ' inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=TA_Tbl_Employee.Employee_Id 
						inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId '
	SET @sql = @sql + ' inner join ta_tbl_employeecategory EC on EC.EmployeeId=TA_Tbl_Employee.Employee_Id 
						inner join ta_tbl_category C on C.CategoryId=EC.CategoryId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId'
	SET @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
	SET @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '
	if(@RowCountEmployeeID >0)
		begin
			SET @sql = @sql + ' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id '
		end
	if(@RowCountEmployeeName >0)
		begin
			SET @sql = @sql + ' Inner join #EmployeeName on #EmployeeName.EmployeeName=TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(Employee_LastName,'''') '
		end
	SET @sql = @sql + ' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 AND Employee_Firstname<>''Administrator'''
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	IF(@EmpCategoryShift>0)
		BEGIN
			SET @sql=@sql+' AND C.CategoryId = '+cast(@EmpCategoryShift as varchar(50))+' '
		END
	IF(@EmpTypeShift>0)
		BEGIN
			SET @sql=@sql+' AND TP.TypeId = '+cast(@EmpTypeShift as varchar(50))+' '
		END    
	IF(@Religion>1)
		BEGIN
			SET @sql=@sql+' AND TA_Tbl_Employee.Religion = '+cast(@Religion as varchar(50))+' '
		END
	set @sql=@sql+' ORDER BY Employee_Code_Id '
	EXEC(@sql)          
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeGroupName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectEmployeeGroupName
Description	:	Get groupName from Ta_tbl_usergroup
Tables Included	:	ta_tbl_employee, Ta_tbl_usergroup
Created By	:	Prabakaran
Created On	:	22-Aug-07
Modified By	:
Modified On	:
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeGroupName]
@employee_Id int =12
as
BEGIN
	SET NOCOUNT ON
	select ug.groupName as GroupName,ug.hasSpecialRights,isnull(ug.ReportsBasedOn,0)ReportsBasedOn,ug.IndividualUsers from ta_tbl_employee e
	inner join Ta_tbl_usergroup ug on ug.groupId=e.UserGroup_Id where e.employee_Id=@employee_Id and e.isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeLevel]
	@EmployeeId as int
AS
BEGIN
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= getdate() and EL.LevelId is not null
	select TA_Tbl_EmployeeLevel.levelID from TA_Tbl_EmployeeLevel
	Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId 
	where TA_Tbl_EmployeeLevel.EmployeeId=@EmployeeId
--Remove the temporary tables here   
drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeLiveAttedance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectEmployeeLiveAttedance null,'1001','01/01/1900','01/01/1900',null,'SuperAdmin','1','0',0,'',3,1
/*

exec Proc_TA_SelectEmployeeLiveAttedance @Employee_FirstName=N'',@Employee_Code_Id=N'MK1002',@StartDate='2024-05-03 00:00:00',@EndDate='2024-05-03 00:00:00',
@EmpSwipeCard='',@UserGroupName=N'SuperAdmin',@UserLevels=N'1',@GradeLevel=N'0',@ParentID=9,@Type='',@isImported=3,@LoginEmployeeAutoId=1

*/

-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeLiveAttedance] 
	-- Add the parameters for the stored procedure here
	@Employee_FirstName nvarchar(50) = null, 
	@Employee_Code_Id nvarchar(15) = 'A001', 
	@StartDate datetime = '2024-05-03', 
	@EndDate datetime = '2024-05-03' ,
	@EmpSwipeCard varchar(10)='',
	@UserGroupName NVARCHAR(250)='SuperAdmin',
	@UserLevels nvarchar(2000)='1',
	@GradeLevel nvarchar(20)='0',
	@ParentID int=1,
	@Type varchar(15)='',
	@isImported int=3,
	@LoginEmployeeAutoId int =1   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	if(@StartDate != '1900-01-01')
	begin
		declare @EMP int
		
		
	Select ManualTimeEntry_Id,TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id as Emp_Id,ManualTimeEntry_Employee_Id as EmployeeCodeid,case when  ManualTimeEntry_Date !='' then Convert(varchar,ManualTimeEntry_Date,101) else 
	Convert(varchar,ManualTimeEntry_OutDate,101) end as ManualTimeEntry_Date , Case when ManualTimeEntry_InDate!='' then Convert(varchar,ManualTimeEntry_InDate,101) else 
	Convert(varchar,ManualTimeEntry_OutDate,101) end as INOUTDate,
	Case when ManualTimeEntry_InPunchType!='' then ManualTimeEntry_InPunchType else ManualTimeEntry_OutPunchType end as PunchType,
	case when ManualTimeEntry_InTime!='' then Convert(varchar,ManualTimeEntry_InTime,101) else ManualTimeEntry_OutTime end as PunchTime,
	ManualTimeEntry_Status as ManualTimeEntry_Status,
	Latitude_value ,Longitude_value as Longitude 
	 from TA_Tbl_ManualTimeEntry
	left Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id
	where TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id =@Employee_Code_Id and 
	--=@Employee_Code_Id and
	ManualTimeEntry_Status='Approved' 
	and TA_Tbl_Employee.Employee_Status = 1 and TA_Tbl_Employee.Isdeleted=0 
	and TA_Tbl_ManualTimeEntry.IsImported=2 and  
	(TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate between @StartDate and @EndDate) or 
	(TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate between @StartDate and @EndDate)
	and Latitude_value!='' and Longitude_value!='' 

	 --and ManualTimeEntry_InPunchType !='Break In'
	--and ManualTimeEntry_InPunchType !='Break Out'
	--and Longitude_value!=null TA_Tbl_Employee.Employee_Status = 0 and TA_Tbl_Employee.Isdeleted=0 and
	--and ManualTimeEntry_InPunchType !='Break In'
	--and ManualTimeEntry_InPunchType !='Break Out'

	end 
	else
	begin 

	Select ManualTimeEntry_Id,TA_Tbl_Employee.Employee_Id as Emp_Id,ManualTimeEntry_Employee_Id as EmployeeCodeid,case when  ManualTimeEntry_Date !='' then Convert(varchar,ManualTimeEntry_Date,101) else 
	Convert(varchar,ManualTimeEntry_OutDate,101) end as ManualTimeEntry_Date , Case when ManualTimeEntry_InDate!='' then Convert(varchar,ManualTimeEntry_InDate,101) else 
	Convert(varchar,ManualTimeEntry_OutDate,101) end as INOUTDate,
	Case when ManualTimeEntry_InPunchType!='' then ManualTimeEntry_InPunchType else ManualTimeEntry_OutPunchType end as PunchType,
	case when ManualTimeEntry_InTime!='' then Convert(varchar,ManualTimeEntry_InTime,101) else ManualTimeEntry_OutTime end as PunchTime,
	ManualTimeEntry_Status as ManualTimeEntry_Status,
	Latitude_value ,Longitude_value as Longitude 
	 from TA_Tbl_ManualTimeEntry
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id
	where TA_Tbl_Employee.Employee_Status = 1 and TA_Tbl_Employee.Isdeleted=0 and ManualTimeEntry_Status='Approved'
	and TA_Tbl_ManualTimeEntry.IsImported=2 and Latitude_value!='' and Longitude_value!='' 

	

	end


	
	
	--print @StartDate

	--select * from TA_Tbl_ManualTimeEntry
	








 --   -- Insert statements for procedure here
	--create table #LevelRights(LevelId int)
	--insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--DECLARE @Isdel as int
	--SET @Isdel = 0
	--Declare @SqlQuery as varchar(5000)
	--set @SqlQuery = ''
	--DECLARE @dateFormat as int
	--declare @isReportingto as int
	--select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	--create table #EmployeeIds(EmpAutoId int)
 --   insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
 --   insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
	--Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	--declare @IndividualUserStatus int
	--set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
	
	--select	M.ManualTimeEntry_Employee_id as EmployeeCodeid, 
	--		M.ManualTimeEntry_Id,
	--		Convert(varchar,M.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date,
	--		M.Emp_Id,
	--		--	case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_InPunchType
	--		--		else M.ManualTimeEntry_InPunchType 
	--		--end PunchType,

	--		--Case when M.ManualTimeEntry_InTime!='' then M.ManualTimeEntry_InTime else ManualTimeEntry_OutTime End As PunchTime,

	--		--case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,@dateFormat),' ','-') 
	--		--		else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, @dateFormat) 
	--		--end AS ManualTimeEntry_InDate,	
	--		--M.ManualTimeEntry_InTime,
	--		--Case when M.ManualTimeEntry_InPunchType!='' then M.ManualTimeEntry_InPunchType else M.ManualTimeEntry_OutPunchType End As PunchType,
				
	--		--case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,@dateFormat),' ','-') 
	--		--		else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, @dateFormat) 
	--		--end AS ManualTimeEntry_OutDate,	
	--		--M.ManualTimeEntry_OutTime,

	--		--case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_OutPunchType
	--		--		else M.ManualTimeEntry_OutPunchType 
	--		--end ManualTimeEntry_OutPunchType,

	--		--case	when Latitude_value is not null and Longitude_value is not null then Clock_Address 
	--		--		else M.ManualTimeEntry_Reason 
	--		--end ManualTimeEntry_Reason,

	--		M.ManualTimeEntry_Status,
	--		E.Employee_FirstName + SPACE(1) + isnull(E.Employee_LastName,'''') AS Employee_Name,
	--		M.IsOnDuty,
	--		EntryType=case when M.IsImported=0 then 'M / D' 
	--			 when M.IsImported=1 then 'I' 
	--			 when M.IsImported=2 then 'Mo' 
	--			 when M.IsImported=3 then 'GA'
	--		end,
	--		ProcessStatus=case	when Clk_Process='N' then 'NP'
	--							when Clk_Process='Y' then 'P'	
	--					  END
	--					,
	--					M.Latitude_value,M.Longitude_value
	--FROM TA_Tbl_ManualTimeEntry as M
	--INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	--INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id
	--and M.Isdeleted=0 and E.IsDeleted=0 and E.Employee_Status=1 and ys.IsActive=1 

	--LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	--LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	--INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId 
	--LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	--INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid	

	--where E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id 
	--AND M.IsOnDuty=0
	----AND EDesig.EffectiveDate=(Select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id order by EffectiveDate desc) 
	----AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
	----and ((@IndividualUserStatus  = 0) or (E.Employee_Id=@LoginEmployeeAutoId))
	----and (@UserGroupName='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	----and (@isReportingto = 0 or (E.Employee_ID IN (select * from #EmployeeIds)))

	--and (isnull(@Employee_Code_Id,'')='' or E.Employee_Code_Id like cast(@Employee_Code_Id+'%' as nvarchar(50)))
	--and (isnull(@Employee_FirstName,'')='' or (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,'') like cast(@Employee_FirstName+'%' as nvarchar(100)))) 
	--and ((@Type<>'Both' and M.IsOnDuty != 1) or (@Type='ODEntry' and M.IsOnDuty = 1) )
	--and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_InDate between @StartDate and @EndDate))
	--and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_OutDate between @StartDate and @EndDate))
	----and  M.IsImported =Case when @IsImported=3 then @IsImported else '' End
	--Order by M.ManualTimeentry_id desc

	--Execute (@SqlQuery)
	--drop table #LevelRights
	--drop table #EmployeeIds



END
--select ManualTimeEntry_Id,ManualTimeEntry_Date,Case when ManualTimeEntry_InPunchType!='' then ManualTimeEntry_InPunchType else ManualTimeEntry_OutPunchType End As PunchType, Case when ManualTimeEntry_InTime!='' then ManualTimeEntry_InTime else ManualTimeEntry_OutTime End As PunchTime from TA_Tbl_ManualTimeEntry where  IsImported =Case when @IsImported=3 then @IsImported else '' End

--Select * From TA_Tbl_Employee

--Select * From TA_tbl_GeoFencingAllocation

--Select * From TA_Tbl_userRights where  PageId=325
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSatDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-Apr-2013
-- Description:	Get the Saturday value 
-- =============================================
create PROCEDURE [dbo].[Proc_TA_SelectEmployeeSatDetails]
	-- Add the parameters for the stored procedure here
	@Empid int,
	@ToDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id	
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
    -- Insert statements for procedure here
	SELECT C.Sat_WorkHrs from #EmpCategory EC
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId 
	where EmployeeId=@Empid
	drop table #EmpCategory
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_SelectEmployeesBasedOnRoutes 1,'04/29/2011'
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]
(
   @RouteId int,
   @InDate varchar(15),
   @LoginEmployeeId int,
   @Parameter varchar(10)
)
AS
BEGIN
create table #TempProcessedData(Employee_Code_Id varchar(20))
insert into #TempProcessedData select Employee_Code_Id from TA_Tbl_ProcessedData
where Attendance = 'Present' and Date = @InDate
if(@Parameter = 'Select')
	BEGIN
		select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + ' ' + emp.Employee_LastName) as EmployeeName from TA_Tbl_Employee emp,
		TA_Tbl_RouteMaster rm,
		#TempProcessedData p 
		where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and rm.Id = @RouteId
	END
else if(@Parameter = 'Add')
	BEGIN
        insert into TA_Tbl_TempShiftAllocation 
        select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + ' ' + emp.Employee_LastName),@LoginEmployeeId from TA_Tbl_Employee emp,
		TA_Tbl_RouteMaster rm,#TempProcessedData p 
		where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and rm.Id = @RouteId
		select * from TA_Tbl_TempShiftAllocation where LoginEmployeeId=@LoginEmployeeId
	END
--where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and p.Attendance = 'Present' and rm.Id = @RouteId and p.Date = @InDate
--select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + ' ' + emp.Employee_LastName) as EmployeeName from TA_Tbl_Employee emp
--inner join TA_Tbl_RouteMaster rm on emp.Bus_Id = rm.Id and rm.Id = @RouteId
--inner join (select * from TA_Tbl_ProcessedData where Attendance = 'Present' and Date='04/29/2011') as p on p.Employee_Code_Id = emp.SwipeCardNo
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesByIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created by		:	Manjula.P
Created Date	:	07-Aug-2014
Descriptions	:	Selecting employee details by employees ids
*/
create proc [dbo].[Proc_TA_SelectEmployeesByIds]
(
@Employee_Id nvarchar(max)
)
as
begin
	select Employee_Id as EmpId,Employee_Code_Id as EmployeeId,Employee_FirstName + ' ' + isnull(Employee_LastName,' ') AS 'EmployeeName' from TA_Tbl_Employee where Employee_Id in (select Value from dbo.Split(@Employee_Id,','));
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeesForBL]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectEmployeesForBL]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select TA_Tbl_Employee.Employee_Id,TA_Tbl_Employee.SwipeCardNo,Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota,TA_Tbl_YearSetting.FromDate,TA_Tbl_YearSetting.ToDate from Ta_Tbl_EmployeeBonusLeave
    INNER JOIN TA_Tbl_Employee ON  TA_Tbl_Employee.Employee_Id=Ta_Tbl_EmployeeBonusLeave.EmployeeId
    INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearSetting.YearSettings_Id=Ta_Tbl_EmployeeBonusLeave.YearSettingId
    Where TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_YearSetting.IsActive=1 and Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota >0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeShift] (@Shiftid int)  
AS  
 BEGIN  
if(@shiftid <> -1)
SELECT Shift_Name,* FROM TA_Tbl_Shift WHERE Shift_Id=@Shiftid and isdeleted=0  
else
Select 'Off'
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]  
 -- Add the parameters for the stored procedure here  
 @maxID int  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
 SELECT isnull(Employee_FirstName,'') + Space(1) + isnull(Employee_LastName,'') as EmployeeName, SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Id = @maxID  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeTransfer]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeTransfer]
(
	@empID varchar(20), 
	@tnsfrfrmDte varchar(20), 
	@trnsfrToDte varchar(20), 
	@empName varchar(150)
)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT TrnsfrID, Emp_AutoID, Trnsfr_frm, Trnsfr_To, Trnsfr_EtyDteTme, Trnsfr_Dte, Etry_RsdBy, NwDsgtonID, NwReprtngTo, 
	NwApprvlAuthrty, Remarks, IsImprtd, Trnsfr_status FROM ta_tbl_transfer T
	inner join TA_Tbl_Employee e on T.Emp_AutoID=e.Employee_Id
	where (isnull(@empID,'')='' or e.Employee_Code_Id=@empID)
	and (ISNULL(@empName,'')='' or e.Employee_FirstName=@empName)
	and (Trnsfr_Dte>=@trnsfrToDte and Trnsfr_Dte<=@trnsfrToDte)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_SelectEmpName 1,'787','SuperAdmin','0','0,21',0,'' 
--exec Proc_TA_SelectEmpName @Employee_ID=1,@EmpCode='bb002',@UserGroupName='SuperAdmin',@GradeLevel='0',@level='0',@ParentID=0,@isFrom=N'CompOff'
CREATE     PROCEDURE [dbo].[Proc_TA_SelectEmpName] 
(
	@Employee_ID int=1,
	@EmpCode varchar(50)='bb003',
	@UserGroupName varchar(250)='SuperAdmin',
	@GradeLevel varchar(20)='',
	@level varchar(2000)='',
	@ParentID int='',
	@isFrom nvarchar(50)='CompOff'
)
AS    
BEGIN  
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000) 
	DECLARE @Isdel int  
	SET @Isdel=0 
	
	SET @sql ='Select E.Employee_Id,E.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') AS ''Employee Name'',E.CompOff_Eligible,e.Emailid,TitleName ,
	E1.Employee_FirstName + '' '' + isnull(e1.Employee_LastName,'''') AS ''ReportingTo_Name'',
	E2.Employee_FirstName + '' '' + isnull(e2.Employee_LastName,'''') AS ''LeaveApproval_Name'',
	DepartmentName=dbo.Fn_GetWholeLevelName(TA_Tbl_EmployeeLevel.LevelId),EmpCurrentLevel=TA_Tbl_EmployeeLevel.LevelId
	' 
	SET @sql = @sql + ' From TA_Tbl_Employee E INNER JOIN TA_Tbl_EmployeeDesignation ON E.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	SET @sql = @sql + ' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId '
	SET @sql = @sql + ' left outer JOIN ta_tbl_employee E1 on E1.Employee_Id=E.Reporting_To'
	SET @sql = @sql + ' left outer JOIN ta_tbl_employee E2 on E2.Employee_Id=E.Leave_Sanc_Authority'
	SET @sql = @sql + ' WHERE E.Employee_Code_Id=''' + @EmpCode + ''' '  
	SET @sql = @sql + ' AND  E.Employee_Code_Id<>''18000000''  AND E.IsDeleted=''' + cast(@Isdel as nvarchar(20)) + '''  AND E.Employee_Status=''1'' '
	SET @sql = @sql + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)'
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
    if(@isFrom='CompOff')
		begin
			set @sql = @sql + ' and E.CompOff_Eligible=1 and E.OT_Eligible=1 '  
		end
	if(@UserGroupName<>'SuperAdmin')
		begin
			SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
		end
	exec(@sql)
	drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name : Proc_TA_SelectEncashmentDetailsByEmpId 15,3,'1','NormalUser',0   
Description : select Encashment details    
Tables Included : TA_Tbl_Encashment     
Created By : Prabakaran    
Created On : 28-Nov-07    
Modified By :     
Modified On :     
*/    
CREATE      procedure [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]      
@EmployeeId bigint,    
@GradeLevel varchar(20),    
@LevelRights varchar(2000),
@UserGroupName varchar(250),
@ParentID int      
as    
BEGIN    
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as varchar(8000)          
	set @sqlQuery = ''          
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	set @sqlQuery = @sqlQuery + ' select (e.Employee_FirstName + '' '' +  isnull(e.Employee_LastName,'' '')) as EmployeeName,e.Employee_Code_Id,ld.name,Et.EncashmentId,Et.EmployeeId, 
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, Et.DateOfEncashment,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, Et.DateOfEncashment, '+cast(@dateFormat as varchar(100))+') end	AS DateOfEncashment,lt.LeaveType as LeaveType,Et.NumberOfDays as NumberOfDays,Et.Reason as Reason,lt.LeaveType_Id as LeaveTypeId '    
	set @sqlQuery = @sqlQuery + ' from TA_Tbl_Encashment Et '     
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_LeaveType lt on Et.LeaveTypeId = lt.LeaveType_Id '    
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_employee e on e.Employee_Id=Et.EmployeeId '    
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId '    
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation eDesig ON Et.EmployeeId = eDesig.EmployeeId '    
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id  '    
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=eDesig.DesignationId '    
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '    
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=Et.YearSettingId '    
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=LD.id '    
	set @sqlQuery = @sqlQuery + ' where ys.IsActive=1 and Et.IsDeleted = 0  and e.isdeleted=0 and Et.EmployeeId=' + cast(@EmployeeId as nvarchar(50)) +' and '    
	set @sqlQuery = @sqlQuery + ' el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  Et.DateOfEncashment order by EffectiveDate desc) '    
	set @sqlQuery = @sqlQuery + ' and eDesig.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = Et.EmployeeId and EffectiveDate <=CONVERT(DATETIME,''' + cast(getdate() as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '    
	set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level >=' + cast(@GradeLevel as nvarchar(100))      
	exec (@sqlQuery) 
	drop table #LevelRights   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Proc_TA_SelectEncashmentDetailsSuperAdmin '1','','','01/01/2007','12/23/2012' ,'','Superadmin',0 
*/  
CREATE procedure [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]  
@Employee_ID int,
@LevelRights varchar(8000) = null,   
@Employee_Code_Id nvarchar(50) = null,   
@Employee_FirstName varchar(50) = null,   
@StartDate datetime = '01/01/1900',   
@EndDate datetime = '01/01/1900',
@EmpSwipeCard varchar(20),
@UserGroupName varchar(250),
@ParentID int    
as    
BEGIN 
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	declare @SqlQuery as varchar(8000)   
	set @SqlQuery = ''
	set @SqlQuery = @SqlQuery + 'select (e.Employee_FirstName + '' '' +  isnull(e.Employee_LastName,'' '')) as EmployeeName,e.Employee_Code_Id,ld.name,Et.EncashmentId,Et.EmployeeId,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, Et.DateOfEncashment,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, Et.DateOfEncashment, '+cast(@dateFormat as varchar(100))+') end	AS DateOfEncashment,
	lt.LeaveType as LeaveType,Et.NumberOfDays as NumberOfDays,Et.Reason as Reason,lt.LeaveType_Id as LeaveTypeId '  
	set @SqlQuery = @SqlQuery + ' from TA_Tbl_Encashment Et '  
	set @SqlQuery = @SqlQuery + ' inner join TA_Tbl_LeaveType lt on Et.LeaveTypeId = lt.LeaveType_Id '  
	set @SqlQuery = @SqlQuery + ' inner join Ta_tbl_employee e on e.Employee_Id=Et.EmployeeId '  
	set @SqlQuery = @SqlQuery + ' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId '  
	set @SqlQuery = @SqlQuery + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '  
	set @SqlQuery = @SqlQuery + ' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=Et.YearSettingId ' 
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=ld.id '  
	set @SqlQuery = @SqlQuery + ' where ys.IsActive=1 and Et.IsDeleted = 0  and e.isdeleted=0 and '  
	set @SqlQuery = @SqlQuery + ' el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  Et.DateOfEncashment order by EffectiveDate desc) '  
	If not(@Employee_Code_Id = '' or @Employee_Code_Id is null)  
		Begin  
			Set @SqlQuery = @SqlQuery + ' and e.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''  
		End  
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sqlQuery = @sqlQuery + ' And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If not(@Employee_FirstName = '' or @Employee_FirstName is null)  
		Begin  
		Set @SqlQuery = @SqlQuery + ' and (dbo.TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''') like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''')'
			--Set @SqlQuery = @SqlQuery + ' and e.Employee_FirstName like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''''  
		End  
	If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
		Begin  
			set @SqlQuery = @SqlQuery + ' and Et.DateOfEncashment between convert(datetime,''' + cast(@StartDate as nvarchar(11)) + ' 00:00:00.000'', 101) and convert(datetime,''' + cast(@EndDate as nvarchar(11)) + ' 23:59:59.000'',101)'  
		End  
	Execute (@SqlQuery)  
	drop table #LevelRights  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
-- Proc_TA_SelectEntranceDetails 'A', 0, 'SuperAdmin' 
CREATE PROCEDURE [dbo].[Proc_TA_SelectEntranceDetails]
(    
	@TYPE CHAR(1)='',    
	@EntranceID INT,
	@UserGroupName nVarchar(50)    
)    
AS  
BEGIN    
	set nocount on
	DECLARE @Isdeleted INT
	SET @Isdeleted=0
	Create table #tempEntrance(ID int,Name nvarchar(510),Entrance_Id int,Entrance_Name nvarchar(100),Entrance_Description nvarchar(500),
	NoOfInTerminals int,NoOfOutTerminals int,IsDeleted nvarchar(10),flag int)
	Create table #Tempclkrawdata(id int identity(1,1),CLK_DEVICEID varchar(30))
	CREATE NONCLUSTERED INDEX IDX_CLK_DEVICEID ON [dbo].#Tempclkrawdata(CLK_DEVICEID ASC) ON [PRIMARY]
	insert into #Tempclkrawdata	
	select distinct CLK_DEVICEID from TA_Tbl_Clk_RawData
	where CLK_DEVICEID not in
	(
		select T.Terminal_ReaderID from TA_Tbl_Terminal T
		inner join TA_Tbl_Entrance_INOUTDetails EIO on T.Terminal_Id=EIO.Reader_Id
		inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
		where flag=1
	)
	update TA_Tbl_Entrance set flag=1 from TA_Tbl_Entrance E
	inner join TA_Tbl_Entrance_INOUTDetails EIO on E.Entrance_Id=EIO.Entrance_Id
	inner join TA_Tbl_Terminal T on T.Terminal_Id=EIO.Reader_Id
	inner join #Tempclkrawdata TC on TC.CLK_DEVICEID=T.Terminal_ReaderID
	where E.flag!=1
	update TA_Tbl_Entrance set flag=1 from TA_Tbl_Entrance E
	inner join TA_Tbl_Entrance_INOUTDetails EIO on E.Entrance_Id=EIO.Entrance_Id
	inner join TA_Tbl_ManualTimeEntry M on (EIO.Reader_Id = M.ManualTimeEntry_InReaderID OR EIO.Reader_Id = M.ManualTimeEntry_OutReaderID)
	where E.flag!=1
	IF (@TYPE='A')    
	BEGIN
		IF(@UserGroupName = 'SuperAdmin')
			BEGIN 
				insert into #tempEntrance
				SELECT '',O.levelName,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,'','',
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E     
				LEFT OUTER JOIN TA_Tbl_Level O ON O.levelID=E.OrgLevel_Id where E.Entrance_Name!='TimecheckPhase'
			END
		ELSE
			BEGIN   
				insert into #tempEntrance
				SELECT '',O.levelName,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,'','',
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_Level O ON O.levelID=E.OrgLevel_Id WHERE E.Isdeleted=@Isdeleted
				and E.Entrance_Name!='TimecheckPhase'   
			END
	END
	ELSE IF (@TYPE='P')    
	BEGIN
		IF(@UserGroupName = 'SuperAdmin')
			BEGIN 
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID
				and E.Entrance_Name!='TimecheckPhase'
			END
		ELSE
			BEGIN
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID AND E.IsDeleted=@Isdeleted    
				and E.Entrance_Name!='TimecheckPhase'   
			END
	END
	ELSE If (@TYPE='I')    
	BEGIN
		IF(@UserGroupName = 'SuperAdmin')
			BEGIN 
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID 
				and E.Entrance_Name!='TimecheckPhase'   
			END
		ELSE
			BEGIN
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE E.Isdeleted=@Isdeleted AND Entrance_Id=@EntranceID    
				and E.Entrance_Name!='TimecheckPhase'   
			END
	END
    select * from #tempEntrance
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Modified date: <23-11-2016 12.44>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]
AS
BEGIN
	SET NOCOUNT ON;
    Select * from TA_Tbl_Entrance E where Entrance_Name='TimecheckPhase' and IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceINOUTDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Procedure Name : Proc_TA_SelectEntranceINOUTDetails
-- Tables Used : TA_Tbl_Entrance_InOutDetails,TA_Tbl_Terminal
-- Author : Kumuthini.L
-- Created On : 17-Mar-2008
-- Modified by:Manikandan.R
-- on: 22-11-2016 17.36
-- Purpose : Used to get the In Terminal or Out Terminal Details based on the Entrance Id and Type
CREATE  PROCEDURE [dbo].[Proc_TA_SelectEntranceINOUTDetails]
(
	@Entrance_Id INT,
	@PunchType nVarchar(10) 
)
AS
BEGIN
	SET NOCOUNT ON
    SELECT T.Terminal_Name,T.Terminal_ReaderID,E.Reader_Id FROM TA_Tbl_Entrance_InOutDetails E
	Inner join TA_Tbl_Terminal T on E.Reader_Id = T.Terminal_Id 
    WHERE E.Entrance_Id = @Entrance_Id AND Type = @PunchType
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectFectingEmployeePunches]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectFectingEmployeePunches]
	-- Add the parameters for the stored procedure here

@Employee_FirstName nvarchar(50) = null, 
	@Employee_Code_Id nvarchar(15) = null, 
	@StartDate datetime = '01/01/1900', 
	@EndDate datetime = '01/01/1900' ,
	@EmpSwipeCard varchar(10)='',
	@UserGroupName NVARCHAR(250)='SuperAdmin',
	@UserLevels nvarchar(2000)='',
	@GradeLevel nvarchar(20)='',
	@ParentID int=1,
	@Type varchar(15)='',
	@LoginEmployeeAutoId int ='' ,
	@IsImported int=3
	As
BEGIN
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @Isdel as int
	SET @Isdel = 0
	Declare @SqlQuery as varchar(5000)
	set @SqlQuery = ''
	DECLARE @dateFormat as int
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	declare @IndividualUserStatus int
	set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
	
	select	M.ManualTimeEntry_Employee_id as EmployeeCodeid, 
			M.ManualTimeEntry_Id,
			Convert(varchar,M.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, @dateFormat) 
			end AS ManualTimeEntry_InDate,	
			M.ManualTimeEntry_InTime,
			case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_InPunchType
					else M.ManualTimeEntry_InPunchType 
			end ManualTimeEntry_InPunchType,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, @dateFormat) 
			end AS ManualTimeEntry_OutDate,	
			M.ManualTimeEntry_OutTime,
			case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_OutPunchType
					else M.ManualTimeEntry_OutPunchType 
			end ManualTimeEntry_OutPunchType,
			case	when Latitude_value is not null and Longitude_value is not null then Clock_Address 
					else M.ManualTimeEntry_Reason 
			end ManualTimeEntry_Reason,
			M.ManualTimeEntry_Status,
			E.Employee_FirstName + SPACE(1) + isnull(E.Employee_LastName,'''') AS Employee_Name,
			M.IsOnDuty,
			EntryType=case when M.IsImported=0 then 'M / D' 
				 when M.IsImported=1 then 'I' 
				 when M.IsImported=2 then 'Mo' 
				 when M.IsImported=3 then 'GA'
			end,
			ProcessStatus=case	when Clk_Process='N' then 'NP'
								when Clk_Process='Y' then 'P'	
						  END
	FROM TA_Tbl_ManualTimeEntry as M
	INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id
	and M.Isdeleted=0 and E.IsDeleted=0 and E.Employee_Status=1 and ys.IsActive=1 
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId 
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid	




	where E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND M.IsOnDuty=0
	AND EDesig.EffectiveDate=(Select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id order by EffectiveDate desc) 

	AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)

	and ((@IndividualUserStatus  = 0) or (E.Employee_Id=@LoginEmployeeAutoId))

	and (@UserGroupName='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)

	and (@isReportingto = 0 or (E.Employee_ID IN (select * from #EmployeeIds)))

	and (isnull(@Employee_Code_Id,'')='' or E.Employee_Code_Id like cast(@Employee_Code_Id+'%' as nvarchar(50)))
	and (isnull(@Employee_FirstName,'')='' or (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,'') like cast(@Employee_FirstName+'%' as nvarchar(100)))) 
	and ((@Type<>'Both' and M.IsOnDuty != 1) or (@Type='ODEntry' and M.IsOnDuty = 1) )

	and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_InDate between @StartDate and @EndDate))
	and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_OutDate between @StartDate and @EndDate))
	and M.IsImported =Case when @IsImported=3 then @IsImported else '' End
	Order by M.ManualTimeentry_id desc
	Execute (@SqlQuery)
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectforcheckLP]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectforcheckLP]
@EmpID INT
as
Begin
select LeavePolicy_Id from ta_tbl_emp_Leavepolicy where EmployeeId=@EmpID
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectFTPConfiguration]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 17-Aug-2011
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectFTPConfiguration] 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    select * from TA_Tbl_FTPConfiguration
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradeLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name 	:	Proc_TA_SelectGradeLevel 174
Created by	:	Prabakaran..P
Created  date	: 	26/Aug/08
Modified by	:	
Modified on	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectGradeLevel]
(
    	@EmpAutoId varchar(20)
)
AS      
BEGIN  
select Grade_Level from ta_tbl_grade G
Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
where eDesig.EffectiveDate =(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGrades]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- ALTER  date: 18  July 07
-- Description:	Select All Grades
-- Modified By: Manikandan.R
-- Modified Date: 11-june-2012
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectGrades] 
	@Type CHAR,
	@GradeID INT,
	@userGroupName nvarchar(25)
AS	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempGrade(Grade_ID int,Grade_Name nvarchar(100),Grade_Level int,Emp_ID int,Time_Stamp datetime,Isdeleted nvarchar(10),flag int)
	IF (@Type='A')
		IF(@userGroupName='SuperAdmin')
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then 'True' else 'False' end IsDeleted ,0  FROM TA_Tbl_Grade  order by Grade_Level
			END
		ELSE
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then 'True' else 'False' end IsDeleted ,0 FROM TA_Tbl_Grade where Isdeleted=0 order by Grade_Level
			END
	ELSE IF (@Type='I')
		IF(@userGroupName='SuperAdmin')
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then 'True' else 'False' end IsDeleted ,0 FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID order by Grade_Level
			END
		ELSE	
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then 'True' else 'False' end IsDeleted ,0 FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID order by Grade_Level
			END
	Update #TempGrade set flag=1 from #TempGrade TG inner join ta_tbl_Title T on TG.Grade_ID=T.GradeID --where T.Isdeleted=0
	Select * from #TempGrade 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradesStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Prabakaran.P
-- ALTER  date: 12-Oct-09
-- Description:	Select All Grades
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectGradesStandard] 
-- Add the parameters for the stored procedure here
@Type CHAR,
@GradeID INT,
@userGroupName nvarchar(25)
AS	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF (@Type='A')
	IF(@userGroupName='SuperAdmin')
		BEGIN
			SELECT * FROM TA_Tbl_Grade where Grade_Name='StandardGradeDefault' and Grade_Level=1 order by Grade_Level
		END
	ELSE
		BEGIN
			SELECT * FROM TA_Tbl_Grade where Grade_Name='StandardGradeDefault' and Isdeleted=0 order by Grade_Level
		END
ELSE IF (@Type='I')
	IF(@userGroupName='SuperAdmin')
		BEGIN
			SELECT * FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID and Grade_Name='StandardGradeDefault' order by Grade_Level
		END
	ELSE	
		BEGIN
			SELECT * FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID and Grade_Name='StandardGradeDefault' order by Grade_Level
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*Modified by	:	P.Prabakaran
Modified on	:	7-Feb-08*/
--Proc_TA_SelectHoliday 'P',219,'superadmin',0,1,0,0
CREATE   PROCEDURE [dbo].[Proc_TA_SelectHoliday]
(
	@Type char(1),
	@HolidayId int,
	@UserGroupName nvarchar(50),
	@LevelId int,
	@YearsettingsId int,
	@ParentId int,
	@EmployeeId int 
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @dateFormat as int
	declare @EmployeeLevelId int
	Declare @LevelId1 int
	select @EmployeeLevelId=LevelId from ta_tbl_employeelevel where EmployeeId=@EmployeeId
	create table #LevelRights(LevelId int)	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	select @dateFormat =dateformat from dbo.Func_TA_GetDateTimeFormat()
	if(@Type='A')
	BEGIN
		if(@UserGroupName='SuperAdmin')
			begin 
				select  Holiday_Id,Htype=	case Holiday_Type	When 'Y' Then 'Restricted Holiday' 
															When 'G' then 'Global Holiday' 
											End,
						case when cast(@dateFormat as varchar(100))=106 then			
									REPLACE(CONVERT(VARCHAR, Holiday_FromDate,106),' ','-')+' '  + 'To' + ' ' + REPLACE(CONVERT(VARCHAR, Holiday_ToDate,106),' ','-')
								else convert(varchar, Holiday_FromDate,@dateFormat) +' '  + 'To' + ' ' + convert(varchar, Holiday_ToDate,@dateFormat) end 'HolidayDate' ,
						Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,LevelId  
				FROM TA_Tbl_Holiday inner join Ta_tbl_Yearsetting
				on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id WHERE  Ta_tbl_Yearsetting.Isactive=1
			end
		else
			begin 
				select  Holiday_Id,Htype=case Holiday_Type	When 'Y' Then 'Restricted Holiday'
															When 'G' then 'Global Holiday' End,
				case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, Holiday_FromDate,106),' ','-')+' '  + 'To' + ' ' + REPLACE(CONVERT(VARCHAR, Holiday_ToDate,106),' ','-')else 																
				convert(varchar, Holiday_FromDate,@dateFormat) +' '  + 'To' + ' ' + convert(varchar, Holiday_ToDate,@dateFormat) end as  HolidayDate ,Holiday_Description,
				case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,
				LevelId  FROM TA_Tbl_Holiday
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id WHERE TA_Tbl_Holiday.Isdeleted=0 and 
				Ta_tbl_Yearsetting.Isactive=1
			end
	END
	SET @dateFormat = 101
	if(@Type='P')
	BEGIN
		select hct.Holiday_Id,Holiday_Type,
		convert(varchar, Holiday_FromDate,101 ) as  Holiday_FromDate,convert(varchar, Holiday_ToDate,101) as  Holiday_ToDate,
		Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,
		convert(varchar, Holiday_FromDate,101) as Holiday_FromDate,convert(varchar, Holiday_ToDate,101) as Holiday_ToDate,hct.LevelId,isnull(ta_tbl_levelDetails.name,'All')as LevelName FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id 
		left join ta_tbl_levelDetails on TA_Tbl_Holiday.LevelId=ta_tbl_levelDetails.Id
		WHERE TA_Tbl_Holiday.Holiday_Id=@HolidayId  and Ta_tbl_Yearsetting.Isactive=1
	END
	if(@Type='Y' and  @HolidayId=-1)
	BEGIN
		select distinct Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,TA_Tbl_Holiday  .LevelId  FROM TA_Tbl_Holiday  
		inner join TA_Tbl_EmployeeLevel EL on EL.levelId=(TA_Tbl_Holiday.LevelId) or (TA_Tbl_Holiday.LevelId=0)
		inner join #LevelRights on #LevelRights.LevelId = EL.LevelId
		WHERE Isdeleted=0 and Holiday_Type='Y' and TA_Tbl_Holiday.yearsettings_Id=@YearsettingsId
		and EL.levelId= @EmployeeLevelId
	END
	if(@Type='Y' and  @HolidayId !=-1)
	BEGIN
		if(@UserGroupName='SuperAdmin')
			begin
				select hct.Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,hct.LevelId  FROM TA_Tbl_Holiday 
				inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id  WHERE Holiday_Type='Y' and TA_Tbl_Holiday.Holiday_Id=@HolidayId and Ta_tbl_Yearsetting.Isactive=1
			end
		else
			begin 
				select hct.Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then 'True' else 'False' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,hct.LevelId  FROM TA_Tbl_Holiday 
				inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id  WHERE Isdeleted=0 and Holiday_Type='Y' and TA_Tbl_Holiday.Holiday_Id=@HolidayId and Ta_tbl_Yearsetting.Isactive=1
			end
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectImportErrorData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-Apr-2017
-- Description:	Get the import master error data.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectImportErrorData]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_ImportMasterError order by recordnumber
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveAnalysisNotes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveAnalysisNotes]
	@fromDate as datetime
AS
BEGIN
SET NOCOUNT ON;
		select *,replace(convert(varchar(20),DateInserted,106),' ','-') as DateIns from TA_Tbl_LeaveAnalysisNotes where
			isdeleted=0 and 
			month(DateInserted) = month(@fromDate) and
			year(DateInserted) = year(@fromDate)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
Procedure Name	:	Proc_TA_SelectLeaveApplicationById 10
Modified by		:	Prabakaran.P
Modified on		:	20-Feb-08
Description		:	Select Leave Application details based on Leave Application Id
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationById]
(
	@LeaveApplication_Id int
)
AS
	declare @strLeaveType as nvarchar(50)
BEGIN
	SET NOCOUNT ON;
	set @strLeaveType=(select Type from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and isdeleted=0)
	if(@strLeaveType='Leave' or @strLeaveType='LOP')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			lt.LeaveType as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id,
			isnull(lt.isWFH,0) as isWFH
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_LeaveType lt   
			on la.LeaveType_Id = lt.LeaveType_Id   
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and lt.Isdeleted=0
		end
	else if(@strLeaveType='Comp Off' or @strLeaveType='ESI')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			'Others' as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id ,
			0 as isWFH
			from  TA_Tbl_LeaveApplication la  
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0
		end
	if(@strLeaveType='Restricted Holiday')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			h.Holiday_Description as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id,
			0 as isWFH
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_Holiday h  
			on la.LeaveType_Id = h.Holiday_Id   
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By: Manikandan.R
-- Modified Date: 28-Feb-2012
-- Reason: Filter Condition is not working 
-- =============================================
--	Proc_TA_SelectLeaveApplicationDetails 148,'1',null,null,'01/01/1900','01/01/1900',null,'IndividualUsers',0
--Proc_TA_SelectLeaveApplicationDetails @EmployeeID=2,@LevelRights='1',@Employee_Code_Id=NULL,@Employee_FirstName=NULL,@LeaveApplicationStartDate='1900-01-01 00:00:00',@LeaveApplicationEndDate='1900-01-01 00:00:00',@EmpSwipeCard=NULL,@UserGroupName='Management',@ParentId=0
CREATE  procedure [dbo].[Proc_TA_SelectLeaveApplicationDetails]
	@EmployeeID int,
	@LevelRights varchar(8000) = null, 
	@Employee_Code_Id nvarchar(50) = null, 
	@Employee_FirstName varchar(50) = null, 
	@LeaveApplicationStartDate datetime = '01/01/1900', 
	@LeaveApplicationEndDate datetime = '01/01/1900' ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentId int
as  
BEGIN
	--insert into TEstingLeave values(@EmployeeID,@LevelRights,@Employee_Code_Id,@Employee_FirstName,@LeaveApplicationStartDate,@LeaveApplicationEndDate,@EmpSwipeCard,@UserGroupName,@ParentId)
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)
	declare @sqlQuery2 as varchar(8000) 
	declare @sqlQuery3 as varchar(8000) 
	declare @sqlQuery4 as varchar(8000) 
	declare @isReportingto as int
	DECLARE @FileNotFound as varchar(200) = 'File Not Found';
	DECLARE @FileFound as varchar(200) = 'Download';
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	Declare @LeaveSuccessiveFromDate datetime
	Declare @LeaveSuccessiveToDate datetime
	Declare @Levelid int
	Declare @RowCount int
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @EmpSwipeCard=SUBSTRING(@EmpSwipeCard,0,len(@EmpSwipeCard)+1)	
	create table #SwipeCardNo(SwipecardNo varchar(25))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
    --select * from #EmployeeIds
	CREATE NONCLUSTERED INDEX [IDX_SwipecardNo] ON [dbo].[#SwipeCardNo]([SwipecardNo] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
	insert into #SwipeCardNo select value from dbo.split(@EmpSwipeCard,',')
	select @RowCount=COUNT(SwipecardNo) from #SwipeCardNo
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	set @Levelid=@ParentId
	WHILE((SELECT Id from TA_tbl_LevelDetails where id=@Levelid) <> '') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@Levelid) <> 1)
				begin	
					set @Levelid = (select parentId from TA_tbl_LevelDetails where id=@Levelid) 
				END
			ELSE
				BEGIN
					BREAK
				END
		END
	set @ParentId=@Levelid
	if((select FromDate from ta_tbl_yearsetting where Isactive=1) is null)
		begin
			set @LeaveSuccessiveFromDate='01/01/1900'
			set @LeaveSuccessiveToDate='01/01/1900'			
		end
	else
		begin
			select @LeaveSuccessiveFromDate = FromDate from ta_tbl_yearsetting where Isactive=1	
			if (@ParentId =0 )
				begin
					select @LeaveSuccessiveToDate=  isnull(dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate),0) 
					from ta_tbl_yearsetting where Isactive=1 
				end
			else
				begin
					select @LeaveSuccessiveToDate= isnull(dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
					where companyId=@ParentId),ToDate),0) from ta_tbl_yearsetting where Isactive=1
				end
		end
	set @sqlQuery = ''      
	set @sqlQuery1 = ''  
	set @sqlQuery2 = ''
	set @sqlQuery3 = ''
	set @sqlQuery4=''
	set @sqlQuery = @sqlQuery + ' select Employee_Code_Id as employeeid,e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') as Employee_FirstName,ld.name,
					la.LeaveApplication_Id,la.Employee_Id,case when '+cast(@dateFormat as varchar(100))+'=106 then
					REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
					else CONVERT(VARCHAR, Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') end  AS Leave_ApplicationDate,
					case when '+cast(@dateFormat as varchar(100))+'=106 then
					REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
					else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
					+ '' To '' + 
					case when '+cast(@dateFormat as varchar(100))+'=106 then
					REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
					else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration, '
	set @sqlQuery = @sqlQuery + ' (lt.LeaveType + '' / '' + la.Type) as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,isnull(lt.isWFH,0) as isWFH,
	LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result '   
	set @sqlQuery = @sqlQuery + ' from TA_Tbl_LeaveApplication la ' 
	set @sqlQuery = @sqlQuery + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery = @sqlQuery + ' inner join  TA_Tbl_LeaveType lt  on la.LeaveType_Id = lt.LeaveType_Id ' 
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId '
	set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=ld.id '
	if(@RowCount >0)
		begin
			set @sqlQuery = @sqlQuery + ' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo '
		end
	set @sqlQuery = @sqlQuery + ' where la.IsDeleted = 0  and e.isdeleted=0 and la.type in (''Leave'',''LOP'') and la.Leave_FromDate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101)'
	set @sqlQuery = @sqlQuery + ' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) '
	If not(@Employee_Code_Id = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and e.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''
		End
	 if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If not(@Employee_FirstName = '')
		Begin
			set @sqlQuery = @sqlQuery + ' and (e.Employee_FirstName +'' '' + isnull(e.Employee_LastName,'''') like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''')'
		End
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin
			set @sqlQuery = @sqlQuery + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery = @sqlQuery + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery1 = @sqlQuery1 + ' union '
	set @sqlQuery1 = @sqlQuery1 + '	select Employee_Code_Id as employeeid,e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') as Employee_FirstName ,ld.name,la.LeaveApplication_Id,la.Employee_Id,
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') end  AS Leave_ApplicationDate,
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
									+ '' To '' + 
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration,h.Holiday_Description as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,0 as isWFH,
									LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
									from TA_Tbl_Holiday h ' 
	set @sqlQuery1 = @sqlQuery1 + ' inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id '
	set @sqlQuery1 = @sqlQuery1 + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id '  
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId '
	set @sqlQuery1 = @sqlQuery1 + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=ld.id '
	if(@RowCount >0)
		begin
			set @sqlQuery1 = @sqlQuery1 + ' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo '
		end
	set @sqlQuery1 = @sqlQuery1 + ' where la.type=''Restricted Holiday'' and la.Isdeleted=0  and e.isdeleted=0'
	set @sqlQuery1 = @sqlQuery1 + ' and la.Leave_Fromdate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101) and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) '
	If not(@Employee_Code_Id = '')
		Begin
			set @sqlQuery1 = @sqlQuery1 + ' and e.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''
		End
	If not(@Employee_FirstName = '')
		Begin
			set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_FirstName +'' '' + isnull(e.Employee_LastName,'''') like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''')'
		End	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin		
			set @sqlQuery1 = @sqlQuery1 + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery1 = @sqlQuery1 + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery2 = @sqlQuery2 + ' union '
	set @sqlQuery2 = @sqlQuery2 + ' select Employee_Code_Id as employeeid,e.Employee_FirstName  + '' '' + isnull(e.Employee_LastName,'''') as Employee_FirstName ,ld.name,la.LeaveApplication_Id,la.Employee_Id,
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') end  AS Leave_ApplicationDate,
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
									+ '' To '' + 
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration,la.Type '
	set @sqlQuery2 = @sqlQuery2 + ' as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,0 as isWFH ,LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result '  
	set @sqlQuery2 = @sqlQuery2 + ' from TA_Tbl_LeaveApplication la '
	set @sqlQuery2 = @sqlQuery2 + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id '
	set @sqlQuery2 = @sqlQuery2 + ' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId '
	set @sqlQuery2 = @sqlQuery2 + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
	set @sqlQuery2 = @sqlQuery2 + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=ld.id '
	if(@RowCount >0)
		begin
			set @sqlQuery2 = @sqlQuery2 + ' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo '
		end
	set @sqlQuery2 = @sqlQuery2 + ' where la.Isdeleted=0  and (la.type=''Comp Off'' or la.type=''ESI'') and  e.isdeleted=0  and la.Leave_FromDate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101)'
	set @sqlQuery2 = @sqlQuery2 + ' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and  EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) '
	If not(@Employee_Code_Id = '')
		Begin
			set @sqlQuery2 = @sqlQuery2 + ' and e.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''
		End
	If not(@Employee_FirstName = '')
		Begin
			set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_FirstName +'' '' + isnull(e.Employee_LastName,'''') like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''')'
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery2 = @sqlQuery2 + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin		
			set @sqlQuery2 = @sqlQuery2 + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery2 = @sqlQuery2 + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery3= @sqlQuery3 + ' Order by LeaveApplication_Id desc '
	exec (@sqlQuery+@sqlQuery1+@sqlQuery2+@sqlQuery3)
	print(@sqlQuery+@sqlQuery1+@sqlQuery2+@sqlQuery3)
	drop table #LevelRights
	drop table #SwipeCardNo
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_SelectLeaveApplicationDetailsByEmpId '2','3','1','4/1/2020','5/18/2020','IndividualUsers',0
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]
(
@Employee_Id int,
@GradeLevel varchar(20),
@LevelRights varchar(8000), 
@LeaveApplicationStartDate datetime = '01/01/1900', 
@LeaveApplicationEndDate datetime = '01/01/1900',
@UserGroupName varchar(250),
@ParentId int
)    
AS    
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	DECLARE @CurrentDate AS NVARCHAR(30)
	Declare @LeaveSuccessiveFromDate datetime
	Declare @LeaveSuccessiveToDate datetime
	if( (select FromDate from ta_tbl_yearsetting where Isactive=1) is null)
		begin
			set @LeaveSuccessiveFromDate='01/01/1900'
			set @LeaveSuccessiveToDate='01/01/1900'				
		end
	else
		begin
			select @LeaveSuccessiveFromDate = FromDate from ta_tbl_yearsetting where Isactive=1
			if (@ParentId =0 )
				begin
					select @LeaveSuccessiveToDate= dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate) 
					from ta_tbl_yearsetting where Isactive=1 
				end
			else
				begin
					if exists(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@ParentId)
					begin
						select @LeaveSuccessiveToDate= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
						where companyId=@ParentId),ToDate) from ta_tbl_yearsetting where Isactive=1
					end
					else
					begin
						select @LeaveSuccessiveToDate= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
						where companyId=-1),ToDate) from ta_tbl_yearsetting where Isactive=1
					end
				end
		end
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)
	declare @sqlQuery2 as varchar(8000)
	declare @sqlQuery4 as varchar(8000)        
	set @sqlQuery = ''      
	set @sqlQuery1 = ''
	set @sqlQuery2 = ''
	set @sqlQuery4 = ''
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	SET @CurrentDate = GetDate()
	DECLARE @FileNotFound as varchar(200) = 'File Not Found';
	DECLARE @FileFound as varchar(200) = 'Download';
	set @sqlQuery = @sqlQuery + ' select '''' as employeeid,'' '' as Employee_firstName,'''' as ''name'',la.LeaveApplication_Id,la.Employee_Id,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') end AS Leave_ApplicationDate,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
									+ '' To '' + 
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration,
									'
	set @sqlQuery = @sqlQuery + ' (lt.LeaveType + '' / '' + la.Type) as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''Pending''		then ''Pen_16x16.png''
			when status=''Forwarded''	then ''Forw_52x52.png''
			when status=''Approved''	then ''Appr_52x52.png'' 
			when status=''Rejected''	then ''Rej_52x52.png'' 
	end as image,
	case	when status=''Pending''		then ''#DD4B39''
			when status=''Forwarded''	then ''#FF7F00''
			when status=''Approved''	then ''#00CC71'' 
			when status=''Rejected''	then ''#00CC74'' 
	end as btnColor,isnull(lt.isWFH,0) as isWFH,
	LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
	from TA_Tbl_LeaveApplication la '
	set @sqlQuery = @sqlQuery + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id '
	set @sqlQuery = @sqlQuery + ' where la.Employee_Id = ''' + cast(@Employee_Id as nvarchar(100))  + ''' and la.IsDeleted = 0 and la.type in (''Leave'',''LOP'') and (la.Leave_FromDate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101))'    
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin
			set @sqlQuery = @sqlQuery + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery = @sqlQuery + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '
	set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '
	set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level >=' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery1 = @sqlQuery1 + ' union '    
	set @sqlQuery1 = @sqlQuery1 + ' select '''' as employeeid,'''' as Employee_firstName,'''' as ''name'',la.LeaveApplication_Id,la.Employee_Id,CONVERT(VARCHAR, la.Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') AS Leave_ApplicationDate,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
									+ '' To '' + 
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration,
	h.Holiday_Description as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''Pending''		then ''Pen_16x16.png''
			when status=''Forwarded''	then ''Forw_52x52.png''
			when status=''Approved''	then ''Appr_52x52.png'' 
			when status=''Rejected''	then ''Rej_52x52.png'' 
	end as image
	,
	case	when status=''Pending''		then ''#DD4B39''
			when status=''Forwarded''	then ''#FF7F00''
			when status=''Approved''	then ''#00CC71'' 
			when status=''Rejected''	then ''#00CC74'' 
	end as btnColor,0 as isWFH ,
	LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
	from TA_Tbl_Holiday h  '  
	set @sqlQuery1 = @sqlQuery1 + ' inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id '
	set @sqlQuery1 = @sqlQuery1 + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId '
	set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	set @sqlQuery1 = @sqlQuery1 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sqlQuery1 = @sqlQuery1 + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery1 = @sqlQuery1 + ' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id '
	set @sqlQuery1 = @sqlQuery1 + ' where la.type=''Restricted Holiday'' and la.Employee_Id=''' + cast(@Employee_Id as nvarchar(100))  + ''' and la.Isdeleted=0 and (la.Leave_FromDate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101)) ' 
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin
			set @sqlQuery1 = @sqlQuery1 + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery1 = @sqlQuery1 + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '
	set @sqlQuery1 = @sqlQuery1 + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <= CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102)  order by EffectiveDate desc) ' 
	set @sqlQuery1 = @sqlQuery1 + ' AND TA_Tbl_Grade.Grade_Level >= ' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery2 = @sqlQuery2 + ' union '
	set @sqlQuery2 = @sqlQuery2 + ' select '''' as employeeid,'''' as Employee_firstName,'''' as ''name'',la.LeaveApplication_Id,la.Employee_Id,
	CONVERT(VARCHAR, la.Leave_ApplicationDate, '+cast(@dateFormat as varchar(100))+') AS Leave_ApplicationDate,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_FromDate, '+cast(@dateFormat as varchar(100))+') end
									+ '' To '' + 
									case when '+cast(@dateFormat as varchar(100))+'=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
									else CONVERT(VARCHAR, Leave_ToDate, '+cast(@dateFormat as varchar(100))+') end  AS Duration,
	la.Type as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''Pending''		then ''Pen_16x16.png''
			when status=''Forwarded''	then ''Forw_52x52.png''
			when status=''Approved''	then ''Appr_52x52.png'' 
			when status=''Rejected''	then ''Rej_52x52.png'' 
	end as image
	,
		case	when status=''Pending''		then ''#f4c9c3''
			when status=''Forwarded''	then ''#ffd8b2''
			when status=''Approved''	then ''#b2efd4'' 
			when status=''Rejected''	then ''#00CC74'' 
	end as btnColor,0 as isWFH
	 ,LA_FU.FileName as Download,case when LA_FU.FileName is null then '''+ cast(@FileNotFound as varchar(100)) +''' else '''+ cast(@FileFound as varchar(100)) +''' end as Result
	from TA_Tbl_LeaveApplication la '     
	set @sqlQuery2 = @sqlQuery2 + ' left outer join TA_Tbl_LeaveApplication_FileUpload LA_FU on la.LeaveApplication_Id = LA_FU.LeaveApplication_Id ' 
	set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId '
	set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId '
	set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	set @sqlQuery2 = @sqlQuery2 + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sqlQuery2 = @sqlQuery2 + ' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id '
	set @sqlQuery2 = @sqlQuery2 + ' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id '
	set @sqlQuery2 = @sqlQuery2 + ' where la.Employee_Id=''' + cast(@Employee_Id as nvarchar(100))  + ''' and (la.type=''Comp Off'' or la.type=''ESI'') and  la.Isdeleted=0 and (la.Leave_FromDate >= convert(datetime,''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + ''',101) and la.Leave_ToDate <= convert(datetime, ''' + cast(@LeaveSuccessiveToDate as varchar(20)) + ''',101))'
	If not(@LeaveApplicationStartDate = '01/01/1900' and @LeaveApplicationEndDate = '01/01/1900')
		Begin
			set @sqlQuery2 = @sqlQuery2 + ' and (la.Leave_FromDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101)'
			set @sqlQuery2 = @sqlQuery2 + ' or la.Leave_ToDate between convert(datetime,''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + ''',101))'
		End
	set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '
	set @sqlQuery2 = @sqlQuery2 + ' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,''' + cast(@CurrentDate as nvarchar(50)) + ''', 102) order by EffectiveDate desc) '
	set @sqlQuery2 = @sqlQuery2 + ' AND TA_Tbl_Grade.Grade_Level >=' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery4= @sqlQuery4 + ' Order by LeaveApplication_Id desc '
	exec (@sqlQuery+@sqlQuery1+@sqlQuery2+@sqlQuery4)
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveDetails_YearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectLeaveDetails_YearClosure] 
(  
@EmpID INT,  
@YearID INT  
)  
AS  
select LPD.* from TA_Tbl_LeavePolicydetails LPD  
INNER JOIN TA_Tbl_Emp_LeavePolicy ELP on ELP.LeavePolicy_Id=LPD.Policy_Id  
INNER JOIN TA_Tbl_LeavePolicy LP ON LPD.Policy_Id=LP.Policy_Id  
where ELP.EmployeeId=@EmpID   
and ELP.YearSettingId=@YearID  and ELP.Isdeleted=0 and LP.IsDeleted=0
and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmpID 
order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectLeaveDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	To check the employee applied the leave or not
--[Proc_Ta_SelectLeaveDetailsForService] 105,'2015-10-12'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectLeaveDetailsForService]
	@INEMPLOYEE_CODE_ID VARCHAR(50),
	@DTMDATE DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LA.Employee_Id,LA.LEAVETYPE_ID,LA.TYPE,LAE.LEAVE_FROMDATE,LAE.LEAVE_TODATE,LAE.LEAVE_SESSIONFROM,LAE.LEAVE_SESSIONTO,LA.Status FROM TA_TBL_LEAVEAPPLICATION LA
	inner join TA_Tbl_LeaveApplicationExists LAE on la.LeaveApplication_Id=LAE.LeaveApplicationId
	INNER JOIN TA_TBL_EMPLOYEE EMP ON LA.EMPLOYEE_ID = EMP.EMPLOYEE_ID 
	WHERE EMP.SWIPECARDNO =@INEMPLOYEE_CODE_ID AND LA.STATUS = 'APPROVED' AND LA.ISDELETED = 0 and lae.IsDeleted=0 and EMP.Isdeleted=0
	AND LAE.LEAVE_FROMDATE = @DTMDATE AND LAE.LEAVE_TODATE =  @DTMDATE
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*
    -- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: 29 June 2007  
-- Description: Leave policy - select  
-- Modified By : Kumuthini.L
-- Modified On : 06-Feb-2008
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Modified by	:	Manikandan.R
Modified on	:	15-Oct-11
Description	:	Year closure changes
[Proc_TA_SelectLeavePolicy] 'A',0,'Superadmin'
-- =============================================  
*/

CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicy]   
 @Type CHAR(1)='',  
 @Policy_Id INT=0,  
 @UserGroupName nVarchar(250)
AS  
BEGIN  
	SET NOCOUNT ON;  
	IF (@Type='A')
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT LP.Policy_Id, LP.PolicyName, LP.Permission_MaxHrs_Month, LP.Permission_MaxInstances_Month, LP.Permission_MaxHrs_Instance, LP.PermissionBeforeLeave, LP.PermissionAfterLeave, LP.OtHourWise, LP.OtDayWise, LP.OtMinHrs, LP.IsDeleted, LP.Time_Stamp, LP.Emp_Id, LP.EmployeeCategory, LP.EmployeeType, LP.Gender, LP.Religion, LP.CompOffValidDays, LP.FullDayOTMinHrs, LP.companyID,Permission_MinHrs_Instance=ISNULL(LP.Permission_MinHrs_Instance,'00:30'),(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'') into #tempLeavePolicy 
					FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePolicy		
				END
			ELSE
				BEGIN
					SELECT LP.Policy_Id, LP.PolicyName, LP.Permission_MaxHrs_Month, LP.Permission_MaxInstances_Month, LP.Permission_MaxHrs_Instance, LP.PermissionBeforeLeave, LP.PermissionAfterLeave, LP.OtHourWise, LP.OtDayWise, LP.OtMinHrs, LP.IsDeleted, LP.Time_Stamp, LP.Emp_Id, LP.EmployeeCategory, LP.EmployeeType, LP.Gender, LP.Religion, LP.CompOffValidDays, LP.FullDayOTMinHrs, LP.companyID, Permission_MinHrs_Instance=ISNULL(LP.Permission_MinHrs_Instance,'00:30'),(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'') into #tempLeavePol FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					WHERE LP.IsDeleted=0 
					Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol	
				END  
		END
	ELSE IF (@Type='P')  
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT LP.Policy_Id, LP.PolicyName, LP.Permission_MaxHrs_Month, LP.Permission_MaxInstances_Month, LP.Permission_MaxHrs_Instance, LP.PermissionBeforeLeave, LP.PermissionAfterLeave, LP.OtHourWise, LP.OtDayWise, LP.OtMinHrs, LP.IsDeleted, LP.Time_Stamp, LP.Emp_Id, LP.EmployeeCategory, LP.EmployeeType, LP.Gender, LP.Religion, LP.CompOffValidDays, LP.FullDayOTMinHrs, LP.companyID, Permission_MinHrs_Instance=ISNULL(LP.Permission_MinHrs_Instance,'00:30'), getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'') into #tempLeavePol2  FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					WHERE Policy_Id=@Policy_Id
					Update #tempLeavePol2 set flag=0 from #tempLeavePol2 TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol2	
				END
			ELSE
				BEGIN
					SELECT LP.Policy_Id, LP.PolicyName, LP.Permission_MaxHrs_Month, LP.Permission_MaxInstances_Month, LP.Permission_MaxHrs_Instance, LP.PermissionBeforeLeave, LP.PermissionAfterLeave, LP.OtHourWise, LP.OtDayWise, LP.OtMinHrs, LP.IsDeleted, LP.Time_Stamp, LP.Emp_Id, LP.EmployeeCategory, LP.EmployeeType, LP.Gender, LP.Religion, LP.CompOffValidDays, LP.FullDayOTMinHrs, LP.companyID, Permission_MinHrs_Instance=ISNULL(LP.Permission_MinHrs_Instance,'00:30'),getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'') into #tempLeavePol3  FROM TA_Tbl_LeavePolicy  LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id	
					WHERE Policy_Id=@Policy_Id AND LP.IsDeleted=0
					Update #tempLeavePol3 set flag=0 from #tempLeavePol3 TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol3	 
				END
		END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun vinoth
-- Create date: 29 June 2007
-- Description:	Leave policy - select
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetails] 
	-- Add the parameters for the stored procedure here
	@Policy_ID Varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	BEGIN
		SELECT L.LeaveType,L.LeaveDescription,LP.*,isnull(L.isWFH,0) as isWFH 
		,IsProrataRequired=isnull(IsProrataRequired,1),IsDocProofRequired=isnull(IsDocProofRequired,1)
		FROM TA_Tbl_LeavePolicyDetails LP
		inner join TA_Tbl_LeaveType L ON LP.LeaveType_Id =L.LeaveType_Id
		WHERE LP.Policy_Id=@Policy_ID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter] 0,2,'Both',0  select * from ta_tbl_leavetype
CREATE Proc [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]
(    
    @EmployeeCategory varchar(50)=null,
    @EmployeeType varchar(50)=null,
    @Gender varchar(10)=null,
    @Religion varchar(20)=null)
AS      
 DECLARE @SQL NVARCHAR(MAX)
			SET @SQL='SELECT Policy_Id, PolicyName FROM TA_Tbl_LeavePolicy where isDeleted=0 '
		IF @EmployeeCategory is not null
			begin
				if @EmployeeCategory=0
					begin
						set @SQL= @SQL+ ' and (EmployeeCategory in (select EmployeeCategory from TA_Tbl_LeavePolicy) or EmployeeCategory=0)'
					end
				else
					begin
						set @SQL= @SQL+ ' and (EmployeeCategory=' +CONVERT(varchar(10),@EmployeeCategory) +' or EmployeeCategory=0)' 
					end
			end
		IF  @EmployeeType is not null
			if @EmployeeType=0
				begin
					set @SQL= @SQL+ ' and (EmployeeType in (select EmployeeType from TA_Tbl_LeavePolicy) or EmployeeType=0)'
				end
			else			
				begin
					set @SQL= @SQL+ ' and (EmployeeType=' +CONVERT(varchar(10),@EmployeeType)+' or EmployeeType=0)' 
				end
		IF  @Gender is not null
			begin
				if @Gender='Both'
					begin
						set @SQL= @SQL + ' and (Gender=''Female'' or Gender=''Male'' or Gender=''Both'')'
					end
				else
					begin
						set @SQL= @SQL + ' and (Gender='''+CONVERT(varchar(10),@gender)+''' or Gender=''Both'')'
					end
			end
		IF  @Religion is not null-- and @Religion<>0
			IF @Religion=0
				begin
					set @SQL= @SQL + ' and (Religion in(select Religion from TA_Tbl_LeavePolicy) or Religion=0)'
				end
			else
				begin
					set @SQL= @SQL + ' and (Religion='+CONVERT(varchar(10),@Religion)+' or Religion=0)'
				end			
			set @SQL= @SQL+ ' order by Policy_Id'
			execute(@sql)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectLeavePolicyDetailsLeaveApplication 67,1,'07/04/2019','07/04/2019'
Description		:	Select Leave Policy Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeavePolicyDetails,Ta_Tbl_Emp_LeavePolicy
Created By		:	Prabakaran
Created On		:	11-Aug-07
Modified By		:
Modified On		:
*/
CREATE     PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication] 
@Employee_Id int,
@LeaveType_Id int,
@FromDate datetime,
@ToDate datetime
AS
BEGIN
	Declare @DateofJoining datetime
	Declare @currentMonth datetime
	Declare @FinancilaYearStartDate datetime
	Declare @difference_fy int
	Declare @difference_DJ int
	Declare @flag int
	IF(@FromDate>GETDATE() or @ToDate>GETDATE())
	BEGIN
		DECLARE @diff INT
		IF(@FromDate>GETDATE() and @ToDate>GETDATE())
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@ToDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
		ELSE IF(@FromDate>GETDATE())
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@FromDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
		ELSE
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@ToDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
	END
	ELSE
	BEGIN	
		set @currentMonth=GETDATE()
	END
	IF(@currentMonth is null)
	BEGIN
		set @currentMonth=GETDATE()
	END
	--Newly Added This coding on 09-Jan-20120	
	Declare @CarryOverValue decimal(18,1)
	Declare @YearSettings_Id int
	select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate
	select @CarryOverValue=Carry_PrevYear from TA_Tbl_YearClosure where Year_SettingID=@YearSettings_Id	 and LeaveTypeID=@LeaveType_Id
	and Employee_Id=@Employee_Id	
	select @CarryOverValue=isnull(@CarryOverValue,0.0)+isnull(PreviousYearBalance,0.0) from ta_tbl_emp_LeaveTypedetails where EmployeeId=@Employee_Id and YearSettingsId=@YearSettings_Id and LeaveTypeID=@LeaveType_Id
	---- End of @CarryOverValue
	
	--if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
	--	BEGIN
	--		select @DateofJoining=
	--		CASE	WHEN DATEPART(d,DateOfJoining)>15 then
	--					CASE	WHEN DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))>15 then dateadd(d,0,DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))))
	--							ELSE DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))
	--					END 
	--				ELSE DATEADD(d,0,DATEADD(d,0,DateOfJoining))
	--		END
	--		from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
	--		select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
	--		set @difference_fy=DATEDIFF(month,@FinancilaYearStartDate,@currentMonth)+1
	--		set @difference_DJ=DATEDIFF(month,@DateofJoining,@currentMonth)+1
	--		select @flag=MIN(b.a) from
	--		(
	--			select	(@difference_DJ) as a union all
	--			select  (@difference_fy) as a
	--		)as b
	Declare @multiply int
	if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
		BEGIN
			select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
			select @multiply=
			CASE	WHEN DATEPART(d,DateOfJoining)>15 then
						case	when DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)),getdate())+1
						end 
					else
						case	when DateOfJoining<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DateOfJoining,getdate())+1
						end 
			END
			from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
			Select *,Eligible=(@multiply*lpd.MaxDays_Month)+@CarryOverValue from Ta_TBl_LeavePolicyDetails lpd  
			inner join Ta_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1
			and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@ToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
			and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		END
	ELSE
		BEGIN
			--select @DateofJoining=
			--CASE	WHEN DATEPART(d,DateOfJoining)>15 then 
			--			CASE	WHEN DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))>15 then dateadd(d,0,DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))))
			--					ELSE DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))
			--			END 
			--		ELSE DATEADD(d,0,DATEADD(d,0,DateOfJoining))
			--END
			--from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
			--select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate
			--set @difference_fy=DATEDIFF(month,@FinancilaYearStartDate,@currentMonth)+1
			--set @difference_DJ=DATEDIFF(month,@DateofJoining,@currentMonth)+1
			--select @flag=MIN(b.a) from
			--(
			--	select	(@difference_DJ) as a union all
			--	select  (@difference_fy) as a
			--)as b	
			select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
			select @multiply=
			CASE	WHEN DATEPART(d,DateOfJoining)>15 then
						case	when DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)),getdate())+1
						end 
					else
						case	when DateOfJoining<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DateOfJoining,getdate())+1
						end 
			END 
			from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0	
			Select *,Eligible=(@multiply*lpd.MaxDays_Month)+@CarryOverValue from Ta_TBl_LeavePolicyDetails lpd
			inner join Ta_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1
			and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <27-10-2011>
-- Description:	<Loading the Leave policy for selected Religion,Employee Category,Employee type and gender>
-- Proc_TA_SelectLeavePolicyforEmployeeFilters 1,1,'Male',43
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters] 
	-- Add the parameters for the stored procedure here
	--@EmployeeCategory  int,
	--@EmployeeType int,
	@loginEmployeeId varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @Query nvarchar(4000)
    set @Query=''
    set @Query= @Query + 'select * from TA_Tbl_TempGroupPolicyAllocation where 1=1  and LoginEmployeeId='+@loginEmployeeId
	exec(@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveType] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT LeaveType_Id, LeaveType From TA_Tbl_LeaveType Where IsDeleted ='0'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesForEncashment]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_SelectLeaveTypesForEncashment
Description		:	GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails
Tables Included	:	TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType, ta_tbl_leavePolicyDetails
					ta_tbl_emp_leavepolicy
Created By		:	Prabakaran
Created On		:	08-Aug-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_SelectLeaveTypesForEncashment]
@EmployeeId bigint
as
select distinct lp.LeaveType_Id,lt.LeaveType 
from TA_Tbl_emp_leavePolicyDetails lp
inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id
inner join ta_tbl_leavePolicyDetails lpd   on lpd.Policy_Id=lp.Policy_ID and lpd.LeaveType_Id=lp.LeaveType_id
inner join  ta_tbl_emp_leavepolicy el on el.Emp_LeavePolicyId=lp.Emp_LeavePolicyId
Where lp.empId=@EmployeeId
and lp.IsDeleted=0 and lpd.Encashment=1 
--and (CONVERT(NVARCHAR(20),getdate(),101) between el.FromDate and el.Todate)
and el.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name 		: Proc_TA_SelectLeaveTypesOfEmployees  2,'04/27/2012','04/27/2012'
Description		: GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails  
Tables Included 	: TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType,ta_tbl_emp_LeavePolicy   
Created By		: Prabakaran  
Created On		: 08-Aug-07  
Modified By		:  
Modified On		:  
*/  
CREATE     procedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]  
(
@EmployeeId bigint,
@LeaveFromDate datetime,
@LeaveToDate datetime  
) 
as  
BEGIN 
    if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
    BEGIn
		declare @LeaveFromDate_PolicyId int
		if exists (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
		inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
		where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
		and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		BEGIN
		    set @LeaveFromDate_PolicyId = (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
			and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		END
		ELSE
		BEGIN
		    set @LeaveFromDate_PolicyId = 0
		END
		declare @LeaveToDate_PolicyId int
		if exists(select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
		inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
		where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
		and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		BEGIN
		    set @LeaveToDate_PolicyId =(select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
			and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		END
		ELSE
		BEGIN
		    set @LeaveToDate_PolicyId = 0
		END
		if((@LeaveFromDate_PolicyId = @LeaveToDate_PolicyId) or (@LeaveFromDate_PolicyId =0) or (@LeaveToDate_PolicyId=0))
		BEGIN
			select distinct lp.LeaveType_Id,lt.LeaveType,LeaveDescription=substring(lt.LeaveDescription,1,15)+' ('+lt.LeaveType+')' from TA_Tbl_emp_leavePolicyDetails lp  
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id  
			inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId
			Where lp.empId=@EmployeeId and lp.IsDeleted=0 
			--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
						inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
						where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
						and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
						order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			order by lt.LeaveType
		END
		ELSE
		BEGIN
		 select 0
		END
	END
	ELSE
	BEGIN
			Declare @SuccessiveyearId int
			set @SuccessiveyearId = (select top 1 yearsettings_Id from ta_tbl_yearSetting where yearsettings_id> (select yearsettings_id from ta_tbl_yearSetting where isactive=1) order by yearsettings_id)
			Declare @SqlQuery varchar(8000)
			set @SqlQuery=''
			set @SqlQuery = @SqlQuery + ' select distinct lp.LeaveType_Id,lt.LeaveType,LeaveDescription=substring(lt.LeaveDescription,1,15)+'' rfec(''+lt.LeaveType+'')'' from TA_Tbl_emp_leavePolicyDetails lp ' 
			set @SqlQuery = @SqlQuery + ' inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id '  
			set @SqlQuery = @SqlQuery + ' inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId '
			set @SqlQuery = @SqlQuery + ' Where lp.empId=' + cast(@EmployeeId as varchar(25)) + ' and lp.IsDeleted=0 '
			set @SqlQuery = @SqlQuery + ' and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy '
			--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
			--set @SqlQuery = @SqlQuery + ' and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy '
			set @SqlQuery = @SqlQuery + ' inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid '
			set @SqlQuery = @SqlQuery + ' where TA_Tbl_Emp_LeavePolicy.EmployeeId= ' + cast(@EmployeeId as varchar(25)) + ' and '
			if((select count(*) from ta_tbl_emp_LeavePolicy where Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId)=0)
				begin
					set @SqlQuery = @SqlQuery + ' TA_Tbl_YearSetting.IsActive=1 '
				end
			else if((select count(*) from ta_tbl_emp_LeavePolicy where Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId) >=1)
				begin
				set @SqlQuery = @SqlQuery + '(''' + cast(@LeaveFromDate as varchar(25)) + ''' between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and ( ''' + cast(@LeaveToDate as varchar(25)) + ''' between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) ' 
				end
			set @SqlQuery = @SqlQuery + ' order by TA_Tbl_Emp_LeavePolicy.ToDate desc) '
			--case (select count(*) from ta_tbl_emp_LeavePolicy where
			--			Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId) when 0 then  (TA_Tbl_YearSetting.IsActive=1) else  
			--			((@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)) end
			--			order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			--order by lt.LeaveType '
			exec(@SqlQuery)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name 		: Proc_TA_SelectLeaveTypesOfEmployees  
Description		: GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails  
Tables Included 	: TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType,ta_tbl_emp_LeavePolicy   
Created By		: Prabakaran  
Created On		: 08-Aug-07  
Modified By		:  
Modified On		: 
Proc_TA_SelectLeaveTypesOfEmployees 28 
*/  
Create     procedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]  
@EmployeeId bigint  
as  
select distinct lp.LeaveType_Id,lt.LeaveType from TA_Tbl_emp_leavePolicyDetails lp  
inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id  
inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId
Where lp.empId=@EmployeeId and lp.IsDeleted=0 
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
where 
--TA_Tbl_YearSetting.IsActive=1 and 
TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
order by lt.LeaveType
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLevelRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Senthil
-- Create date: 23-Aug-08
-- Description:	Get the levels by groups
-- Proc_TA_SelectLevelRights
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLevelRights]
	@GroupID as int
AS
BEGIN	
	Select LevelId from TA_Tbl_LevelRights where groupId= @Groupid
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure '1,2,3,47,113,133,134,135,137,138,140,150','1/1/2009','05/08/2009',''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
as  
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000)  
declare @Result as varchar(1000) 
  set @sqlQuery=''  
  set @sqlQuery = 'select Count(*) as Count from TA_TBL_LeaveApplication '  
  set @sqlQuery = @sqlQuery + ' Where IsDeleted=0 and Status IN (''Forwarded'',''Pending'')' 
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
  set @sqlQuery1=''  
  set @sqlQuery1 = 'select Count(*) as Count from TA_TBL_ManualTimeEntry '  
  set @sqlQuery1 = @sqlQuery1 + 'where IsDeleted=0 and ManualTimeEntry_Status IN (''Forwarded'',''Pending'') ' 
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''  
  set @sqlQuery2 = 'select Count(*) as Count from TA_TBL_ProcessedData '  
  set @sqlQuery2 = @sqlQuery2 + ' where OvertimeStatus IN (''Forwarded'',''Pending'')' 
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
--  set @sqlQuery3=''  
--  set @sqlQuery3 = 'select Count(*) as Count from TA_TBL_Employee E '  
--  set @sqlQuery3 = @sqlQuery3 + ' inner join TA_TBL_Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId '  
--  set @sqlQuery3 = @sqlQuery3 + ' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId '  
--  set @sqlQuery3 = @sqlQuery3 + ' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '  
--  set @sqlQuery3 = @sqlQuery3 + ' AND E.Isdeleted=0'  
--  set @sqlQuery3 = @sqlQuery3 + ' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) order by EffectiveDate desc) '  
--  set @sqlQuery3 = @sqlQuery3 + ' and crd.Clk_Date between CONVERT(DATETIME, ''' + cast(@dtFromDate as nvarchar(11)) + ''', 102) and CONVERT(DATETIME, ''' + cast(@dtToDate as nvarchar(11)) + ''', 102) '
--  set @sqlQuery3 = @sqlQuery3 + ' and (EL.LevelId IN (' + @vcLevelId  + '))'  
--  set @sqlQuery3 = @sqlQuery3 + ' and (crd.Clk_Flag =0 or crd.Clk_Process =0)' 
--
--if not(@EmployeeCodeIds='')
--begin
-- set @sqlQuery3 = @sqlQuery3 + ' and (e.Employee_Code_Id IN (' + @EmployeeCodeIds  + '))'  
--end
--
--insert into  #tblProcessRaw exec(@sqlQuery3)
--set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''  
set @sqlQuery4 = 'select Count(*) as Count from TA_TBL_Permission '  
set @sqlQuery4 = @sqlQuery4 + ' where IsDeleted=0 and Permission_Status IN (''Forwarded'',''Pending'')'  
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result='Pending or Forwarded Records for '
--if(@gintRawCount>0)
--	begin
--	
--	set @Result=@Result + ' Device '
--	
--	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + ','
	end
set @Result=@Result + 'Over Time '
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + ','
			end
		set @Result=@Result + ' Leave '
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + ','
					end
		set @Result=@Result + ' Permission '
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + ','
							end
		set @Result=@Result + ' Manual Entry '
	end
set @Result=@Result + 'Exists,Close them before updating new license'
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''
end
select @Result as Result
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure '1,2,3,47,113,133,134,135,137,138,140,150','1/1/2009','05/08/2009',''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Manjula          
-- Date    : 28-Jan-2014          
-- Update History :   [Date Updated By (Initials) Reason]   
--	Proc_TA_SelectLICPendingForwardedRecords_YearClosure 1,1       
/****************************************************************************************/ 
@OrgLevelId int=0,
@Year_SettingID int=0       
as  
	create table #tblProcessLeave(intCount bigint)
	declare @gintLeaveCount bigint
	declare @sqlQuery as varchar(8000)
	declare @Result as varchar(1000) 
	set @sqlQuery=''  
	set @sqlQuery = 'select isnull( Count(*),0) as Count from TA_TBL_LeaveApplication '  
	set @sqlQuery = @sqlQuery + ' Where IsDeleted=0 and Status IN (''Forwarded'',''Pending'') and companyId='+CAST( @OrgLevelId as varchar)+' and YearSettings_Id='+CAST( @Year_SettingID as varchar)+'' 
	insert into  #tblProcessLeave exec(@sqlQuery)
	set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
	set @Result='Pending or Forwarded Records for '
	if(@gintLeaveCount>0)
	begin	
		set @Result=@Result + ' Leave '
	end
	set @Result=@Result + 'Exists,Close them before Save the Year Closure'
	if( @gintLeaveCount>0)
	begin
	set @Result=@Result
	end
	else
	begin
	set @Result=''
	end
	select @Result as Result
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoanEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_TA_SelectLoanEntry]
( 
	@loanId int
)
As 
Begin
	Select E.Employee_Code_Id,E.Employee_FirstName,L.Loan_Amount,L.Total_DeductionMonth,L.Deduction_StartMonth,L.Monthly_DeductAmount,L.Loan_BalanceAmount,L.Loan_Description From TA_Tbl_LoanEntryDetails L inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id where L.Loan_ID=@loanId 
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectLocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_SelectLocation 
Description : select the Locatiom  
Tables Included : TA_Tbl_LevelDetails,TA_Tbl_Level  
Created By : velumani  
Created On : 29-Jun - 2019
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_selectLocation]  
AS   
BEGIN  
	select id as LocationId, Options, LocationName, Radius, Description, Address, City, State, Country, latitude, longitude, CreatedBy, CreatedDate, ModifiedBy, ModifiedDate from ta_tbl_landmarks
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogDownloaded]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By		: Manjula.P
Created Date	: 21-May-2013
Descriptions	: For creating log downloaded details as per the given requirements by sathish sir 
*/
CREATE proc [dbo].[Proc_TA_SelectLogDownloaded]
as
begin
select LoggedEmployeeId,CONVERT(varchar(20), LoggedDate,100) as LoggedDate from ta_tbl_LogDownloaded order by LoggedId desc
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLoginDetails] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
SELECT ConcurrentUserId, UserId, IpAddress, LoginTime, Status 
FROM TA_Tbl_ConcurrentUser where status = 1 ORDER BY LoginTime DESC
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginLock]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectLoginLock]
(
	@UserName VARCHAR(1000)
)
AS
BEGIN
	SELECT * FROM TA_Tbl_LockLogin WHERE UserName=@UserName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,26-November-07>
-- Description:	<Description,,Select CustomerLogo from database>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLogo]
AS
BEGIN
	SELECT Cus_Image FROM Ta_Tbl_Branding
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLookupData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLookupData]
	@Category CHAR,
	@ID INT,
	@userGroupName nvarchar(25)
AS
BEGIN
	SET NOCOUNT ON;
IF (@Category='C')
	IF(@userGroupName='SuperAdmin')
		BEGIN
  			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1  
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.Isdeleted=0
		END	
ELSE IF (@Category='D')
	IF(@userGroupName='SuperAdmin')
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.ID=@ID
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.ID=@ID AND L.Isdeleted=0
		END
ELSE IF (@Category='S')
	IF(@userGroupName='SuperAdmin')
		BEGIN
			SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS country,0 as flag into #tempState FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2
			Update #tempState set flag=1 from #tempState TC inner join ta_tbl_Employee E on TC.ID=E.State --where E.Isdeleted =0
			Update #tempState set flag=1 from #tempState TC inner join ta_tbl_lookup L on TC.ID=L.Parent 
			Select * from #tempState  
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS country,0 as flag into #tempState1 FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2 AND L.Isdeleted=0
			Update #tempState1 set flag=1 from #tempState1 TC inner join ta_tbl_Employee E on TC.ID=E.State --where E.Isdeleted =0			
			Update #tempState1 set flag=1 from #tempState1 TC inner join ta_tbl_lookup L on TC.ID=L.Parent 
			Select * from #tempState1 
		END	
ELSE IF (@Category='T')
	IF(@userGroupName='SuperAdmin')
		SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		WHERE L.Type=2 AND L.ID=@ID 
	ELSE
		SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		WHERE L.Type=2 AND L.ID=@ID AND L.Isdeleted=0
ELSE IF (@Category='N')
	IF(@userGroupName='SuperAdmin')
		begin
			SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country,0 as flag 
			into #TempCity FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3		
			Update #TempCity set flag=1 from #TempCity TC inner join ta_tbl_Employee E on TC.ID=E.Native_Place --where E.Isdeleted =0
			Select * from #TempCity 
		End
	ELSE
		Begin		
			SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country,0 as flag 
			into #TempCity1 FROM TA_Tbl_Lookup L INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3 AND L.Isdeleted=0
			Update #TempCity1 set flag=1 from #TempCity1 TC inner join ta_tbl_Employee E on TC.ID=E.Native_Place --where E.Isdeleted =0
			Select * from #TempCity1 
		End
ELSE IF (@Category='O')
	IF(@userGroupName='SuperAdmin')
		SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent
		WHERE L.Type=3 AND L.ID=@ID
	ELSE
		SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then 'True' else 'False' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent
		WHERE L.Type=3 AND L.ID=@ID AND L.Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_SelectManualEntry null,'','01/01/1900','01/01/1900',null,'SuperAdmin','1','0',0,'',1
-- Proc_TA_SelectManualEntry null,'1001','01/01/1900','01/01/1900',null,'SuperAdmin','1','0',0,'ManualEntry',1
-- Modified by K.Gopinath (01.02.2014), for Filter the OnDuty Entry
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntry]
	@Employee_FirstName nvarchar(50) = null, 
	@Employee_Code_Id nvarchar(15) = null, 
	@StartDate datetime = '01/01/1900', 
	@EndDate datetime = '01/01/1900' ,
	@EmpSwipeCard varchar(10),
	@UserGroupName NVARCHAR(250),
	@UserLevels nvarchar(2000),
	@GradeLevel nvarchar(20),
	@ParentID int,
	@Type varchar(15),
	@LoginEmployeeAutoId int    
AS
BEGIN
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @Isdel as int
	SET @Isdel = 0
	Declare @SqlQuery as varchar(5000)
	set @SqlQuery = ''
	DECLARE @dateFormat as int
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	declare @IndividualUserStatus int
	set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
	
	select	M.ManualTimeEntry_Employee_id as EmployeeCodeid, 
			M.ManualTimeEntry_Id,
			Convert(varchar,M.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, @dateFormat) 
			end AS ManualTimeEntry_InDate,	
			M.ManualTimeEntry_InTime,
			case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_InPunchType
					else M.ManualTimeEntry_InPunchType 
			end ManualTimeEntry_InPunchType,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,@dateFormat),' ','-') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, @dateFormat) 
			end AS ManualTimeEntry_OutDate,	
			M.ManualTimeEntry_OutTime,
			case	when Latitude_value is not null and Longitude_value is not null then 'M - ' + M.ManualTimeEntry_OutPunchType
					else M.ManualTimeEntry_OutPunchType 
			end ManualTimeEntry_OutPunchType,
			case	when Latitude_value is not null and Longitude_value is not null then Clock_Address 
					else M.ManualTimeEntry_Reason 
			end ManualTimeEntry_Reason,
			M.ManualTimeEntry_Status,
			E.Employee_FirstName + SPACE(1) + isnull(E.Employee_LastName,'''') AS Employee_Name,
			M.IsOnDuty,
			EntryType=case when M.IsImported=0 then 'M / D' 
				 when M.IsImported=1 then 'I' 
				 when M.IsImported=2 then 'Mo' 
				 when M.IsImported=3 then 'GA'
			end,
			ProcessStatus=case	when Clk_Process='N' then 'NP'
								when Clk_Process='Y' then 'P'	
						  END
	FROM TA_Tbl_ManualTimeEntry as M
	INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id
	and M.Isdeleted=0 and E.IsDeleted=0 and E.Employee_Status=1 and ys.IsActive=1 
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId 
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid	
	where E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND M.IsOnDuty=0
	AND EDesig.EffectiveDate=(Select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id order by EffectiveDate desc) 
	AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
	and ((@IndividualUserStatus  = 0) or (E.Employee_Id=@LoginEmployeeAutoId))
	and (@UserGroupName='SuperAdmin' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	and (@isReportingto = 0 or (E.Employee_ID IN (select * from #EmployeeIds)))
	and (isnull(@Employee_Code_Id,'')='' or E.Employee_Code_Id like cast(@Employee_Code_Id+'%' as nvarchar(50)))
	and (isnull(@Employee_FirstName,'')='' or (E.Employee_FirstName + ' ' + isnull(E.Employee_LastName,'') like cast(@Employee_FirstName+'%' as nvarchar(100)))) 
	and ((@Type<>'Both' and M.IsOnDuty != 1) or (@Type='ODEntry' and M.IsOnDuty = 1) )
	and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_InDate between @StartDate and @EndDate))
	and ((@StartDate = '01/01/1900' and @EndDate = '01/01/1900') or (M.ManualTimeEntry_OutDate between @StartDate and @EndDate))
	Order by M.ManualTimeentry_id desc
	Execute (@SqlQuery)
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDuty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_SelectManualEntryOnDuty] null,null,'01/01/1900','01/01/1900',null,'SuperAdmin','1','0','1',1  
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDuty]  
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = '01/01/1900',   
	@EndDate datetime = '01/01/1900' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(8000)  
	set @SqlQuery = ''  
	Declare @SqlQuery2 as varchar(8000)  
	set @SqlQuery2 = ''  
	DECLARE @dateFormat as int
		DECLARE @TimeFormat as nvarchar(25)
		Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
		set @SqlQuery = @SqlQuery + 'select M. ManualTimeEntry_Employee_Id as EmployeeID, M.ManualTimeEntry_Id,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_Date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS OndutyEntry_Date, 
	  case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.shift_date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.shift_date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS shiftDate, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_InDate ,
	 CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,ManualTimeEntry_InTime,0)), 114) 
									ELSE SUBSTRING(ManualTimeEntry_InTime,13,5)+'' '' + SUBSTRING(ManualTimeEntry_InTime,18,2)									 
									END ManualTimeEntry_InTime,
	 M.ManualTimeEntry_InPunchType,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_OutDate,
	 CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,ManualTimeEntry_OutTime,0)), 114)
									ELSE SUBSTRING(ManualTimeEntry_OutTime,13,5)+'' '' + SUBSTRING(ManualTimeEntry_OutTime,18,2) 
									END ManualTimeEntry_OutTime
	 ,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then '''+
	   +''' + cast(E.Employee_MiddleName as varchar(50)) else '''+   +''' end + SPACE(1) + E.Employee_LastName AS Employee_Name,E.Employee_Id as EmpID '  
	 set @SqlQuery = @SqlQuery + 'FROM TA_Tbl_ManualTimeEntry as M '  
	 set @SqlQuery = @SqlQuery + 'INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id '  
	 set @SqlQuery = @SqlQuery + 'INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id '  
	 set @SqlQuery = @SqlQuery + 'and M.Isdeleted=0 and E.IsDeleted=0 and ys.IsActive=1 '  
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'  
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'  
	 set @SqlQuery =@SqlQuery +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'  
	 set @SqlQuery = @SqlQuery + ' WHERE E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) '
	 set @SqlQuery = @SqlQuery + ' AND E.Employee_Status=1 AND M.IsOnDuty=1'  
	 If not(@Employee_Code_Id = '' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + ' and E.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''  
	 End  
		If Not (@EmpSwipeCard = '')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
	 End   
	 If not(@Employee_FirstName = '' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= '(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')'
		set @SqlQuery2 = @SqlQuery2 + ' and '+ @Tempname +'= ''' + cast(@Employee_FirstName as nvarchar(100)) + ''')'   
	 End  
	 If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + ' and (M.ManualTimeEntry_InDate between convert(datetime,''' + cast(@StartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@EndDate as nvarchar(11)) + ''',101)'  
	 End  
	 If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + ' or M.ManualTimeEntry_OutDate between convert(datetime,''' + cast(@StartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@EndDate as nvarchar(11)) + ''',101))'  
	 End  
		set @SqlQuery2 = @SqlQuery2 + ' order by ManualTimeEntry_Date desc'  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyByID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_SelectManualEntryOnDutyByID] 916, null,null,'01/01/1900','01/01/1900',null,'SuperAdmin','1','0','1',1 
-- CReate by Gopinath on 6thJun2014 for Individual users 
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyByID]  
	@Employee_Id nvarchar(50),
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = '01/01/1900',   
	@EndDate datetime = '01/01/1900' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(max)  
	set @SqlQuery = ''  
	Declare @SqlQuery2 as varchar(mAX)  
	set @SqlQuery2 = ''  
		DECLARE @dateFormat as int
		SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	BEGIN  
	 set @SqlQuery = @SqlQuery + 'select M. ManualTimeEntry_Employee_Id as EmployeeID, M.ManualTimeEntry_Id,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_Date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_Date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_Date, 
	  case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.shift_date,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.shift_date, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS shiftDate, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_InDate ,
	 M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS ManualTimeEntry_OutDate,
	 M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then '''+
	   +''' + cast(E.Employee_MiddleName as varchar(50)) else '''+   +''' end + SPACE(1) + E.Employee_LastName AS Employee_Name '  
	 set @SqlQuery = @SqlQuery + 'FROM TA_Tbl_ManualTimeEntry as M '  
	 set @SqlQuery = @SqlQuery + 'INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id '  
	 set @SqlQuery = @SqlQuery + 'INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id '  
	 set @SqlQuery = @SqlQuery + 'and M.Isdeleted=0 and E.IsDeleted=0 and ys.IsActive=1 '  
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'  
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'  
	 set @SqlQuery =@SqlQuery +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'  
	 set @SqlQuery = @SqlQuery + ' WHERE E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) '
	 set @SqlQuery = @SqlQuery + ' AND E.Employee_Status=1 AND M.ManualTimeEntry_Employee_Id=''' + cast(@Employee_Id as nvarchar(100))  + ''' AND M.IsOnDuty=1 ' 
	 If not(@Employee_Code_Id = '' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + ' and E.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''  
	 End  
		If Not (@EmpSwipeCard = '')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
	 End   
	 If not(@Employee_FirstName = '' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= '(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')'
		set @SqlQuery2 = @SqlQuery2 + ' and '+ @Tempname +'= ''' + cast(@Employee_FirstName as nvarchar(100)) + ''')'   
	 End  
	 If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + ' and (M.ManualTimeEntry_InDate between convert(datetime,''' + cast(@StartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@EndDate as nvarchar(11)) + ''',101)'  
	 End  
	 If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + ' or M.ManualTimeEntry_OutDate between convert(datetime,''' + cast(@StartDate as nvarchar(11)) + ''', 101) and convert(datetime,''' + cast(@EndDate as nvarchar(11)) + ''',101))'  
	 End  
		set @SqlQuery2 = @SqlQuery2 + ' order by ManualTimeEntry_Date desc'  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
	END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_SelectManualEntryOnDutyForTable] null,null,'01/01/1900','01/01/1900',null,'SuperAdmin','16','0','1',0
--Select * from TA_Tbl_OndutyEntry
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]  
      @Employee_FirstName nvarchar(50) = null,   
      @Employee_Code_Id nvarchar(15) = null,   
      @StartDate datetime = '01/01/1900',   
      @EndDate datetime = '01/01/1900' ,  
      @EmpSwipeCard varchar(15),  
      @UserGroupName NVARCHAR(250),  
      @UserLevels varchar(8000),  
      @GradeLevel nvarchar(20),  
      @EmpAutoId varchar(10),  
      @ParentID int  
AS   
begin
Set nocount on;
      create table #LevelRights(LevelId int)  
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
      declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](CAST(@EmpAutoId as int)) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](CAST(@EmpAutoId as int)) as EmpAutoId
      Declare @SqlQuery as varchar(MAX)  
      set @SqlQuery = ''  
      Declare @SqlQuery2 as varchar(MAX)  
      set @SqlQuery2 = ''  
		DECLARE @dateFormat as int
		DECLARE @TimeFormat as nvarchar(25)
		Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
      BEGIN  
       set @SqlQuery = @SqlQuery + 'select OD.Onduty_EmployeeId as EmployeeID, OD.Onduty_ID,
      case when '+cast(@dateFormat as varchar(100))+'=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
            else CONVERT(VARCHAR, OD.Onduty_EntryDate, '+cast(@dateFormat as varchar(100))+')
            end 
       AS OndutyEntry_Date, 
       case when '+cast(@dateFormat as varchar(100))+'=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
            else CONVERT(VARCHAR, OD.Onduty_FromDate, '+cast(@dateFormat as varchar(100))+')
            end 
       AS Onduty_FromDate ,
      CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Onduty_FromTime,0)), 114),0,6)
									ELSE Onduty_FromTime
									END Onduty_FromTime,
      case when '+cast(@dateFormat as varchar(100))+'=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
            else CONVERT(VARCHAR, OD.Onduty_ToDate, '+cast(@dateFormat as varchar(100))+')
            end 
       AS Onduty_ToDate,
       CASE	WHEN ('''+convert(varchar(10),@TIMEFORMAT)+''')=''HH:MM'' THEN substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Onduty_ToTime,0)), 114),0,6)
									ELSE Onduty_ToTime
									END Onduty_ToTime
      ,OD.Onduty_Reason,OD.Onduty_Status,E.Employee_FirstName + isnull(E.Employee_LastName,'''') AS Employee_Name,E.Employee_Id as EmpID '  
            set @SqlQuery = @SqlQuery + 'FROM TA_Tbl_OndutyEntry OD '  
            set @SqlQuery = @SqlQuery + ' INNER JOIN TA_Tbl_YearSetting ys on (ys.YearSettings_Id=OD.YearSettings_Id and isActive=1)'
            set @SqlQuery = @SqlQuery + 'INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=OD.Onduty_EmployeeId '  
            set @SqlQuery = @SqlQuery + 'and OD.Isdeleted=0 and E.IsDeleted=0 '    
            set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel el on E.Employee_Id = el.EmployeeId '
            set @sqlQuery = @sqlQuery + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
            set @sqlQuery = @sqlQuery + ' inner join #LevelRights on #LevelRights.LevelId=ld.id '
            set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'  
            set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'  
            set @SqlQuery =@SqlQuery +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '  
        set @SqlQuery = @SqlQuery + ' WHERE E.Employee_Code_Id=OD.Onduty_EmployeeId AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) '
      set @SqlQuery = @SqlQuery + ' AND E.Employee_Status=1'  
       If not(@Employee_Code_Id = '' or @Employee_Code_Id is null)  
       Begin  
        Set @SqlQuery2 = @SqlQuery2 + ' and E.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''  
       End  
       if(@isReportingto > 0)
            BEGIN
               set @SqlQuery2 = @SqlQuery2 + ' and (E.Employee_ID IN (select * from #EmployeeIds)) '  
            END
            If Not (@EmpSwipeCard = '')    
            Begin    
            Set @SqlQuery2 = @SqlQuery2 + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
       End   
       If not(@Employee_FirstName = '' or @Employee_FirstName is null)  
       Begin  
            Declare @Tempname nvarchar(200)
            set @Tempname= '(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')'
            set @SqlQuery2 = @SqlQuery2 + ' and '+ @Tempname +'= ''' + cast(@Employee_FirstName as nvarchar(100)) + ''')'   
       End  
       If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
       Begin  
        set @SqlQuery2 = @SqlQuery2 + ' AND (((CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
            set @SqlQuery2 = @SqlQuery2 + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102)))'
      End  
            set @SqlQuery2 = @SqlQuery2 + ' order by Onduty_ID desc'  
       Exec (@SqlQuery+@SqlQuery2)  
       drop table #LevelRights  
      END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualTimeDashBoard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualTimeDashBoard]
@Employee_Code_Id Nvarchar(50)='1139',
@Date Nvarchar(50)='2024-06-26',
@Flag Nvarchar(50)='Shift In'
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @CountIN nvarchar(10)
	declare @CountIN1 nvarchar(10)
	declare @CountIN2 nvarchar(10)
	declare @TempCountIN1 nvarchar(10)
	declare @TempCountIN2 nvarchar(10)
	declare @In nvarchar(10)
	Select @CountIN1= Count(*)
			from TA_Tbl_ManualTimeEntry where
			ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_InDate=@Date and ManualTimeEntry_Status='Approved'and
			ManualTimeEntry_InPunchType in
			( Select ManualTimeEntry_InPunchType from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InPunchType in ('In','Shift In'))
			Select @CountIN2= Count(*)
			from TA_Tbl_ManualTimeEntry where
			ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_OutDate=@Date and ManualTimeEntry_Status='Approved'and
			ManualTimeEntry_OutPunchType in
			( Select ManualTimeEntry_OutPunchType from TA_Tbl_ManualTimeEntry where ManualTimeEntry_OutPunchType in ('Out','Shift Out'))
	if(@Flag ='Shift In')
	begin
		Select @CountIN=Count(*) from TA_Tbl_ProcessedData where Employee_Code_Id= @Employee_Code_Id and Date=@Date and ProcessFlag=1
		if(@CountIN>0)
		begin
			--print @CountIN
		 Select isnull(InTime,'NO') as InTime,isnull(OutTime,'NO') as OutTime from TA_Tbl_ProcessedData where Employee_Code_Id= @Employee_Code_Id and Date=@Date and ProcessFlag=1
		end
		else if(@CountIN1>0)
		begin
			Select  ISNULL(
        FORMAT(TRY_CAST(ManualTimeEntry_InTime AS DATETIME),'hh:mm:ss tt'), 'NO') AS InTime,ManualTimeEntry_Employee_Id as EmpId into #Temp1
			from TA_Tbl_ManualTimeEntry where
			ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_InDate=@Date and ManualTimeEntry_Status='Approved'and
			ManualTimeEntry_InPunchType in
			( Select ManualTimeEntry_InPunchType from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InPunchType in ('In','Shift In'))
			Select @TempCountIN1=Count(*) from #Temp1
			--print @TempCountIN1
		end
		 if (@CountIN2>=0)
		begin
			
			Select top(1) isnull(FORMAT(TRY_CAST(
			ManualTimeEntry_OutTime as DATETIME),'hh:mm:ss tt'),'NO') as OutTime,ManualTimeEntry_Employee_Id as EMID into #Temp2
			from TA_Tbl_ManualTimeEntry where
			ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_OutDate=@Date and ManualTimeEntry_Status='Approved'and
			ManualTimeEntry_OutPunchType in
			( Select ManualTimeEntry_OutPunchType from TA_Tbl_ManualTimeEntry where ManualTimeEntry_OutPunchType in ('Out','Shift Out'))
			order by ManualTimeEntry_Id desc
		end
		if(@TempCountIN1>0)
		begin
			Select * from  #Temp2
			Select  #Temp1.InTime as InTime,#Temp2.OutTime as OutTime from #Temp1
			inner Join #Temp2 on #Temp2.EMID=#Temp1.EmpId
			group by #Temp1.EmpId,#Temp1.InTime ,#Temp2.OutTime
			
drop table #Temp1
drop table #Temp2
		end
		else
		begin
		Select 'NO' as  InTime,'NO' as OutTime
		end
	end
	else if(@Flag ='Break In')
	begin
	Select top(1) isnull(ManualTimeEntry_InTime,'NO') as BreakIN from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_InDate=@Date and
	ManualTimeEntry_InPunchType !='In' and 	ManualTimeEntry_InPunchType !='Shift In' and ManualTimeEntry_Status='Approved' order by ManualTimeEntry_Id asc
	--and Clk_Process='P'
	end
	else if(@Flag ='Break Out')
	begin
	Select isnull(Max(ManualTimeEntry_OutTime),'NO') as BreakOut from TA_Tbl_ManualTimeEntry
	where ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_OutDate=@Date and
	  ManualTimeEntry_OutPunchType!='Out' and  ManualTimeEntry_Status='Approved' --order by ManualTimeEntry_Id desc
	--and Clk_Process='P'
	end
	--Select * from TA_Tbl_ProcessedData where Employee_Code_Id= @Employee_Code_Id and Date=@Date and ProcessFlag=1
   --Select Max(ManualTimeEntry_OutTime) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id =@Employee_Code_Id and ManualTimeEntry_OutDate='2024-05-02' and  ManualTimeEntry_OutPunchType!='Out'
   --order by ManualTimeEntry_Id desc
	--ManualTimeEntry_InPunchType !='In' and 	ManualTimeEntry_InPunchType !='Shift In'
	--inner join TA_Tbl_ProcessedData on TA_Tbl_ProcessedData.Date =TA_Tbl_ManualTimeEntry.
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualTimeEntryforMail]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectManualTimeEntryforMail 'TT9998','20240801','','',''
-- exec Proc_TA_SelectManualTimeEntryforMail @ManualEntry_EmployeeId=N'TT9998',@ManualEntry_Date='2024-09-12 00:00:00',@InDate=N'2024/09/11',@OutDate=N'',@Type=N''
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_SelectManualTimeEntryforMail]  

	@ManualEntry_EmployeeId NVARCHAR(20)='T001',
	@ManualEntry_Date DATETIME ='2024',
	@InDate NVARCHAR(15),  
	@OutDate NVARCHAR(15),
	@Type NVARCHAR(15)


AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LevelID nvarchar(10)
	if(@Type != '' or @Type!=null)
	begin 
	Select @LevelID= levelId From [dbo].[Func_TA_EmpLevel](getdate(),@ManualEntry_EmployeeId)
   Select ManualTimeEntry_Employee_Id,ManualTimeEntry_Id,TA_Tbl_Employee.EmailId,TA_Tbl_Employee.Employee_FirstName +' '+TA_Tbl_Employee.Employee_MiddleName +' '+
   TA_Tbl_Employee.Employee_LastName as Employeename ,[dbo].[Func_TA_GetParentIds](@LevelID) as ParentID,ManualTimeEntry_InDate,ManualTimeEntry_OutDate,ManualTimeEntry_InPunchType,ManualTimeEntry_InTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutTime,ManualTimeEntry_Status,ManualTimeEntry_Remarks
   from TA_Tbl_ManualTimeEntry 
   inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id
   where ManualTimeEntry_Id=@Type
   and TA_Tbl_ManualTimeEntry.Isdeleted=0
	end 
	else
	begin

	--declare @LevelID nvarchar(10)
	Select @LevelID= levelId From [dbo].[Func_TA_EmpLevel](getdate(),@ManualEntry_EmployeeId)
	Select ManualTimeEntry_Employee_Id,ManualTimeEntry_Id,TA_Tbl_Employee.EmailId,TA_Tbl_Employee.Employee_FirstName +' '+TA_Tbl_Employee.Employee_MiddleName +' '+
   TA_Tbl_Employee.Employee_LastName as Employeename ,[dbo].[Func_TA_GetParentIds](@LevelID) as ParentID,ManualTimeEntry_InDate,ManualTimeEntry_OutDate,ManualTimeEntry_InPunchType,ManualTimeEntry_InTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutTime,ManualTimeEntry_Status,ManualTimeEntry_Remarks
   from TA_Tbl_ManualTimeEntry 
   inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Code_Id =TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id
   where ManualTimeEntry_Employee_Id=@ManualEntry_EmployeeId and ManualTimeEntry_Date=@ManualEntry_Date and TA_Tbl_ManualTimeEntry.Isdeleted =0 
   and ManualTimeEntry_Status!='Deleted'
   and (ManualTimeEntry_InDate=@InDate or ManualTimeEntry_OutDate=@OutDate)

	end

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMatchingDevice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- [Proc_TA_SelectMatchingDevice]'28', 'In'  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectMatchingDevice]  
 @ReaderID as varchar(25),  
 @Para as varchar(25)  
AS  
BEGIN  
 declare @DeviceID as int  
 set @DeviceID = (Select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@ReaderID)  
 if @Para='In'  
 Begin  
  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type='Out'  
  Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type='In'  
 End  
 if @Para='Out'  
 Begin  
  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type='In'  
  Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type='Out'  
 End  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_SelectMaxDayMonth 72,9,'06/Aug/2013',1,0
/*
Modified By			:	Manjula.P
Modified Date		:	01-Aug-2013
Descriptions		:	Adding SL Concepts with max applicable days 
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth]    
 -- Add the parameters for the stored procedure here    
@EmpID INT ,
@intLeaveTypeId INT,
@FromDate datetime ,
@isAccumulated bit,
@LeaveApplicationId int=0
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON; 
 declare @LeaveTypeId int=0;
 declare @SLLeaveTypeId int=0;
 set @LeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType='CL');
 --adding for SL by MAnjula.P on 08-Aug-2013
 set @SLLeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType='SL');
 declare @Todate as datetime;
 declare @YearSettingId as int
 set @YearSettingId = (select YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate)   
 set @Todate=(SELECT isnull(max(Leave_ToDate),@FromDate) FROM TA_Tbl_LeaveApplication WHERE Employee_Id = @EmpID AND Status<>'Rejected' 
 and IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>'LOP' and YearSettings_Id=@YearSettingId)
if(@Todate>= @FromDate)
set @Todate=@Todate
else
set @Todate=@FromDate
    -- Insert statements for procedure here    
declare @fltMaxDays as decimal(18,2)
 --adding for SL by MAnjula.P on 08-Aug-2013
declare @SLfltMaxDays as decimal(18,2)=0;
set @fltMaxDays =(SELECT top 1 isnull(cast(LPD.MaxDays_applicable as float)/12,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
--Following code commented by Prabakaran.P on 15-Feb-08, changes based on Year closure modification
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id  
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
 --adding for SL by MAnjula.P on 08-Aug-2013
set @SLfltMaxDays =(SELECT top 1 isnull(LPD.MaxDays_applicable,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
inner join  TA_Tbl_Employee E on E.Employee_Id=ELP.EmployeeId and E.Isdeleted=0
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id      
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
and ISNULL( DATEDIFF(MONTH, E.DateOfJoining,@FromDate),0)>=2
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
--for getting accumulated months availabel leaves By Manjula.P on 27-May-2013
declare @TotalMonth as int
set @TotalMonth=(
select ISNULL( DATEDIFF(MONTH,YS.FromDate,@Todate),0) as month from TA_Tbl_YearSetting YS
where YS.YearSettings_Id=@YearSettingId )
set @TotalMonth= @TotalMonth+1
--getting applied leave days count
declare @AppliedDays as decimal(18,2)=0;
IF (EXISTS(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
where 
Leave_ToDate between YS.FromDate and @Todate
and 
Employee_Id=@EmpID 
and 
LA.Status<>'Rejected' and LA.IsDeleted=0  and LeaveType_id =@LeaveTypeId and type<>'LOP' and type<>'Comp Off' and LeaveApplication_Id<>@LeaveApplicationId
and YS.YearSettings_Id=@YearSettingId
) and @intLeaveTypeId = @LeaveTypeId)
	begin
	set @AppliedDays=(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
	where 
	Leave_ToDate between YS.FromDate and @Todate 
	and 
	Employee_Id=@EmpID 
	and 
	LA.Status<>'Rejected' and LA.IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>'LOP' and type<>'Comp Off' and LeaveApplication_Id<>@LeaveApplicationId
	and YS.YearSettings_Id=@YearSettingId
	--group by LA.NumberOfDays
	)
	end
---/////////////////////////////////////////////
if(@isAccumulated=1 and @intLeaveTypeId=@LeaveTypeId)
	begin
	select isnull((isnull(@fltMaxDays,0.0)*@TotalMonth)-(@AppliedDays),0) as MaxDays_Month
	end
	 --adding for SL by MAnjula.P on 08-Aug-2013
else if(@intLeaveTypeId=@SLLeaveTypeId)
	BEGIN
	 select ISNULL( @SLfltMaxDays-@AppliedDays,0) as MaxDays_Month
	END
	--*******************************************
	else
	select (isnull(@fltMaxDays,0.0)) as MaxDays_Month
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth_Testing]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth_Testing]    
 -- Add the parameters for the stored procedure here    
@EmpID INT ,
@intLeaveTypeId INT,
@FromDate datetime ,
@isAccumulated bit,
@LeaveApplicationId int=0
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON; 
 declare @LeaveTypeId int=0;
 set @LeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType='CL');
 declare @Todate as datetime;
 declare @YearSettingId as int
 set @YearSettingId = (select YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate)   
 set @Todate=(SELECT isnull(max(Leave_ToDate),@FromDate) FROM TA_Tbl_LeaveApplication WHERE Employee_Id = @EmpID AND Status<>'Rejected' 
 and IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>'LOP' and YearSettings_Id=@YearSettingId)
if(@Todate>= @FromDate)
set @Todate=@Todate
else
set @Todate=@FromDate
    -- Insert statements for procedure here    
declare @fltMaxDays as decimal(18,2)
set @fltMaxDays =(SELECT top 1 isnull(cast(LPD.MaxDays_applicable as float)/12,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
--Following code commented by Prabakaran.P on 15-Feb-08, changes based on Year closure modification
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id 
-- inner join Ta_tbl_Yearsetting YS on LP.Policy_Year=YS.YearSettings_Id  
--LEFT OUTER JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id=EL.LeavePolicy_Id    
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
--for getting accumulated months availabel leaves By Manjula.P on 27-May-2013
declare @TotalMonth as int
set @TotalMonth=(
select ISNULL( DATEDIFF(MONTH,YS.FromDate,@Todate),0) as month from TA_Tbl_YearSetting YS
where YS.YearSettings_Id=@YearSettingId )
set @TotalMonth= @TotalMonth+1
--getting applied leave days count
declare @AppliedDays as decimal(18,2)=0;
IF (EXISTS(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
where 
Leave_ToDate between YS.FromDate and @Todate
and 
Employee_Id=@EmpID 
and 
LA.Status<>'Rejected' and LA.IsDeleted=0  and LeaveType_id =@LeaveTypeId and type<>'LOP' and type<>'Comp Off' and LeaveApplication_Id<>@LeaveApplicationId
and YS.YearSettings_Id=@YearSettingId
) and @intLeaveTypeId = @LeaveTypeId)
	begin
	set @AppliedDays=(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
	where 
	Leave_ToDate between YS.FromDate and @Todate 
	and 
	Employee_Id=@EmpID 
	and 
	LA.Status<>'Rejected' and LA.IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>'LOP' and type<>'Comp Off' and LeaveApplication_Id<>@LeaveApplicationId
	and YS.YearSettings_Id=@YearSettingId
	--group by LA.NumberOfDays
	)
	end
---/////////////////////////////////////////////
if(@isAccumulated=1 and @intLeaveTypeId=@LeaveTypeId)
begin
select isnull((isnull(@fltMaxDays,0.0)*@TotalMonth)-(@AppliedDays),0) as MaxDays_Month
end
else
select (isnull(@fltMaxDays,0.0)) as MaxDays_Month
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxEmpID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxEmpID]
AS
BEGIN
	SELECT MAX(Employee_Id) AS MaxID FROM TA_Tbl_Employee
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID] 
AS
BEGIN
	SET NOCOUNT ON;
	SELECT MAX(Emp_LeavePolicyId) AS MaxID FROM TA_Tbl_Emp_LeavePolicy
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated] '09/01/2008','09/30/2008','151'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated] 
@FromDate datetime,
@ToDate datetime,
@EmployeeID as int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--SELECT MAX(Emp_LeavePolicyId) AS MaxID FROM TA_Tbl_Emp_LeavePolicy
	 select Emp_LeavePolicyId as MaxID from TA_Tbl_Emp_LeavePolicy where fromdate=@fromDate and todate=@todate and EmployeeId=@employeeid
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxHoliday]
AS
BEGIN
	Select * from TA_Tbl_HolidaySettings
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaximumNoOfHolidays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectMaximumNoOfHolidays
Description	:	Get Restricted Holidays from Holiday settings table
Tables Included	:	TA_Tbl_HolidaySettings
Created By	:	Prabakaran
Created On	:	13-Aug-07
Modified By	:
Modified On	:
*/
CREATE      procedure [dbo].[Proc_TA_SelectMaximumNoOfHolidays]
(
	@YearSettingID int
)
as
BEGIN
	if exists(select Yearly_Maxdays as RetrictedHolidays from TA_Tbl_HolidaySettings hs
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId
	where ys.YearSettings_Id=@YearSettingID)
	BEGIN
	    select Yearly_Maxdays as RetrictedHolidays from TA_Tbl_HolidaySettings hs
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId
		where ys.YearSettings_Id=@YearSettingID
	END
	ELSE
	BEGIN
		select 0 as RetrictedHolidays
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXLeavePolicyID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Max Policy ID - select
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXLeavePolicyID] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(Policy_Id) AS MAX_PolicyID FROM TA_Tbl_LeavePolicy WHERE IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxPayrollClosureDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxPayrollClosureDate]
 AS
Begin
	SELECT Max(MonthClosure_EndDate) AS MonthClosure_EndDate FROM TA_Tbl_MonthClosure WHERE IsDeleted = 0 AND Process = 'P'
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMinLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectMinLevel 1,0
CREATE PROCEDURE [dbo].[Proc_TA_SelectMinLevel]
(
 @orgLevelId int,
 @ParentLevelId int
)
AS
BEGIN
	Create Table #TempLevel(LevelId int)
	Declare @ParentID varchar(20)
	declare @orgID_ToAdd int 
	declare @orgID_ParentSelected int
	declare @TopOrgId int
	Select @ParentID=parentLevelID from TA_Tbl_Level where levelID=@orgLevelId and isDeleted=0
	while @ParentID<>0
		begin
			Insert into #TempLevel values(@ParentID)
			Select @ParentID=parentLevelID from TA_Tbl_Level where levelID=@ParentID and isDeleted=0
		end
	set @orgID_ToAdd = (select top 1 LevelId from #TempLevel where LevelId<@orgLevelId)
	set @orgID_ParentSelected = (select levelId from Ta_Tbl_levelDetails where id=@ParentLevelId)
	--select min(levelID) as MinLevel from ta_tbl_level  where isdeleted=0
	if(@orgID_ToAdd = @orgID_ParentSelected)
		BEGIN
			select 1 as Result
		END
	else
		BEGIN			
			set @TopOrgId = (select parentLevelId from TA_Tbl_Level where levelId=@orgLevelId)
			if(@TopOrgId = 0)
				BEGIN
					select 1  as Result
				END
			else
				BEGIN
					select 0  as Result
				END
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthCloseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthCloseDetails]
(
 @TYPE CHAR(1)='',
 @MonthCloseID INT
)
AS
BEGIN	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	DECLARE @Isdeleted INT
	SET @Isdeleted=0
	IF (@TYPE='A')
		BEGIN
			SELECT M.MonthClosure_Id,L.[Name],MonthClosure_Month,MonthClosure_Year,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_StartDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, MonthClosure_StartDate, @dateFormat) end AS MonthClosure_StartDate,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_EndDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, MonthClosure_EndDate, @dateFormat)end AS MonthClosure_EndDate,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_ClosingDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, MonthClosure_ClosingDate, @dateFormat)end AS MonthClosure_ClosingDate 
			FROM TA_Tbl_MonthClosure M
			INNER JOIN TA_Tbl_LevelDetails L  ON M.OrgLevel_Id = L.[Id]
			INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id  
			WHERE ys.IsActive=1 and M.Isdeleted=@Isdeleted			
		END
	ELSE IF (@TYPE='P')
		BEGIN
			SELECT L.[Name],M.MonthClosure_Month,M.MonthClosure_Year,
			CONVERT(VARCHAR,M.MonthClosure_StartDate,101) AS MonthClosure_StartDate,
			CONVERT(VARCHAR,M.MonthClosure_EndDate,101) AS MonthClosure_EndDate,
			CONVERT(VARCHAR,M.MonthClosure_ClosingDate,101) AS MonthClosure_ClosingDate 
			FROM TA_Tbl_MonthClosure M,TA_Tbl_LevelDetails L WHERE M.OrgLevel_Id = L.[Id] AND M.MonthClosure_Id=@MonthCloseID AND M.IsDeleted=@Isdeleted
		END
	ELSE If (@TYPE='I')
		BEGIN
			SELECT M.MonthClosure_Id, M.OrgLevel_Id,L.[Name],MonthClosure_Month,MonthClosure_Year,
			CONVERT(VARCHAR,MonthClosure_StartDate,101) AS MonthClosure_StartDate,
			CONVERT(VARCHAR,MonthClosure_EndDate,101) AS MonthClosure_EndDate,
			CONVERT(VARCHAR,MonthClosure_ClosingDate,101) AS MonthClosure_ClosingDate
			FROM TA_Tbl_MonthClosure M,TA_Tbl_LevelDetails L
			WHERE M.Isdeleted=@Isdeleted AND MonthClosure_Id=@MonthCloseID AND M.OrgLevel_Id = L.[Id]
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthClosureById]
	@MonthClosureID as int
AS
BEGIN
	select MonthClosure_Month, MonthClosure_Year from ta_tbl_monthclosure where MonthClosure_Id=@MonthClosureID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  <Author,,Name>  
-- ALTER  date: <Create Date,,>  select * from ta_tbl_monthclosure
-- Description: <Description,,>  select * from ta_tbl_payrollprocessdetails
-- Proc_TA_SelectMonthClosureDetails 2,1,'02/01/2016','02/29/2016','02/29/2016'  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthClosureDetails]  
-- Add the parameters for the stored procedure here  
@monthClosureId int,  
@levelId int,   
@startDate nvarchar(25),  
@endDate nvarchar(25),  
@closedDate nvarchar(25)  
AS  
declare @sqlQuery as nvarchar(4000)      
set @sqlQuery=''      
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from  
	-- interfering with SELECT statements.  
	SET NOCOUNT ON;  
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ,[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ,[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ,[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	-- Insert statements for procedure here  
	set @sqlQuery = @sqlQuery + 'select e.Employee_Code_Id as Employee_Id,
																			isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as EmployeeName,'  
	set @sqlQuery = @sqlQuery + '				ppd.HrsWork,
																			ppd.NormOT,
																			ppd.OffOT,
																			ppd.HolOT,
																			ppd.LateIn,
																			ppd.EarlyOut,'
	set @sqlQuery = @sqlQuery + '				mc.MonthClosure_Id,
																			isnull(ppd.LeaveDays,0) as LeaveDays,
																			isnull(ppd.PresentDays,0) as PresentDays,
																			isnull(ppd.AbsentDays,0) as AbsentDays,
																			isnull(ppd.Holidays,0) as Holidays,
																			isnull(ppd.LOPDays,0) as LOPDays,
																			isnull(ppd.TotalPermissionHours,''00:00'') TotalPermissionHours,
																			isnull(ppd.WeekOffDays,0) as WeekOffDays,
																			isnull(ppd.HrsLess,''00:00'') HrsLess,
																			isnull(ppd.HrsExtra,''00:00'') HrsExtra,
																			SPEC_NormOT1=isnull(SPEC_NormOT1,''00:00''),
            SPEC_NormOT2=isnull(SPEC_NormOT2,''00:00''),
            SPEC_OffOT1=isnull(SPEC_OffOT1,''00:00''),SPEC_OffOT2=isnull(SPEC_OffOT2,''00:00''),
            SPEC_HOLOT1=isnull(SPEC_HOLOT1,''00:00''),SPEC_HOLOT2=isnull(SPEC_HOLOT2,''00:00'')
																			from TA_Tbl_MonthClosure mc'   
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_PayrollProcessDetails ppd on ppd.MonthClosure_Id=mc.MonthClosure_Id'      
	set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_Employee e on e.SwipeCardNo=ppd.Employee_Id'    
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= e.Employee_Id '  
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id '   
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= e.Employee_Id '  
	Set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId '  
	SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId '  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'  
	set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'   
	set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=Lev.EffectiveDate and #EmpLevel.employeeid=Lev.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
	set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
	set @sqlQuery = @sqlQuery + ' where e.Isdeleted=0 and mc.IsDeleted=0 and mc.MonthClosure_StartDate=CONVERT(DATETIME, ''' +cast( @startDate as nvarchar(50))+ ''', 102) and mc.MonthClosure_EndDate=CONVERT(DATETIME, ''' +cast( @endDate as nvarchar(50))+ ''', 102) and mc.MonthClosure_ClosingDate=CONVERT(DATETIME, ''' +cast( @closedDate as nvarchar(50))+ ''', 102) And mc.MonthClosure_Id = '+cast(@monthClosureId as nvarchar(4))+' And mc.OrgLevel_Id = '+cast(@levelId as nvarchar(10))+''  
	set @sqlQuery = @sqlQuery + ' order by e.Employee_Code_Id'         
	exec(@sqlQuery)  
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectMovementsEntryXtraGrid 'Admin','10'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]
	-- Add the parameters for the stored procedure here
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LevelRights varchar(1000),
	@ParentId int,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
		set @sqlQuery = ''				
		set @sqlQuery = @sqlQuery + 'SELECT ED.employee_code_id AS [Employee Code Id],'       
		set @sqlQuery = @sqlQuery + ' ED.Employee_FirstName + '' '' + isnull(ED.Employee_LastName,'''') AS [Employee Name],'       
		set @sqlQuery = @sqlQuery + ' replace(TA_Tbl_Title.TitleName,''&amp;'',''&'')  AS [Designation],'       
		set @sqlQuery = @sqlQuery + ' replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS [Level Name],'      
		set @sqlQuery = @sqlQuery + ' CD.Clk_InDeviceId as [In ReaderID],ITer.Terminal_Name as [In Terminal], CONVERT(VARCHAR,CD.Clk_InDate,101) as [InDate], Convert(varchar(10),CD.Clk_InTime,108) as [InTime],'      
		set @sqlQuery = @sqlQuery + ' CD.Clk_OutDeviceId as [Out ReaderID], OTer.Terminal_Name as [Out Terminal], CONVERT(VARCHAR,CD.Clk_OutDate,101) as [OutDate], Convert(varchar(10),CD.Clk_OutTime,108) as [OutTime], CONVERT(VARCHAR,CD.Clk_Date,101) as [ClockDate], SH.Shift_ShortName as [Shift Short Name] FROM TA_Tbl_Employee ED'      		 
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on ED.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeDesignation ON ED.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'
   		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
		set @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'		
        set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_ClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId'
        set @sqlQuery = @sqlQuery + ' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'
		set @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Processeddata PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date'   
		set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID'  
	    set @sqlQuery = @sqlQuery + ' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID'        
	    set @sqlQuery = @sqlQuery + ' Where  ED.IsDeleted = 0 and ED.report_exclude=0 and ED.employee_status=1'     				
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'		
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''' + cast(@ToDate as nvarchar(50))  + ''', 102) order by EffectiveDate desc)'
		--set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
			if(@EmpAutoId = 0)
		BEGIN 
		  set @sqlQuery = @sqlQuery + ' and TA_Tbl_EmployeeLevel.LevelId in (' + @LevelRights +')'
		END
		ELSE
		   BEGIN
			  set @sqlQuery = @sqlQuery + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
		   END
		if(@UserGroupName<>'SuperAdmin')
		begin
		set @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ' '
		end
		If (@FromDate <> '')      
		 Begin      
		  Set @sqlQuery = @sqlQuery + 'And CD.Clk_Date >= ''' + @FromDate + ''' '      
		 End      
		 If (@ToDate <> '')      
		 Begin      
		  Set @sqlQuery = @sqlQuery + 'And CD.Clk_Date <= ''' + @ToDate + ''' '      
		 End   
		EXEC (@sqlQuery)
		drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextShiftId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_SelectNextShiftId]
(
	@EmployeeCodeId as varchar(15),
	@ShiftDate as datetime,
	@ShiftInDateTime as datetime,
	@WeeklyOffStartHours as varchar(5),
	@dtNextShiftStartTime as datetime output
)
--RETURNS varchar(20)
AS
--BEGIN
--Declare @dtNextShiftStartTime as varchar(20)
declare @WeeklyOffMinutes as int
set @WeeklyOffMinutes=(select DATePART(hh, cast(@WeeklyOffStartHours as Datetime))*60+DATePART(n, cast(@WeeklyOffStartHours as Datetime)))
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)
SET @query = 'SELECT (tsa.Day'+ cast(datepart(dd,@ShiftDate+1) as varchar(2)) + 'Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= ' + cast(datepart(yyyy,@ShiftDate+1) as varchar(4)) + '  and  tsa.[Month]= ' + cast(datepart(mm,@ShiftDate+1) as varchar(2)) + ' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''+ @EmployeeCodeId +''' '  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)
IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
SET @query = 'SELECT (tsa.Day'+ cast(datepart(dd,@ShiftDate+1) as varchar(2)) + 'Shift)  from TA_Tbl_PermanentShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= ' + cast(datepart(yyyy,@ShiftDate+1) as varchar(4)) + '  and  tsa.[Month]= ' + cast(datepart(mm,@ShiftDate+1) as varchar(2)) + ' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''+ @EmployeeCodeId +''' '  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
  SELECT ISNULL(@ShiftId,0)
END
IF(@ShiftId > 0)
BEGIN
    declare @shiftStartTime as varchar(8)
    set @shiftStartTime=(select Shift_StartTime from TA_tbl_Shift  where Shift_Id=@ShiftId)
 set @dtNextShiftStartTime=(@ShiftDate+1)+ @shiftStartTime
END
ELSE IF(@ShiftId = -1)
BEGIN
set @dtNextShiftStartTime=DateAdd(minute,@WeeklyOffMinutes,@ShiftInDateTime)
END
--ELSE IF(@ShiftId = 0)
--BEGIN
--END
set @dtNextShiftStartTime='2/01/2010'
DROP TABLE #Temp
DROP TABLE #Temp1
--return @dtNextShiftStartTime
--END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextYearSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectNextYearSetting]
AS
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + ' - ' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting,convert(nvarchar(20),FromDate,101) as YearSettingFromDate,convert(nvarchar(20),ToDate,101) as YearSettingToDate,* 
from Ta_Tbl_Yearsetting 
where 
YearSettings_Id=(select top 1 YearSettings_Id from Ta_Tbl_Yearsetting where YearSettings_Id > (select YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1) order by YearSettings_Id asc)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOnDutyEntryByID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_SelectManualEntryOnDutyByID] 916, null,null,'01/01/1900','01/01/1900',null,'SuperAdmin','1','0','1',1 
-- CReate by Gopinath on 6thJun2014 for Individual users 
CREATE PROCEDURE [dbo].[Proc_TA_SelectOnDutyEntryByID]  
	@Employee_Id nvarchar(50),
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = '01/01/1900',   
	@EndDate datetime = '01/01/1900' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(8000)  
	set @SqlQuery = ''  
	Declare @SqlQuery2 as varchar(8000)  
	set @SqlQuery2 = ''  
	DECLARE @dateFormat as int
		SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	BEGIN  
	  set @SqlQuery = @SqlQuery + 'select OD.Onduty_EmployeeId as EmployeeID, OD.Onduty_ID,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS OndutyEntry_Date, 
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_FromDate ,
	 OD.Onduty_FromTime,
	 case when '+cast(@dateFormat as varchar(100))+'=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, '+cast(@dateFormat as varchar(100))+')
		end 
	 AS Onduty_ToDate,
	 OD.Onduty_ToTime,OD.Onduty_Reason,OD.Onduty_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then '''+
	   +''' + cast(E.Employee_MiddleName as varchar(50)) else '''+   +''' end + SPACE(1) + E.Employee_LastName AS Employee_Name,E.Employee_Id as EmpID '  
	 set @SqlQuery = @SqlQuery + 'FROM TA_Tbl_OndutyEntry OD '  
	 set @SqlQuery = @SqlQuery + 'INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=OD.Onduty_EmployeeId '  
	 set @SqlQuery = @SqlQuery + 'and OD.Isdeleted=0 and E.IsDeleted=0 '    
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id'  
	 set @SqlQuery= @SqlQuery +' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId'  
	 set @SqlQuery =@SqlQuery +' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'  
	  set @SqlQuery = @SqlQuery + ' WHERE E.Employee_Code_Id=OD.Onduty_EmployeeId AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) '
	 set @SqlQuery = @SqlQuery + ' AND E.Employee_Status=1 and OD.Onduty_EmployeeId=''' + cast(@Employee_Id as nvarchar(100))  + ''''  
	 If not(@Employee_Code_Id = '' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + ' and E.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''  
	 End  
		If Not (@EmpSwipeCard = '')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + ' And E.SwipeCardNo = ''' + @EmpSwipeCard + ''' '    
	 End   
	 If not(@Employee_FirstName = '' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= '(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')'
		set @SqlQuery2 = @SqlQuery2 + ' and '+ @Tempname +'= ''' + cast(@Employee_FirstName as nvarchar(100)) + ''')'   
	 End  
	 If not(@StartDate = '01/01/1900' and @EndDate = '01/01/1900')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + ' AND (((CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )'
		set @SqlQuery2 = @SqlQuery2 + ' or (OD.Onduty_FromDate between CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, ''' +cast(@StartDate as nvarchar(50))   + ''', 102) and CONVERT(DATETIME, ''' +cast(@EndDate as nvarchar(50))   + ''', 102)))'
	 End  
		set @SqlQuery2 = @SqlQuery2 + ' order by Onduty_ID desc'  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
	END  
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectOrgDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_selectOrgDetails]
(
	@id int
)
AS
BEGIN
	select * from ta_tbl_levelDetails where id=@id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectOtType 5,'No','',''
CREATE PROCEDURE [dbo].[Proc_TA_SelectOtType]
	@OtTypeID int,
	@All nvarchar(3),
	@UserGroup nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroup,@ParentID) as LevelId 
declare @Query as varchar(7000)
BEGIN	
	if (@All='All')
		Begin	
			if (@UserGroup='SuperAdmin')
				BEGIN	
					--select * from TA_Tbl_OtType order by OtType
					set @Query=	'select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID,case when TA_Tbl_OtType.IsDeleted=1 then ''True'' else ''False'' end IsDeleted, TA_Tbl_OtType.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_OtType'
					set @Query= @Query + ' inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id'
					set @Query= @Query + ' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_OtType.CompanyId'
					--set @Query= @Query +	' where TA_Tbl_OtType.CompanyId in (' +@UserLevels+ ')'
					set @Query= @Query +	' order by ta_tbl_leveldetails.name' 
				End
			Else
				Begin
					--select * from TA_Tbl_OtType where isdeleted=0 order by OtType
					set @Query= 'select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID, case when TA_Tbl_OtType.IsDeleted=1 then ''True'' else ''False'' end IsDeleted, TA_Tbl_OtType.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_OtType'
					set @Query= @Query + ' inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id'
					set @Query= @Query + ' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_OtType.CompanyId'
					--set @Query= @Query + ' where TA_Tbl_OtType.isdeleted=0 and TA_Tbl_OtType.CompanyId in (' +@UserLevels+ ')'
					set @Query= @Query + ' where TA_Tbl_OtType.isdeleted=0'
					set @Query= @Query +	' order by ta_tbl_leveldetails.name' 
				End		
		End
	Else
		Begin
			set @Query= 'select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID, case when TA_Tbl_OtType.IsDeleted=1 then ''True'' else ''False'' end IsDeleted, TA_Tbl_OtType.TimeStamp from TA_Tbl_OtType where OtTypeID=' +cast(@OtTypeID as varchar(100))+ ' order by OtType'
		End
END
exec(@Query)
drop table #LevelRights
/*ALTER PROCEDURE [dbo].[Proc_TA_SelectOtType]
	@OtTypeID as int,
	@All as varchar(3),
	@UserGroup as varchar(25)	
AS
BEGIN	
	if (@All='All')
		Begin	
			if (@UserGroup='SuperAdmin')
				BEGIN	
					--select * from TA_Tbl_OtType order by OtType
						select TA_Tbl_OtType.*,ta_tbl_leveldetails.name  from TA_Tbl_OtType
						inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id
						order by ta_tbl_leveldetails.name
				End
			Else
				Begin
					--select * from TA_Tbl_OtType where isdeleted=0 order by OtType
					select TA_Tbl_OtType.*,ta_tbl_leveldetails.name  from TA_Tbl_OtType
						inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id
						where TA_Tbl_OtType.isdeleted=0
						order by ta_tbl_leveldetails.name
				End		
		End
	Else
		Begin
			select * from TA_Tbl_OtType where OtTypeID=@OtTypeID order by OtType
		End
END
*/
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectParentLevel]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_selectParentLevel]
(
	@levelId int
)
AS
BEGIN
	select * from ta_tbl_level where levelId=@levelId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNames]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [Proc_TA_SelectPayrollFieldNames] 'Summarized Data', 3
CREATE PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNames]
(
@DataType varchar(50),
@CompanyID int
)
AS
if(@DataType = 'SummarizedData')
	BEGIN
		if((select DemoType from TA_Tbl_Demo)='Express')
			begin
				SELECT column_name+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType='All' and TA_ExportData_FieldData.DataType='SummarizedData' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = 'TA_TBL_PayrollProcessDetails' AND column_name <> 'PayrollProcess_Id'
				AND column_name <> 'MonthClosure_Id' AND column_name <> 'User_Id' AND  column_name <> 'TimeStamp'
				--AND column_name <> 'MonthClosure_Id' AND column_name <> 'User_Id'
				AND column_name <> 'Emp_Id' AND column_name <> 'HrsWork' AND column_name <> 'HrsOt' AND column_name <> 'NormOt' AND column_name <> 'WorkHrs' AND column_name <> 'HolOT' AND column_name <> 'OffOT'
				union all
				select '','Hours_Worked','',''
				union all
				select '','Defined_WorkHours','','' 
				union all
				select '','LevelCode','',''	
			end
		else
			begin
				SELECT column_name+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType='All' and TA_ExportData_FieldData.DataType='SummarizedData' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = 'TA_TBL_PayrollProcessDetails' AND column_name <> 'PayrollProcess_Id'
				AND column_name <> 'MonthClosure_Id' AND column_name <> 'User_Id' AND  column_name <> 'TimeStamp'
				--AND column_name <> 'MonthClosure_Id' AND column_name <> 'User_Id'
				AND column_name <> 'Emp_Id' AND column_name <> 'HrsWork' AND column_name <> 'HrsOt' AND column_name <> 'NormOt' AND column_name <> 'WorkHrs' AND column_name <> 'HolOT' AND column_name <> 'OffOT'
				union all
				select '','Hours_Worked','','' 
				union all
				select '','Total_OT','','' 
				union all
				select '','WeekDay_OT','','' 
				union all
				select '','WeekOff_OT','','' 
				union all
				select '','Holiday_OT','','' 
				union all
				select '','Defined_WorkHours','','' 
				union all
				select '','LevelCode','',''	
			end		
	END
else
	BEGIN
		if((select DemoType from TA_Tbl_Demo)='Express')
			begin
				SELECT column_name+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType='All' and TA_ExportData_FieldData.DataType='DailyData' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = 'TA_Tbl_ProcessedData' AND column_name <> 'Process_Rec_ID' AND column_name <> 'LeaveCode'
				AND column_name <> 'Employee_Code_Id' AND column_name <> 'Shift_Id' AND  column_name <> 'Status'
				AND column_name <> 'Attendance' AND column_name <> 'EarlyOutMins' AND column_name <> 'ExtraMins' 
				AND column_name <> 'OtMins' AND column_name <> 'TotalDays' AND column_name <> 'OvertimeStatus'
				AND column_name <> 'LateEntryReason' AND column_name <> 'EarlyOutReason' AND column_name <> 'ProcessFlag'
				AND column_name <> 'LateExit' AND column_name <> 'EarlyEntry'
				AND column_name <> 'LateInMins' AND column_name <> 'HrsWork' AND column_name <> 'HrsOt' AND column_name <> 'NormOt' AND column_name <> 'WorkHrs' AND column_name <> 'HolOT' AND column_name <> 'OffOT' 
				union all
				select '','Hours_Worked','','' 				 
				union all
				select '','Defined_WorkHours','','' 
				union all
				select '','Employee_Id','','' 
				union all
				select '','EmployeeName','',''
				union all
				select '','CardNo','','' 
				union all
				select '','ShiftCode','','' 
				union all
				select '','ShiftName','','' 
				union all
				select '','DateIn','',''
				union all
				select '','DateOut','',''
				union all
				select '','InReaderId','','' 
				union all
				select '','OutReaderId','','' 
				union all
				select '','InReaderName','','' 
				union all
				select '','OutReaderName','','' 
				union all
				select '','Remarks','','' 
				union all
				select '','LevelCode','','' 
				union all
				select '','LevelName','',''				
				--union all
				--select '','AttendanceCode','','' 
			end
		else
			begin
				SELECT column_name+' ('+isnull(TA_ExportData_FieldData.UserDefinedFieldName,' ')+')' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType='All' and TA_ExportData_FieldData.DataType='DailyData' and TA_ExportData_FieldData.CompanyID=2
				WHERE Table_Name = 'TA_Tbl_ProcessedData' AND column_name <> 'Process_Rec_ID' AND column_name <> 'LeaveCode'
				AND column_name <> 'Employee_Code_Id' AND column_name <> 'Shift_Id' AND  column_name <> 'Status'
				AND column_name <> 'Attendance' AND column_name <> 'EarlyOutMins' AND column_name <> 'ExtraMins' 
				AND column_name <> 'OtMins' AND column_name <> 'TotalDays' AND column_name <> 'OvertimeStatus'
				AND column_name <> 'LateEntryReason' AND column_name <> 'EarlyOutReason' AND column_name <> 'ProcessFlag'
				AND column_name <> 'LateExit' AND column_name <> 'EarlyEntry'
				AND column_name <> 'LateInMins' AND column_name <> 'HrsWork' AND column_name <> 'HrsOt' AND column_name <> 'NormOt' AND column_name <> 'WorkHrs' AND column_name <> 'HolOT' AND column_name <> 'OffOT' 
				union all
				select '','Hours_Worked','','' 
				union all
				select '','Total_OT','','' 
				union all
				select '','WeekDay_OT','',''
				union all
				select '','WeekOff_OT','','' 
				union all
				select '','Holiday_OT','',''  
				union all
				select '','Defined_WorkHours','','' 
				union all
				select '','Employee_Id','','' 
				union all
				select '','EmployeeName','',''
				union all
				select '','CardNo','','' 
				union all
				select '','ShiftCode','','' 
				union all
				select '','ShiftName','','' 
				union all
				select '','DateIn','',''
				union all
				select '','DateOut','',''
				union all
				select '','InReaderId','','' 
				union all
				select '','OutReaderId','','' 
				union all
				select '','InReaderName','','' 
				union all
				select '','OutReaderName','','' 
				union all
				select '','Remarks','','' 
				union all
				select '','LevelCode','','' 
				union all
				select '','LevelName','',''
				union all
				select '','OverTimeType','','' 
				--union all
				--select '','AttendanceCode','','' 
			end
	END
/*
declare @TableID as int
set @TableID =(select id from sysobjects where name='TA_TBL_PayrollProcessDetails')
exec Proc_TA_SelectAllColumnNames @TableID
*/
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]
AS
Begin
declare @TableID as int
set @TableID =(select id from sysobjects where name='TA_TBL_PayrollProcessDetails')
	DECLARE @version as nvarchar(50)
		SET @version = ''
		SET @version = (SELECT left(@@version,26))
		if (@version='Microsoft SQL Server  2000')
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4 and c.Name in ('AbsentDays','Employee_Id')
--			union 
--
--			select '12345','OT_Type','OT Type'
			END
		else
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0 and c.Name in ('AbsentDays','Employee_Id')			
--				union 
--				select '12345','AttendanceCode','Attendance Code'
			END		
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]
AS
Begin
declare @TableID as int
set @TableID =(select id from sysobjects where name='TA_TBL_PayrollProcessDetails')
	DECLARE @version as nvarchar(50)
		SET @version = ''
		SET @version = (SELECT left(@@version,26))
		if (@version='Microsoft SQL Server  2000')
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4 and c.Name in ('HrsOT','Employee_Id')
--			union 
--
--			select '12345','OT_Type','OT Type'
			END
		else
			BEGIN
				SELECT o.id AS 'id',
				CAST(c.Name AS varchar(75)) AS 'ColumnName', 
				CAST(p.Value AS varchar(75)) AS 'Description' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0 and c.Name in ('HrsOT','Employee_Id')			
--				union 
--				select '12345','OT_Type','OT Type'
			END		
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	: Proc_TA_SelectPayrollMonthClosureDetails
Tables Incluced	: TA_Tbl_MonthClosure
Description	: It is used for the Payroll report to display duration Dropdown list
Date Created	: 16-Oct-07
Created By	: P.Prabakaran
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]
as
select mc.MonthClosure_Id, (Convert(varchar,mc.MonthClosure_StartDate,106) + ' - ' + Convert(varchar,mc.MonthClosure_EndDate,106) + ' [ ' + replace(ld.name,'&amp','&') + ' ]') as Duration 
from TA_Tbl_MonthClosure mc
inner join TA_Tbl_LevelDetails ld on ld.id=mc.OrgLevel_Id
where mc.IsDeleted=0
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	: Proc_TA_SelectPayrollMonthClosureDetailsByCompId
Tables Incluced	: TA_Tbl_MonthClosure
Description	: It is used to fill month closure duration for company
Date Created	: 03-jun-09
Created By	: Christopher S
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]
@companyId int
as
select mc.MonthClosure_Id, (Convert(varchar,mc.MonthClosure_StartDate,106) + ' - ' + Convert(varchar,mc.MonthClosure_EndDate,106) + ' [ ' + replace(ld.name,'&amp','&') + ' ]') as Duration 
from TA_Tbl_MonthClosure mc
inner join TA_Tbl_LevelDetails ld on ld.id=mc.OrgLevel_Id
where mc.IsDeleted=0 and mc.OrgLevel_Id=@companyId and mc.Process='P'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================          
-- Author:  Prabakaran    Proc_TA_SelectTemporaryShiftForDate '01/01/2009','174'  
-- Created  date:   
-- Description: Report Permanent Shift          
-- =============================================   
--Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate '07/07/2009','07/07/2009','483'       
CREATE PROCEDURE [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]           
(          
 @fromDate datetime,  
 @toDate datetime,
 @EmployeeId varchar(50)
)          
AS          
BEGIN          
	 create table #TempShiftData(P_FromShiftDate varchar(20),P_FromShiftId varchar(20),P_ToShiftDate varchar(20),P_ToShiftId varchar(20),T_FromShiftDate varchar(20),T_FromShiftId varchar(20),T_ToShiftDate varchar(20),T_ToShiftId varchar(20),EmployeeId varchar(30))
	 declare @sqlQuery as varchar(8000)  
	 set @sqlQuery = ''    
	 set @sqlQuery = @sqlQuery + ' insert into #TempShiftData(EmployeeId) SELECT '+ @EmployeeId +''     
	 exec(@sqlQuery)
	  set @sqlQuery = '' 
	 set @sqlQuery = @sqlQuery + ' update #TempShiftData set P_FromShiftDate = convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101),P_FromShiftId = dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift '     
	 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_PermanentShiftAllocation ' 
	 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'        
	 exec(@sqlQuery)
	 set @sqlQuery = '' 
	 set @sqlQuery = @sqlQuery + ' update #TempShiftData set P_ToShiftDate = convert(varchar,CONVERT(datetime,''' + cast(@toDate as nvarchar(50))  + ''', 101),101),P_ToShiftId = dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@toDate) as nvarchar(10)) + 'Shift '     
	 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_PermanentShiftAllocation ' 
	 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@toDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@toDate) as nvarchar(10)) + ')'        
	 exec(@sqlQuery)
	 set @sqlQuery = '' 
	 set @sqlQuery = @sqlQuery + ' update #TempShiftData set T_FromShiftDate = convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101),T_FromShiftId = dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift '     
	 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation ' 
	 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'        
	 exec(@sqlQuery)
	 set @sqlQuery = '' 
	 set @sqlQuery = @sqlQuery + ' update #TempShiftData set T_ToShiftDate = convert(varchar,CONVERT(datetime,''' + cast(@toDate as nvarchar(50))  + ''', 101),101),T_ToShiftId = dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@toDate) as nvarchar(10)) + 'Shift '     
	 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation ' 
	 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@toDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@toDate) as nvarchar(10)) + ')'        
	 exec(@sqlQuery)
	 select * from #TempShiftData
	 drop table #TempShiftData
END   
--select * from TA_Tbl_PermanentShiftAllocation
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*   
Procedure Name : Proc_TA_SelectPermanentShiftAllocationForDates  '01/01/2009','01/03/2009','3'  
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation    
Created By : Prabakaran    
Created on : 3-Aug-07      
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]    
 @fromDate datetime,    
 @toDate datetime,  
 @EmployeeId varchar(50)     
AS    
BEGIN    
  declare @sqlQuery as nvarchar(4000)    
  set @sqlQuery=''    
  create table #tblTempShiftDetails (ShiftDate datetime,ShiftId int,EmployeeId int)  
while(@fromdate <= @toDate)  
begin  
 set @sqlQuery = @sqlQuery + ' SELECT  convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId '       
  set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_PermanentShiftAllocation '   
 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'          
 set @fromdate=DateAdd(dd,1,@fromdate)  
 INSERT INTO #tblTempShiftDetails exec(@sqlQuery)  
set @sqlQuery=''    
end  
select convert(varchar,ShiftDate,101) as ShiftDate,ShiftId ,EmployeeId from #tblTempShiftDetails  
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftForDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================        
-- Author:  Prabakaran    Proc_TA_SelectPermanentShiftForDate '01/07/2009','174'
-- Created  date: 
-- Description: Report Permanent Shift        
-- =============================================        
CREATE   PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftForDate]         
(        
 @fromDate datetime,
 @EmployeeId varchar(50)    
)        
AS        
BEGIN        
  declare @sqlQuery as varchar(8000)
  set @sqlQuery = ''  
 set @sqlQuery = @sqlQuery + ' SELECT  convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_PermanentShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId '     
 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_PermanentShiftAllocation ' 
 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_PermanentShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'        
exec(@sqlQuery)
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Proc_TA_SelectPermissionDetails] 'SuperAdmin','0',21,null,null,'01/01/1900','01/01/1900',null,0
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetails]
@Employee_ID int,
@UserGroupName nvarchar(250),
@GradeLevel nvarchar(20),
@LevelRights varchar(2000), 
@Employee_Code_Id nvarchar(50) = null, 
@Employee_FirstName varchar(50) = null, 
@PermissionStartDate datetime = '01/01/1900', 
@PermissionEndDate datetime = '01/01/1900' ,
@EmpSwipeCard varchar(20),
@ParentID int 
as  
begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000) 
	declare @sql1 as varchar(8000)  
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @sql1=''
	SET @sql = ' select E.Employee_Code_Id as employeeid,e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') as Employee_FirstName,ld.name,p.Permission_Id,p.Employee_Id,
	case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, p.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, p.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end  AS Permission_AppliedDate	
	,p.Permission_Date,(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '' '', ''/'') + '' - '' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '' '', ''/'')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,p.Permission_Reason,p.Permission_Status,p.Emp_Id_Sanction,p.Remarks,p.IsDeleted,p.TimeStamp,p.Emp_Id from TA_Tbl_Permission p  '
	SET @sql = @sql + ' inner join Ta_tbl_employee e on e.Employee_Id=p.Employee_Id  '
	SET @sql = @sql + ' inner join TA_Tbl_EmployeeLevel el ON e.Employee_Id = el.EmployeeId '
	SET @sql = @sql + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
	SET @sql = @sql + ' inner JOIN TA_Tbl_EmployeeDesignation ON p.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId'
	SET @sql = @sql + ' inner JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	SET @sql = @sql + ' inner JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId  '
	set @sql = @sql + ' inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id '
	set @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=el.EffectiveDate and #EmpLevel.employeeid=el.EmployeeId '
	set @sql = @sql + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	SET @sql = @sql + ' where ys.IsActive=1 and p.IsDeleted=''0''  and e.isdeleted=''0'' '
	If(@UserGroupName<>'SuperAdmin')
		Begin
			SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level >='''+ @GradeLevel + ''' '
		End
	If not(@Employee_Code_Id = '')
		Begin
			set @sql = @sql + ' and e.Employee_Code_Id = ''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + ' and (e.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @sql = @sql + 'And e.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End 
	If not(@Employee_FirstName = '')
		Begin
			set @sql = @sql + ' and (e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''') like ''' + cast(@Employee_FirstName+'%' as nvarchar(100)) + ''')'
		End
	If not(@PermissionStartDate = '01/01/1900' and @PermissionEndDate = '01/01/1900')
		Begin
			set @sql = @sql + ' and (p.Permission_FromTime between convert(datetime,''' + cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000'', 102) and convert(datetime,''' + cast(@PermissionEndDate as nvarchar(11)) + ' 23:59:59.999'',102)'
			set @sql = @sql + ' or p.Permission_ToTime between convert(datetime,''' + cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000'', 102) and convert(datetime,''' + cast(@PermissionEndDate as nvarchar(11)) + ' 23:59:59.999'',102))'
		End
	set @sql1= @sql1 + ' Order By Permission_Id Desc '	
	execute (@sql + @sql1)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name :  Proc_TA_SelectPermissionDetailsByEmpId  
Description : Get Permisssion Details of Employees Based on their Employee_Id  
Tables Included : TA_Tbl_Permission  
Created By : Prabakaran  
Created On : 18-Jul-07  
Modified By :  
Modified On :
Proc_TA_SelectPermissionDetailsByEmpId 10899,'3','58','20120301','20120301','New - Trainee Staffs IT',0
*/  
CREATE procedure [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]  
@Employee_Id bigint,
@GradeLevel nvarchar(20),
@LevelRights varchar(8000), 
@PermissionStartDate datetime = '01/01/1900', 
@PermissionEndDate datetime = '01/01/1900',
@UserGroupName varchar(250),
@ParentID int  
as  
BEGIN
SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @CurrentDate AS NVARCHAR(30)
	DECLARE @sql AS VARCHAR(8000)
	declare @sql1 as varchar(8000)    
	SET @CurrentDate = GetDate()
	-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @sql1=''
	 SET @sql = ' select '''' as employeeid,'''' as Employee_FirstName,'''' as ''name'',TA_Tbl_Permission.Permission_Id,TA_Tbl_Permission.Employee_Id, '
	SET @sql = @sql + ' case when '+cast(@dateFormat as varchar(100))+'=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_Permission.Permission_AppliedDate,'+cast(@dateFormat as varchar(100))+'),'+''' '''+','+'''-'''+') 
	else CONVERT(VARCHAR, TA_Tbl_Permission.Permission_AppliedDate, '+cast(@dateFormat as varchar(100))+') end  AS Permission_AppliedDate
	,TA_Tbl_Permission.Permission_Date, '
	SET @sql = @sql + ' (REPLACE(CONVERT(VARCHAR(9), TA_Tbl_Permission.Permission_FromTime, 6), '' '', ''/'') + '' - '' + REPLACE(CONVERT(VARCHAR(9),TA_Tbl_Permission.Permission_ToTime, 6), '' '', ''/'')) AS Duration, '
	SET @sql = @sql + ' TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime, '
	SET @sql = @sql + ' TA_Tbl_Permission.Permission_Reason,TA_Tbl_Permission.Permission_Status,TA_Tbl_Permission.Emp_Id_Sanction, '
	SET @sql = @sql + ' TA_Tbl_Permission.Remarks,TA_Tbl_Permission.IsDeleted,TA_Tbl_Permission.TimeStamp,TA_Tbl_Permission.Emp_Id from TA_Tbl_Permission '
	SET @sql = @sql + ' inner join TA_Tbl_EmployeeLevel el ON TA_Tbl_Permission.Employee_Id = el.EmployeeId '
	SET @sql = @sql + ' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Permission.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId '
	SET @sql = @sql + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId '
	set @sql = @sql + ' inner join TA_Tbl_YearSetting ys on TA_Tbl_Permission.YearSettings_Id=ys.YearSettings_Id '
	set @sql = @sql + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=el.EffectiveDate and #EmpLevel.employeeid=el.EmployeeId '
	set @sql = @sql + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId '
	set @sql = @sql + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '
	SET @sql = @sql + ' where ys.IsActive=1 and TA_Tbl_Permission.Employee_Id=''' + cast(@Employee_Id as nvarchar(20)) + ''' and TA_Tbl_Permission.IsDeleted=0 '
	SET @sql = @sql + ' AND TA_Tbl_Grade.Grade_Level >='''+ @GradeLevel + ''' '
	If not(@PermissionStartDate = '01/01/1900' and @PermissionEndDate = '01/01/1900')
	Begin
		set @sql = @sql + ' and (TA_Tbl_Permission.Permission_FromTime between convert(datetime,''' + cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000'', 102) and convert(datetime,''' + cast(@PermissionEndDate as nvarchar(11)) + ' 23:59:59.999'',102)'
		set @sql = @sql + ' or TA_Tbl_Permission.Permission_ToTime between convert(datetime,''' + cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000'', 102) and convert(datetime,''' + cast(@PermissionEndDate as nvarchar(11)) + ' 23:59:59.999'',102))'
	End
	set @sql1= @sql1 + ' Order By Permission_Id Desc '
	exec(@sql + @sql1)  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectPermissionDetailsByPermissionId
Description		:	Get Permisssion Details of Employees Based on Permission_ID
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	20-Jul-07
Modified By		:
Modified On		:
*/
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]
	@Permission_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select * from TA_Tbl_Permission p
	inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
	inner join TA_Tbl_EmployeeLevel EL on E.Employee_Id=EL.EmployeeId
	where Permission_Id=@Permission_Id and P.IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPermissionDetailsForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectPermissionDetailsForService]
	-- Add the parameters for the stored procedure here
	@inEmployee_Code_Id varchar(50),
	@dtmDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT P.Permission_FromTime,P.Permission_ToTime,P.No_Of_Hours FROM TA_Tbl_Permission P
	inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id
	WHERE  E.SwipeCardNo= @inEmployee_Code_Id AND P.Permission_Date = @dtmDate AND P.Permission_Status='Approved' AND P.IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <27-Mar-2019 07:29 PM>
-- Description:	<Get the previously availed permission details for printout>
-- Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman 62
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]
@PermissionID bigint
AS
BEGIN
	SET NOCOUNT ON;
	SELECT AutoID, Cur_Perm_ID as Permission_Id, Prev_Perm_ID, Timestamp, Prev_Perm_date as Permission_Date, Prev_Perm_ShiftTime as Permission_FromTime, 
	Prev_Perm_InTime as No_Of_Hours , Prev_Perm_LateHours as Permission_ToTime, Prev_Perm_Reason as Permission_Reason, Prev_Perm_ReceivedDate as Permission_AppliedDate 
	from ta_tbl_PrevPermissionDetails_EastMan where Cur_Perm_ID=@PermissionID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan 787,'03/25/2019'
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]
(
	@Employee_Code_Id nvarchar(50) = null, 
	@PermissionStartDate datetime = '01/01/1900' 
)
as  
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	Declare @sql varchar(max)
	Declare @startDate datetime
	Declare @EndDate datetime
	Declare @intime varchar(20)
	Declare @lateInHours varchar(20)
	Declare @ShiftStartTime varchar(20)
	Declare @Shift_SecondHalf_StartTime datetime
	Declare @Shift_Id int
	Declare @Difference varchar(10)
	select	@startDate=DATEADD(month,DATEDIFF(MONTH,0,@PermissionStartDate),0),
			@EndDate=DATEADD(d, -1, DATEADD(month, DATEDIFF(month, 0, @PermissionStartDate)+1, 0))
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	--if the employee is absent on first session, need to take the second timing as shift in time
	IF EXISTS(SELECT Shift_Id from TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
	and Date=@PermissionStartDate and (FNAttendanceCode!='Present'))
	BEGIN
		SELECT @Shift_Id=Shift_Id
		FROM TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
		and Date=@PermissionStartDate and (FNAttendanceCode!='Present')
		select @Shift_SecondHalf_StartTime= cast(Shift_SecondHalf_StartTime as datetime) from TA_Tbl_Shift where Shift_Id =@Shift_Id and Isdeleted=0
	END
	SELECT	@intime=CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114),1,5)
							ELSE SUBSTRING(convert(varchar(20),InTime),1,5)
					END,
			@ShiftStartTime=CASE	WHEN FNAttendanceCode='Present' THEN
											CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Shift_StartTime,0)), 114),1,5)
													ELSE SUBSTRING(convert(varchar(20),Shift_StartTime),1,5)
											END			
									ELSE convert(varchar(20),@Shift_SecondHalf_StartTime)
							END,
			@lateInHours=LateIn
	FROM TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
	and Date=@PermissionStartDate and (FNAttendanceCode='Present' or ANAttendanceCode='Present')
	select @intime=@PermissionStartDate+@intime,@ShiftStartTime=@PermissionStartDate+@ShiftStartTime
	select @Difference=DATEDIFF(minute,CONVERT(datetime,@ShiftStartTime),CONVERT(datetime,@intime))
	+DATEDIFF(HOUR,CONVERT(datetime,@ShiftStartTime),CONVERT(datetime,@intime))*60
	if(@Difference<0)
	begin
		set @Difference=0
	end
	select P.Permission_Id,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, p.Permission_AppliedDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, p.Permission_AppliedDate, @dateFormat) 
	end  AS Permission_AppliedDate,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, p.Permission_Date,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, p.Permission_Date, @dateFormat) 
	end  AS Permission_Date,
	CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Permission_FromTime,0)), 114),1,5)
						ELSE SUBSTRING(convert(varchar(20),Permission_FromTime),13,5)+' ' + SUBSTRING(convert(varchar(20),Permission_FromTime),18,2) 					
				END Permission_FromTime,
	CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Permission_ToTime,0)), 114),1,5)
						ELSE SUBSTRING(convert(varchar(20),Permission_ToTime),13,5)+' ' + SUBSTRING(convert(varchar(20),Permission_ToTime),18,2) 					
				END Permission_ToTime,
	p.No_Of_Hours ,	
	p.Permission_Reason,
	p.Permission_Status,
	Isavailable=case when CONVERT(datetime,@PermissionStartDate)=CONVERT(datetime,Permission_Date) then 1 else 0 end,
	pd.InTime
	from TA_Tbl_ProcessedData pd 
	inner join Ta_tbl_employee e on e.SwipeCardNo=pd.Employee_Code_Id
	inner join TA_Tbl_Permission p on (p.Employee_Id=e.Employee_Id and p.Permission_Date=pd.Date)
	inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id
	where ys.IsActive=1 and p.IsDeleted='0'  and e.isdeleted='0'
	and e.Employee_Code_Id = cast(@Employee_Code_Id as nvarchar(50))
	and (p.Permission_FromTime between convert(datetime,cast(@startDate as nvarchar(11)) + ' 00:00:00.000', 102) and convert(datetime,cast(@EndDate as nvarchar(11)) + ' 23:59:59.999',102)
	or p.Permission_ToTime between convert(datetime, cast(@startDate as nvarchar(11)) + ' 00:00:00.000', 102) and convert(datetime,cast(@EndDate as nvarchar(11)) + ' 23:59:59.999',102))
	Order By Permission_Id Desc
	Declare @Isavailable int
	select @Isavailable=case when CONVERT(datetime,@PermissionStartDate)=CONVERT(datetime,Permission_Date) then 1 else 0 end
	from TA_Tbl_Permission p  
	inner join Ta_tbl_employee e on e.Employee_Id=p.Employee_Id  
	inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id
	where ys.IsActive=1 and p.IsDeleted='0'  and e.isdeleted='0'
	and e.Employee_Code_Id = cast(@Employee_Code_Id as nvarchar(50))
	and (p.Permission_FromTime between convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000', 102) and convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + ' 23:59:59.999',102)
	or p.Permission_ToTime between convert(datetime, cast(@PermissionStartDate as nvarchar(11)) + ' 00:00:00.000', 102) and convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + ' 23:59:59.999',102))
	Order By Permission_Id Desc
	select @Difference=isnull(@Difference,''),@Isavailable=isnull(@Isavailable,0)
	select
	ShiftStartTime=
	CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,@ShiftStartTime,0)), 114)
						ELSE SUBSTRING(@ShiftStartTime,13,5)+' ' + SUBSTRING(@ShiftStartTime,18,2) 					
				END,
				CASE	WHEN (@TIMEFORMAT)='HH:MM' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,@intime,0)), 114)
						ELSE SUBSTRING(@intime,13,5)+' ' + SUBSTRING(@intime,18,2) 					
				END intime,
	Differences=@lateInHours,
	Isavailable=@Isavailable
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPFESIPolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Select * From TA_Tbl_PF_ESIDetails

--Select * From Ta_Tbl_levelDetails

-- Proc_TA_SelectPFESIPolicy @Type='P', @Policy_Id=3
-- Deleted
CREATE Procedure [dbo].[Proc_TA_SelectPFESIPolicy]
(
	@Type CHAR(1)='',
	@Policy_Id INT=0,  
	@UserGroupName nVarchar(250)=null
)
As 

Begin
	SET NOCOUNT ON;
	IF (@Type='A')
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT PE.PFESI_Id, PE.PFESI_PolicyName,PE.PF_Employee, PE.PF_Employer, PE.ESI_Employee, PE.ESI_Employer,PE.IsDeleted,PE.Created_Date, PE.Creadted_BY, PE.EmployeeType, PE.Gender, PE.companyID,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempPFESIPolicy 
					FROM TA_Tbl_PF_ESIDetails PE
					Left Outer join Ta_Tbl_levelDetails LD on PE.companyid=LD.id
					--Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempPFESIPolicy	
					
					--Drop Table #tempPFESIPolicy	
				END
			ELSE
				BEGIN
					SELECT PE.PFESI_Id, PE.PFESI_PolicyName,PE.PF_Employee, PE.PF_Employer, PE.ESI_Employee, PE.ESI_Employer,PE.IsDeleted,PE.Created_Date, PE.Creadted_BY, PE.EmployeeType, PE.Gender, PE.companyID,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempPFESIPol1 FROM TA_Tbl_PF_ESIDetails PE
					Left Outer join Ta_Tbl_levelDetails LD on PE.companyid=LD.id
					WHERE PE.IsDeleted=0 
					--Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
				END  
		END
	ELSE IF (@Type='P')  
		BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					SELECT PE.PFESI_Id, PE.PFESI_PolicyName,PE.PF_Employee, PE.PF_Employer, PE.ESI_Employee, PE.ESI_Employer,PE.IsDeleted,PE.Created_Date, PE.Creadted_BY, PE.EmployeeType, PE.Gender, PE.companyID,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempPFESIPol2 
					FROM TA_Tbl_PF_ESIDetails PE
					Left Outer join Ta_Tbl_levelDetails LD on PE.companyid=LD.id
					where PE.PFESI_Id=@Policy_Id
					--Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempPFESIPol2	
					
					--Drop Table #tempPFESIPol2
					
				END
			ELSE
				BEGIN
					SELECT PE.PFESI_Id, PE.PFESI_PolicyName,PE.PF_Employee, PE.PF_Employer, PE.ESI_Employee, PE.ESI_Employer,PE.IsDeleted,PE.Created_Date, PE.Creadted_BY, PE.EmployeeType, PE.Gender, PE.companyID,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					1 as flag,CompanyName=isnull(LD.name,'') into #tempPFESIPol3 FROM TA_Tbl_PF_ESIDetails PE
					Left Outer join Ta_Tbl_levelDetails LD on PE.companyid=LD.id
					WHERE PE.IsDeleted=0 And PE.PFESI_Id=@Policy_Id
					--Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					--select * from #tempPFESIPol	
				END  
		END  
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****************************************************************************************/            
-- Name    : Proc_TA_SelectPolicyAllocatedEmployeeDetails
-- Desc    : To select the enties from TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : R.Manikandan
-- Date    : 25-Feb-2012
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/
CREATE PROCEDURE [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]
@EmployeeId int       
AS      
BEGIN       
	SET NOCOUNT ON;      
	if Exists(select LeavePolicy_Id from TA_Tbl_Emp_LeavePolicy where employeeid=@EmployeeId)
		begin
			select 'Exists'
		end
	else
		begin
			select 'NotExists'
		end 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPreviousLevelCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectPreviousLevelCount]
	-- Add the parameters for the stored procedure here
	@levelid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select top 1 levelID as count from TA_Tbl_Level where levelID<@levelid and isDeleted=0 order by levelID desc
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPreviousYearLeaveDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By:Manikandan.RR
-- Modified Date:12-Jul-2019 03:45 PM
-- Proc_TA_SelectPreviousYearLeaveDetails 4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectPreviousYearLeaveDetails] 
	-- Add the parameters for the stored procedure here
	@employeeId as int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LT.LeaveDescription+' ('+LT.LeaveType+')' AS [Leave Type],TA_Tbl_YearClosure.Carry_PrevYear AS [Carry Previous Year]
	FROM TA_Tbl_YearClosure
	INNER JOIN TA_Tbl_LeaveType LT ON TA_Tbl_YearClosure.LeaveTypeID = LT.LeaveType_Id
	INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearClosure.Year_SettingID = TA_Tbl_YearSetting.YearSettings_Id
	WHERE TA_Tbl_YearSetting.IsActive = 1 AND TA_Tbl_YearClosure.Employee_Id = @employeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]
(
   @SwipeCardNo nVarchar(20),
   @Date Varchar(15)
)
AS
SELECT Employee_Code_Id,[Date],InTime,OutTime FROM TA_Tbl_ProcessedData where Employee_Code_Id = @SwipeCardNo and [Date] = @Date and Attendance = 'Present'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPunchTypes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [dbo].[Proc_TA_SelectPunchTypes] 'A',0,'Superadmin'
CREATE PROCEDURE [dbo].[Proc_TA_SelectPunchTypes] 
(
	@Type CHAR,
	@PunchType_Id INT,
	@UserGroupName nVarchar(50)
)
AS
BEGIN
	SET NOCOUNT ON
	Create table #TA_Tbl_PunchTypes(PunchType_Id int,Terminal_Id int,Terminal_ReaderID nvarchar(20),
	PunchType nvarchar(50),[Value] nvarchar(50),IsDeleted nvarchar(10),flag int)
	update TA_Tbl_PunchTypes set flag=1 from TA_Tbl_PunchTypes P inner join TA_Tbl_ManualTimeEntry M 
	on
	(
		(P.Terminal_Id = M.ManualTimeEntry_InReaderID AND P.PunchType = M.ManualTimeEntry_InPunchType) OR 
		(P.Terminal_Id = M.ManualTimeEntry_OutReaderID AND P.PunchType = M.ManualTimeEntry_OutPunchType)
	)
	where isnull(flag,0)!=1
	update TA_Tbl_PunchTypes set flag=1 FROM TA_Tbl_PunchTypes P 
	inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id 
	inner join TA_Tbl_ClockDetails c 
	on
	(
		(T.Terminal_ReaderID= c.Clk_InDeviceId AND P.PunchType=c.Clk_InPunchType) OR 
		(T.Terminal_ReaderID = c.Clk_OutDeviceId AND P.PunchType =c.Clk_OutPunchType)
	)
	where isnull(flag,0)!=1
	-- Select all Punch Type Details
	IF (@Type='A')
		BEGIN
			IF(@UserGroupName = 'SuperAdmin')
				BEGIN
					--checking here
					insert into #TA_Tbl_PunchTypes				
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE CONVERT(varchar(20),T.Terminal_ReaderID) not in('787','788')
				END
			ELSE
				BEGIN
				--here also
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE P.Isdeleted = 0 and CONVERT(varchar(20),T.Terminal_ReaderID) not in('787','788')
				END
		END
	-- Select Punch Type Details based on the Punch Type Id
	IF (@Type='I')
		BEGIN
			IF(@UserGroupName = 'SuperAdmin')         
				BEGIN
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE  P.PunchType_Id = @PunchType_Id and CONVERT(varchar(20),T.Terminal_ReaderID) not in('787','788')
				END
			ELSE        
				BEGIN
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then 'True' else 'False' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE  P.PunchType_Id = @PunchType_Id AND P.Isdeleted = 0 and CONVERT(varchar(20),T.Terminal_ReaderID) not in('787','788')
				END
		END
		select * from #TA_Tbl_PunchTypes
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRawDataFormats]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectRawDataFormats]
AS
BEGIN 
	SELECT TerminalDatatype_ID,Raw_Data_Format FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- ==========================================================================================
-- Author:		R.Manikandan.
-- Create date: 20-11-2013
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in windows service
-- PROC_TA_SelectReaderBasicInfo
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
CREATE PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
		BEGIN
			DECLARE @sql VARCHAR(2000)
			DECLARE @UpdateToTimecheckFlag varchar(8000)
			DECLARE @sql2 varchar(8000)
			DECLARE @sql1 varchar(8000)
			DECLARE @ConnectionString NVARCHAR(2000)
			DECLARE @ServerName NVARCHAR(2000)
			DECLARE @DatabaseName NVARCHAR(2000)
			--Added by Manjula.P on 06-Feb-2014
			DECLARE @UserId NVARCHAR(100)
			DECLARE @Password NVARCHAR(100)
			IF((SELECT top 1 FileType FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)='RDBMS' and (SELECT top 1 BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=3)
				BEGIN
					SET @ConnectionString=(SELECT top 1 ConnectionString FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0 and FileType='RDBMS' and BrandId=3)
					--Create table To splitup the Server and database name
					--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
					IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
						BEGIN
							INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
							SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=2
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=3)
							UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=4)
							--Added by Manjula.P on 06-Feb-2014
							--select * from Ta_tbl_DeviceServerDetails			
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=5)				
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							--select * from  Ta_tbl_DeviceServerDetails
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						END			
					SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
					if not exists(select * from sys.servers where name = N''+@ServerName+'')
					begin
						EXEC sp_addlinkedserver @server=@ServerName
					end
					declare @suser_sname nvarchar(256) 
					set @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N'False',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------
					CREATE TABLE #test(exist int,TableName varchar(500))
					Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
					--Bio admin we dont tested. if we wants to test the bioadmin, just uncomment the below line and comment the next line and check the same
					--03-02-2014 06.00 PM
					--set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''tb_device'',''TB_READER'')'
					set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''TB_READER'')'
					Insert into #test exec(@sql)			
					if exists(select COUNT(*) from #test where TableName ='TB_READER')
						begin
							--Declare @sql4 varchar(8000)
							--set @sql4='select name from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.sys.columns where name=''ToTimecheck'' and object_id=(select object_id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.sys.tables where name=''TB_READER'')'
							--insert into #DeviceDetailsMovedToTimecheck exec(@sql4)
							--if not exists(select name from #DeviceDetailsMovedToTimecheck where name='ToTimecheck')
							--	begin
							--		declare @AlterQuery1 varchar(100)
							--		set @AlterQuery1='Alter table ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER add ToTimecheck bit'						
							--		Exec(@AlterQuery1)
							--		Declare @sql5 varchar(8000)
							--		set @sql5='select nReaderIdn,sName,sName,'''',getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where ToTimecheck is null'
							--		--insert into TA_Tbl_Terminal 
							--		exec(@sql5)
							--		set @UpdateToTimecheckFlag='Update ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null'
							--		exec(@UpdateToTimecheckFlag)
							--		--update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
							--		--where TerminalDatatype_ID is null							
							--	end
							--else
							--	begin							
									--Declare @sql6 varchar(8000)
									--set @sql6='select  nReaderIdn,sName,sName,'''',getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where ToTimecheck is null'
									--insert into TA_Tbl_Terminal 
									--exec(@sql6)
									set @sql2='select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0),getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where 
									convert(varchar(20),nReaderIdn) not in('
									set @sql2=@sql2+ ' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )'
									insert into TA_Tbl_Terminal exec(@sql2)	
									--set @UpdateToTimecheckFlag='Update ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null'
									--exec(@UpdateToTimecheckFlag)
									update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0 and FileType='RDBMS' and BrandId=3)
									where TerminalDatatype_ID is null	
									--select * from TA_Tbl_Terminal 
								--end					
						end
					delete from Ta_tbl_DeviceServerDetails
				END
		END
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo_New]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================
-- Author:		R.Karthikeyan.
-- Create date: 04-03-2016
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in Terminal sync
-- PROC_TA_SelectReaderBasicInfo_New
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
Create PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo_New]
	-- Add the parameters for the stored procedure here	
	--PROC_TA_SelectReaderBasicInfo_New 'Provider=SQLOLEDB.1;Data Source=angler67\SQL20141;Initial Catalog=biostar;User Id=sa;pwd=angler123;'
	@ConnString as nvarchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
			DECLARE @sql VARCHAR(2000)
			DECLARE @UpdateToTimecheckFlag varchar(8000)
			DECLARE @sql2 varchar(8000)
			DECLARE @sql1 varchar(8000)
			DECLARE @ConnectionString NVARCHAR(2000)
			DECLARE @ServerName NVARCHAR(2000)
			DECLARE @DatabaseName NVARCHAR(2000)
			--Added by Manjula.P on 06-Feb-2014
			DECLARE @UserId NVARCHAR(100)
			DECLARE @Password NVARCHAR(100)
					SET @ConnectionString=@ConnString
					--Create table To splitup the Server and database name
					--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
					IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
						BEGIN
							INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
							SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=2
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=3)
							UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=4)
							--Added by Manjula.P on 06-Feb-2014
							--select * from Ta_tbl_DeviceServerDetails			
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,';'))AS A WHERE Id=5)				
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
							--select * from  Ta_tbl_DeviceServerDetails
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),'='))AS B WHERE Id=2)
						END			
					SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
					if not exists(select * from sys.servers where name = N''+@ServerName+'')
					begin
						EXEC sp_addlinkedserver @server=@ServerName
					end
					declare @suser_sname nvarchar(256) 
					set @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N'False',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------
					CREATE TABLE #test(exist int,TableName varchar(500))
					Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
					--Bio admin we dont tested. if we wants to test the bioadmin, just uncomment the below line and comment the next line and check the same
					--03-02-2014 06.00 PM
					--set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''tb_device'',''TB_READER'')'
					set @sql='SELECT object_id,name FROM ['+ @ServerName +'].['+ @DatabaseName+'].sys.tables WHERE name in(''TB_READER'')'
					Insert into #test exec(@sql)			
					if exists(select COUNT(*) from #test where TableName ='TB_READER')
						begin
							--Declare @sql4 varchar(8000)
							--set @sql4='select name from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.sys.columns where name=''ToTimecheck'' and object_id=(select object_id from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.sys.tables where name=''TB_READER'')'
							--insert into #DeviceDetailsMovedToTimecheck exec(@sql4)
							--if not exists(select name from #DeviceDetailsMovedToTimecheck where name='ToTimecheck')
							--	begin
							--		declare @AlterQuery1 varchar(100)
							--		set @AlterQuery1='Alter table ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER add ToTimecheck bit'						
							--		Exec(@AlterQuery1)
							--		Declare @sql5 varchar(8000)
							--		set @sql5='select nReaderIdn,sName,sName,'''',getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where ToTimecheck is null'
							--		--insert into TA_Tbl_Terminal 
							--		exec(@sql5)
							--		set @UpdateToTimecheckFlag='Update ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null'
							--		exec(@UpdateToTimecheckFlag)
							--		--update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
							--		--where TerminalDatatype_ID is null							
							--	end
							--else
							--	begin							
									--Declare @sql6 varchar(8000)
									--set @sql6='select  nReaderIdn,sName,sName,'''',getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where ToTimecheck is null'
									--insert into TA_Tbl_Terminal 
									--exec(@sql6)
									set @sql2='select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0),getdate(),1,0 from ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER where 
									convert(varchar(20),nReaderIdn) not in('
									set @sql2=@sql2+ ' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )'
									insert into TA_Tbl_Terminal exec(@sql2)	
									--set @UpdateToTimecheckFlag='Update ['+ @ServerName +'].['+ @DatabaseName+'].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null'
									--exec(@UpdateToTimecheckFlag)
									update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0 and FileType='RDBMS' and BrandId=3)
									where TerminalDatatype_ID is null	
									--select * from TA_Tbl_Terminal 
								--end					
						end
					delete from Ta_tbl_DeviceServerDetails
END
--------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectReceiversForSMS]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <05-09-2016 14:46>
-- Description:	<Getting the existing Receivers Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectReceiversForSMS]
@TemplateID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
    -- Insert statements for procedure here
	select sr.Usergroupid,ug.groupName,1 Status from TA_Tbl_Usergroup ug
	inner join Ta_Tbl_SMSReceivers SR on ug.groupId=sr.Usergroupid 
	where sr.TemplateId=@TemplateID and ug.isDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReligion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 7-10-2011
-- Description:	SELECTING RELIGIONS
-- =============================================
create PROCEDURE [dbo].[Proc_TA_SelectReligion]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Religion where isDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthority]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 7-12-2011
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthority]
	-- Add the parameters for the stored procedure here
	@LeaveApplication_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=(
	select Employee_id from ta_tbl_leaveapplication where leaveapplication_id=@LeaveApplication_ID)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 7-12-2011
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]
	-- Add the parameters for the stored procedure here
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=@EmployeeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRestrictedHolidayDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectRestrictedHolidayDetails
Description		:	Get Restricted Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeaveApplication,TA_Tbl_Holiday
Created By		:	Prabakaran
Created On		:	13-Aug-07
Modified By		:
Modified On		:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectRestrictedHolidayDetails](@Employee_Id int)
AS
select la.LeaveApplication_Id,CONVERT(VARCHAR, la.Leave_ApplicationDate, 101) AS Leave_ApplicationDate,CONVERT(VARCHAR, la.Leave_FromDate,101) + ' - ' + CONVERT(VARCHAR, la.Leave_ToDate, 101) AS Duration,h.Holiday_Description,la.Status,la.Reason  from TA_Tbl_Holiday h
inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id
inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id
where ys.IsActive=1 and la.type='Restricted Holiday' and la.Employee_Id=@Employee_Id and la.Isdeleted=0
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [dbo].[Proc_TA_SelectSearchShift]  
@ShiftID as int,
@iCompanyID as int
AS
DECLARE @timeformat   varchar(10)
declare @Query as varchar(7000)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
		if(@timeformat='hh:mm tt')
			BEGIN
				set @Query = 'SELECT LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id '					
				set @Query= @Query +' WHERE  1=1 '
				if not (@ShiftID='0')
				begin
					set @Query= @Query +' and S.Shift_Id = '+ cast(@ShiftID as varchar(100))
				end
				if not (@iCompanyID='0')
				begin
					set @Query= @Query +' and S.Level_Id = '+ cast(@iCompanyID as varchar(100))
				end
				set @Query= @Query +' Union '
				set @Query = @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' WHERE S.Level_Id=0'
			END
		else
			BEGIN
				set @Query = 'SELECT  LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend, convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '    
				set @Query= @Query +' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id '							
				set @Query= @Query +' WHERE  1=1 '
				if not (@ShiftID='0')
				begin
					set @Query= @Query +' and S.Shift_Id = '+ cast(@ShiftID as varchar(100))
				end
				if not (@iCompanyID='0')
				begin
					set @Query= @Query +' and S.Level_Id = '+ cast(@iCompanyID as varchar(100))
				end
				set @Query= @Query +' Union '
				set @Query = @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' WHERE S.Level_Id=0'
			END
	exec(@Query)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShiftByShortName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_SelectSearchShiftByShortName 's','0'
CREATE PROCEDURE [dbo].[Proc_TA_SelectSearchShiftByShortName]  
@ShortName as varchar(25),
@CompanyID as int
AS
DECLARE @timeformat   varchar(10)
declare @Query as varchar(7000)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
		if(@timeformat='hh:mm tt')
			BEGIN
				set @Query = 'SELECT LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id '					
				set @Query= @Query +' WHERE upper(S.shift_ShortName) like ''' + upper(@ShortName) + '%'' '
				if (@CompanyID!=0 and @CompanyID!='')
				Begin
						set @Query= @Query +' And S.Level_Id = ' + cast(@CompanyID as varchar(100))
				End
				set @Query= @Query +' Union '
				set @Query = @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' WHERE S.Level_Id=0'
			END
		else
			BEGIN
				set @Query = 'SELECT  LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend, convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '    
				set @Query= @Query +' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id '							
				set @Query= @Query +' WHERE upper(S.shift_ShortName) like ''' + upper(@ShortName) + '%'' '
				if (@CompanyID!=0 and @CompanyID!='')
				Begin
						set @Query= @Query +' And S.Level_Id = ' + cast(@CompanyID as varchar(100))
				End
				set @Query= @Query +' Union '
				set @Query = @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ' 
				set @Query= @Query +' WHERE S.Level_Id=0'
			END
	exec(@Query)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Modified By		:	Prabakaran.P
Modified On		:	05-Feb-08
Description		:	UserGroupName Checking for Active and Inactive Records
Proc_TA_SelectShift 'superadmin','1,2,3,4,5,6,7,8,9,20,21,22,23,24,137,138,2,3,140,47,113,132,134,135,150,136,145,146,147,151,152,153,154,155,159,160,161,162,133',0
Modified by:Manikandan.R
Modified on:23-11-2016 14.58
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectShift]
(
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int
)
AS
BEGIN
	SET NOCOUNT ON
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	DECLARE @timeformat   varchar(10)
	declare @Query as varchar(7000)
	declare @CommonJoinQuery as varchar(7000)
	declare @SelectJoinQuery as varchar(7000)
	set @SelectJoinQuery ='SELECT	LD.name,
									S.Shift_Id,
									S.Shift_ShortName, 
									S.Shift_StartTime as shiftstart,
									S.Shift_EndTime as shiftend,
									S.Isdeleted,'
	set @CommonJoinQuery =' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id 
							INNER JOIN #LevelRights ON #LevelRights.LevelId = S.Level_Id
							WHERE S.Isdeleted=0'
	SELECT @timeformat=TimeFormat FROM TA_Tbl_DateandTimeFormat
	if(@timeformat='hh:mm tt')
	BEGIN
		set @Query	= @SelectJoinQuery 
		set @Query	= @Query+'S.Shift_Name + '' -'' + '' ( '' + S.Shift_StartTime + '' - '' +  S.Shift_EndTime + '' )'' as Shift_Name , 						
							S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime FROM TA_Tbl_Shift S' 
		set @Query	= @Query +@CommonJoinQuery		
		set @Query	= @Query +' Union '
		set @Query	= @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,S.Isdeleted,S.Shift_Name + '' -'' + '' ( '' + S.Shift_StartTime + '' - '' +  S.Shift_EndTime + '' )'',  S.Shift_StartTime + '' TO '' + S.Shift_EndTime as ShiftTime FROM TA_Tbl_Shift S ' 
		set @Query	= @Query +' WHERE S.Level_Id=0'	 				
	END
	else
	BEGIN
		set @Query	= @SelectJoinQuery 
		set @Query	= @Query +'	S.Shift_ShortName + '' -'' + '' ( '' + convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(S.Shift_EndTime as datetime),108) + '' )'' as Shift_Name,
								convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' + convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime
								FROM TA_Tbl_Shift S '
		set @Query	= @Query +@CommonJoinQuery		
		set @Query	= @Query +' Union '
		set @Query	= @Query + 'SELECT '''' as name,S.Shift_Id,S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,S.Isdeleted,S.Shift_ShortName + '' -'' + '' ( '' + convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(S.Shift_EndTime as datetime),108) + '' )'', 
								convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' + convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime
								FROM TA_Tbl_Shift S ' 
		set @Query	= @Query +' WHERE S.Level_Id=0'					
	END
	EXEC(@Query)
	DROP TABLE #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftAllocationDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,27-Nov-07>
-- Description:	<Description,,Select ShiftIds for the given period and selected employees>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftAllocationDetails](@Empid varchar(100),@Year varchar(100),@Month varchar(100))
AS
BEGIN
CREATE TABLE #TemShift( ShiftCount int )	
DECLARE @count int
DECLARE @sSql  nvarchar(200)
	set @sSql='SELECT COUNT(*) FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year] IN ( ' + @Year + ') and [Month] IN (' + @Month + ')  and EmployeeId IN (' + @Empid + ')'
	INSERT INTO #TemShift EXEC(@sSql)	
	set @count=(SELECT ShiftCount from #TemShift)
	IF(@count<>0)
		BEGIN
			set @sSql='SELECT * FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year] IN ( ' + @Year + ') and [Month] IN (' + @Month + ')  and EmployeeId IN (' + @Empid + ')'
			EXEC(@sSql)
		END
	ELSE
		BEGIN
			SET @sSql='SELECT  * FROM TA_Tbl_PermanentShiftAllocation WHERE [Year] IN ( ' + @Year + ') and [Month] IN (' + @Month + ')  and EmployeeId IN (' + @Empid + ')'
			EXEC(@sSql)
		END	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftAnalysisChart]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftAnalysisChart]
	-- Add the parameters for the stored procedure here
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		
		SELECT Shift_Id,Shift_Name,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName 
		from TA_Tbl_Shift where isdeleted=0 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftByCompany]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [dbo].[Proc_TA_SelectShiftByCompany]  
	@LevelID int
AS
Begin
	DECLARE @timeformat   varchar(10)
	SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat='hh:mm tt')
		begin
			SELECT Shift_Id,Shift_Name,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName 
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=0
		end
	else
		begin
			SELECT Shift_Id,Shift_Name,Shift_ShortName + ' ( ' + convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName 
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' + convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=0
		end
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by Manikandan.RR
-- Modified on 18-July-2020 04:22 PM
-- [Proc_TA_SelectShiftDetails]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftDetails]
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @timeformat   varchar(10)
	SELECT @timeformat=TimeFormat FROM dbo.Func_TA_GetDateTimeFormat()
	SELECT	LD.name,
			S.Shift_Id,
			S.Shift_Name,
			S.Shift_ShortName, 
			S.Shift_StartTime as shiftstart,
			S.Shift_EndTime as shiftend,  
			case	when @timeformat='hh:mm tt' then S.Shift_StartTime + ' TO ' + S.Shift_EndTime 
					else convert(char(5),cast(S.Shift_StartTime as datetime),108) + ' TO ' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) 
			end as ShiftTime,
			case when S.IsDeleted=1 then 'True' else 'False' end Isdeleted,
			case when ShiftType=0 then 'Function Key' else 'Free Scan' end ShiftType,
			Case when [24HrsShift]=1 then 'Yes' else 'No' end [24HrsShift],
			Shift_GraceInTime,
			Shift_GraceOutTime,
			Shift_MinTimeOT,
			Shift_MaxTimeOT,
			Shift_WorkingDay_OverTime,
			Shift_FirstHalf_StartTime,
			Shift_FirstHalf_EndTime,
			Shift_SecondHalf_StartTime,
			Shift_SecondHalf_EndTime,
			Shift_BreakStartTime1,
			Shift_BreakEndTime1,
			Shift_BreakStartTime2,
			Shift_BreakEndTime2,
			Shift_BreakStartTime3,
			Shift_BreakEndTime3,
			DefaultShift,
			CreatedDate,
			ModifiedDate,
			MaxShiftWorkHours
	FROM TA_Tbl_Shift S 
	INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id
	INNER JOIN #LevelRights ON #LevelRights.LevelId = S.Level_Id 
	Union 
	SELECT '' as name,
			S.Shift_Id,
			S.Shift_Name, 
			S.Shift_ShortName, 
			S.Shift_StartTime as shiftstart,
			S.Shift_EndTime as shiftend,  
			case	when @timeformat='hh:mm tt' then S.Shift_StartTime + ' TO ' + S.Shift_EndTime 
					else convert(char(5),cast(S.Shift_StartTime as datetime),108) + ' TO ' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) 
			end as ShiftTime,
			case when S.IsDeleted=1 then 'True' else 'False' end Isdeleted,
			case when ShiftType=0 then 'Function Key' else 'Free Scan' end ShiftType,
			Case when [24HrsShift]=1 then 'Yes' else 'No' end [24HrsShift],
			Shift_GraceInTime,
			Shift_GraceOutTime,
			Shift_MinTimeOT,
			Shift_MaxTimeOT,
			Shift_WorkingDay_OverTime,
			Shift_FirstHalf_StartTime,
			Shift_FirstHalf_EndTime,
			Shift_SecondHalf_StartTime,
			Shift_SecondHalf_EndTime,
			Shift_BreakStartTime1,
			Shift_BreakEndTime1,
			Shift_BreakStartTime2,
			Shift_BreakEndTime2,
			Shift_BreakStartTime3,
			Shift_BreakEndTime3,
			DefaultShift,
			CreatedDate,
			ModifiedDate,
			MaxShiftWorkHours
	FROM TA_Tbl_Shift S
	WHERE S.Level_Id=0	
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftForShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectShiftForShiftPattern  
Description : select shift pattern for respective company
Tables Included : TA_Tbl_ShiftPattern
Created By : Christopher.S   
Created On : 15-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftForShiftPattern] 
	-- Add the parameters for the stored procedure here
	@companyId int
AS
DECLARE @timeformat   varchar(10)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@timeformat='hh:mm tt')
		begin
			-- Insert statements for procedure here
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName  FROM TA_Tbl_Shift WHERE Isdeleted=0 AND Level_Id = @companyId
		end
	else
		begin
			SELECT Shift_Id,Shift_Name, Shift_ShortName + ' ( ' + convert(char(5),cast(Shift_StartTime as datetime),108) + ' - ' + convert(char(5),cast(Shift_EndTime as datetime),108) + ' ) ' as Shift_ShortName  FROM TA_Tbl_Shift WHERE Isdeleted=0 AND Level_Id = @companyId
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name  : Proc_TA_SelectShiftId
-- Tables Used	     : TA_Tbl_TemporaryShiftAllocation,TA_Tbl_PermanentShiftAllocation,TA_Tbl_Employee
-- Purpose                : This Procedure is used to get the Shift Id either from Temporary or Permanent Shift Allocation   
--	Proc_TA_SelectShiftId '8967661',2019,8,30
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftId] 
(
   @Employeecode VARCHAR(15),
   @year VARCHAR(5),
   @month VARCHAR(5),
   @date VARCHAR(5)
)  
AS
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)

SET @query = 'SELECT (tsa.Day'+ @date + 'Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''+ @Employeecode +''' '  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)

IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
  SET @query = 'SELECT (psa.Day'+ @date + 'Shift)  from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''' + @Employeecode +''' '  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
END

ELSE IF(@ShiftId > 0 or @ShiftId = -1)
BEGIN
   set @ShiftId = ISNULL(@ShiftId,0)
END

IF(@SHIFTID = 0)
		BEGIN
			Delete from #Temp1
			Declare @CompanyId int
			Declare @EmpAutoId int
			Declare @EmpLevelId int
			select @EmpAutoId = isnull(Employee_Id,0) from TA_Tbl_Employee where Employee_Code_Id=@Employeecode
			--checking AutoShift Employee or not
				IF Exists(SELECT AutoShiftConfigId FROM TA_Tbl_AutoShiftConfiguration WHERE EmployeeId = @EmpAutoId and (ShiftId1!=0 or ShiftId2!=0 or ShiftId3!=0 or ShiftId4!=0 or ShiftId5!=0))
				Begin				
					select @EmpLevelId = isnull(Levelid,0) from TA_Tbl_EmployeeLevel where EmployeeId = @EmpAutoId
					select @CompanyId = dbo.[Func_TA_GetParentIds](@EmpLevelId)		
					SELECT @ShiftId=Shift_Id FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@CompanyId
				End
		END

 SELECT ISNULL(@ShiftId,0)

DROP TABLE #Temp
DROP TABLE #Temp1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name  : Proc_TA_SelectShiftId_Group
-- Tables Used	   : TA_Tbl_TemporaryShiftAllocation,TA_Tbl_PermanentShiftAllocation,TA_Tbl_Employee
-- Purpose         : This Procedure is used to get the Shift Id for a group of employees either from Temporary or Permanent Shift Allocation   
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftId_Group] 
(
   @year VARCHAR(5),
   @month VARCHAR(5),
   @date VARCHAR(5),
   @xml xml
)  
AS
BEGIN 
	DECLARE @query VARCHAR(2000)   
	CREATE TABLE #Temp(EmployeeAutoId INT,ShiftID int)
	 Declare @Index int
	 Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into #Temp (EmployeeAutoId)
		  select xm.EmpID
		  from OpenXML(@Index, '/NewDataSet/Table')
		  With (EmpID Bigint 'EmpID') as xm
	  Exec sp_xml_removedocument @Index
	SET @query = 'update #Temp set #Temp.ShiftID = (tsa.Day'+ @date + 'Shift)  from TA_Tbl_TemporaryShiftAllocation tsa inner join #Temp on #Temp.EmployeeAutoId = tsa.EmployeeId where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ''  
	EXEC(@query)
	SET @query = 'update #Temp set #Temp.ShiftID = (psa.Day'+ @date + 'Shift)  from TA_Tbl_PermanentShiftAllocation psa inner join #Temp on #Temp.EmployeeAutoId = psa.EmployeeId and (#Temp.ShiftId is null or #Temp.ShiftId=0) where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ''  
	EXEC(@query)
	update #Temp set ShiftID=0 where ShiftID is null
	select EmployeeAutoId from #Temp where ShiftID=0
	DROP TABLE #Temp
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForFieldDuty] 'emp2','2013','5','3'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(15),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	-- Check Shift in Temporary Shift Allocation
	SET @query = 'SELECT (tsa.Day'+ @date + 'Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp 
				where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
				tsa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo = '''+ @Employeecode +''' '  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)
	DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = 'SELECT (psa.Day'+ @date + 'Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa,
			TA_Tbl_Employee emp where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ' and   psa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo = ''' + @Employeecode +''' '  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName ='No Shift' AND IsDeleted = 0)
				END
		END	
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, '00:00 AM' AS Shift_SecondHalf_StartTime, '00:00 AM' AS Shift_FirstHalf_EndTime, '00:00 AM' AS Shift_EndTime
			,'00:00 AM' Shift_StartTime
		END
	DROP Table #Temp	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForFieldDuty_Employee] 'Emp2,Emp5,Emp8','2013','5','14'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(max),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	-- Check Shift in Temporary Shift Allocation
	SET @query = 'SELECT (tsa.Day'+ @date + 'Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp 
				where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
				tsa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo in( '''+ @Employeecode +''' )'  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)
	Select * from #Temp
	DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = 'SELECT (psa.Day'+ @date + 'Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa,
			TA_Tbl_Employee emp where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ' and   psa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo in( ''' + @Employeecode +''' )'  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName ='No Shift' AND IsDeleted = 0)
				END
		END	
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, '00:00 AM' AS Shift_SecondHalf_StartTime, '00:00 AM' AS Shift_FirstHalf_EndTime, '00:00 AM' AS Shift_EndTime
			,'00:00 AM' Shift_StartTime
		END
	DROP Table #Temp	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForOnDuty]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Amsaveni>
-- Create date: <24/07/2013>
-- Description:	<To retrieve shift and time>
-- [Proc_TA_SelectShiftIdForOnDuty] 'VA163','2019','11','14'
-- Modified the shift name for NOS in condition by gopinath on 31Jul14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForOnDuty]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(15),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)
SET @query = 'SELECT (tsa.Day'+ @date + 'Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''+ @Employeecode +''' '  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)
IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
  SET @query = 'SELECT (psa.Day'+ @date + 'Shift)  from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''' + @Employeecode +''' '  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
END
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END	
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, '00:00 AM' AS Shift_SecondHalf_StartTime, '00:00 AM' AS Shift_FirstHalf_EndTime, '00:00 AM' AS Shift_EndTime
			,'00:00 AM' Shift_StartTime
		END
	DROP Table #Temp	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Thilakraj>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForSelectedEmployee] '3,6','2013','5','14'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(max),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000) 
	declare @query1 varchar(2000)
	DECLARE @query2 VARCHAR(2000) 
	DECLARE @query3 VARCHAR(2000) 
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	SET @query = 'SELECT (tsa.Day'+ @date + 'Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation
				   tsa
				where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
				tsa.EmployeeId in ( '+ @Employeecode +' )' 
	INSERT INTO #Temp 
	EXEC(@query)
	Select * from #Temp	
	Delete from #Temp	
	SET @query1 = 'SELECT (tsa.Day'+ @date + 'Shift) AS ShiftId from 
	TA_Tbl_PermanentShiftAllocation tsa
	where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
	tsa.EmployeeId  in( '+ @Employeecode +' )'  
	INSERT INTO #Temp
	EXEC(@query1)
	Select * from #Temp	
	Delete from #Temp
	SET @query2 = 'SELECT distinct((tsa.Day'+ @date + 'Shift)) AS ShiftId from 
	TA_Tbl_TemporaryShiftAllocation tsa
	where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
	tsa.EmployeeId  in( '+ @Employeecode +' )'
	INSERT INTO #Temp 
	EXEC(@query2)
	Select * from #Temp	
	Delete from #Temp
	SET @query3= 'SELECT  distinct((tsa.Day'+ @date + 'Shift)) AS ShiftId from 
	TA_Tbl_PermanentShiftAllocation tsa
	where tsa.[Year]= ' + @year + '  and  tsa.[Month]= ' + @month + ' and   
	tsa.EmployeeId in( '+ @Employeecode +' )'
	INSERT INTO #Temp
	EXEC(@query3)
	Select * from #Temp	
	Delete from #Temp
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	Getting Employee shift id for particulare date
-- [PROC_TA_SELECTSHIFTIDFORSERVICE] '2','2014/12/04','1'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForService]
	@EMPLOYEEAUTOID VARCHAR(50),
	@DATE datetime,
	@COMPANYID INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @QUERY VARCHAR(2000)   
	DECLARE @SHIFTID INT
	SET @SHIFTID=0
	DECLARE @ISDELETED INT
	CREATE TABLE #TEMP (SHIFTID INT)	
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)
	SET @YEAR=DATEPART(YEAR,@DATE)
	SET @MONTH=DATEPART(MONTH,@DATE)	
	-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	SET @QUERY = '	SELECT (TSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
					WHERE TSA.[YEAR]= ' + @YEAR + '  AND  TSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = '''+ @EMPLOYEEAUTOID +''' '	
	INSERT INTO #TEMP EXEC(@QUERY)
	SELECT @SHIFTID =ISNULL(SHIFTID,0) FROM #TEMP	
	DELETE FROM #TEMP
	-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	IF(@SHIFTID = 0)
		BEGIN
			SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= ' + @YEAR + '  AND  PSA.[MONTH]= ' + @MONTH + ' AND EMPLOYEEID = ''' + @EMPLOYEEAUTOID +''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SELECT @SHIFTID =ISNULL(SHIFTID,0) FROM #TEMP	
			DELETE FROM #TEMP
		END
	IF(@SHIFTID != 0)
		BEGIN			
			IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
				BEGIN
					SET @SHIFTID = ISNULL(@SHIFTID,0)			
				END
		END
	--To check current date is weekly off as per the configuration in the shift settings
	--implemented on 08-July-2022 11:14 pm by Manikandan.rr
	IF(@SHIFTID = 0)
	BEGIN		
		IF EXISTS(select WeekOffDay from dbo.Fn_CheckCurrentDayIsWeeklyOff(@COMPANYID) where WeekOffDay=DATENAME(DW,@DATE))
		BEGIN
			SET @SHIFTID = -1
		END
	END	
	-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	IF(@SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID = ISNULL(SHIFT_ID,0) FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID
			IF(@SHIFTID = 0)
				BEGIN					
					SELECT @SHIFTID =ISNULL(SHIFT_ID,0) FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0					
				END
		END
	IF(@SHIFTID > 0)
		BEGIN
			SELECT ISNULL(@SHIFTID,0)AS SHIFTID FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
		END
	ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID AS SHIFTID
		END		
	DROP TABLE #TEMP
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNameById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftNameById]
@ShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@ShiftId<>0)
	BEGIN
	  select *,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName1 From TA_Tbl_Shift WHERE Isdeleted = 0 and Shift_Id=@ShiftId
	END
	else
	BEGIN
	  select *,Shift_ShortName + ' ( ' +Shift_StartTime + ' - ' + Shift_EndTime + ' ) ' as Shift_ShortName1 From TA_Tbl_Shift WHERE Isdeleted = 0 
	END
-- 	select Shift_Id,Shift_Name From TA_Tbl_Shift WHERE Isdeleted = 0 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNotAllocated]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Proc_TA_SelectShiftNotAllocated 'day1shift',60013,2010,1    
CREATE  PROCEDURE [dbo].[Proc_TA_SelectShiftNotAllocated]    
(    
@ColName varchar(20),    
@EmpId int,    
@Year int,    
@Month int    
)    
AS    
BEGIN    
declare @ShiftCount as int    
SET @ShiftCount =(select  count(EmployeeId) as shiftCount  from TA_Tbl_PermanentShiftAllocation where ( @ColName  <> '0'  or  @ColName is null) and EmployeeId=@Empid and [Month]=@Month and [Year]=@Year )    
if(@ShiftCount<=0)    
BEGIN    
SET @ShiftCount =(select  count(EmployeeId) as shiftCount  from TA_Tbl_TemporaryShiftAllocation where ( @ColName  <> '0'  or  @ColName is null) and EmployeeId=@Empid and [Month]=@Month and [Year]=@Year )    
END    
select @ShiftCount    
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_SelectShiftPattern]  
@UserGroupName nvarchar(250),
@UserLevels nvarchar(2000),
@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(8000)
BEGIN
	--set @Query = 'SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id in ( '+ @UserLevels +' )'
	set @Query = 'SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id in (select * from #LevelRights)'
	exec (@Query)
	drop table #LevelRights
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]  
	@ShiftPatternID INT  
	AS  
	BEGIN  
	 SET NOCOUNT ON;  
	create table #TABLE  
	(  
	id INT,  
	name nvarchar(255)  
	)  
	DECLARE @Count INT  
	DECLARE @iLoop INT  
	DECLARE @Query NVARCHAR(4000)  
	DECLARE @Query1 NVARCHAR(4000)  
	SET @iLoop = 1  
	SET @Count= (SELECT Shift_days FROM TA_Tbl_Shiftpattern WHERE ShiftPattern_Id=@ShiftPatternID)   
	SET @Query = ''  
	WHILE (@iLoop <= @Count)  
	 BEGIN  
		Declare @test varchar(1000)  
	  SET @test = 'SELECT count(dbo.TA_Tbl_ShiftPattern.Day'+ cast(@iLoop as VARCHAR) +'_Shift)'  
	  set @test = @test + ' FROM         dbo.TA_Tbl_ShiftPattern INNER JOIN '  
	  set @test = @test + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_ShiftPattern.Day' +  cast(@iLoop as VARCHAR)  + '_shift = dbo.TA_Tbl_Shift.Shift_Id '  
	  set @test = @test + ' WHERE     (dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id = ' + cast(@ShiftPatternID as VARCHAR) + ')'  
				create table #temp1 
				(
				rows int
				)  
				insert into #temp1 exec(@test) 
				declare @count1 int
				set @count1=(select * from #temp1)
				drop table #temp1
		if (@count1=0)
			begin
				insert into #TABLE values(-1,'Off')
			end   
		else
			begin	 
				  SET @Query = 'SELECT dbo.TA_Tbl_ShiftPattern.Day'+ cast(@iLoop as VARCHAR) +'_Shift,'  
				  set @Query = @Query + ' dbo.TA_Tbl_Shift.Shift_ShortName '  
				  set @Query = @Query + ' FROM         dbo.TA_Tbl_ShiftPattern INNER JOIN '  
				  set @Query = @Query + ' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_ShiftPattern.Day' +  cast(@iLoop as VARCHAR)  + '_shift = dbo.TA_Tbl_Shift.Shift_Id '  
				  set @Query = @Query + ' WHERE     (dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id = ' + cast(@ShiftPatternID as VARCHAR) + ')'  
				  Insert  into #TABLE exec(@Query)  
			end
	  set @iLoop = @iLoop + 1  
	 END  
	Select * From #TABLE  
	END  
drop table #TABLE  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternDetails]
(
@type CHAR(1),
@ShiftPatternId INT=0
)
AS
DECLARE @del BIT
SET @del=1
--selecting all Shift Pattern
IF @type='A'
BEGIN
	SELECT * FROM TA_Tbl_ShiftPattern WHERE IsDeleted=@del
END
--selecting Shift Pattern based on id
ELSE IF @type='P'
BEGIN
	SELECT * FROM TA_Tbl_ShiftPattern WHERE IsDeleted=@del AND ShiftPattern_Id=@ShiftPatternId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectShiftPatternForShiftAllocation  
Description : select shift pattern for respective company
Tables Included : TA_Tbl_ShiftPattern
Created By : Christopher.S   
Created On : 13-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]
	-- Add the parameters for the stored procedure here
	@companyId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ShiftPattern_Id,Pattern_Name,Shift_days,Isdeleted FROM TA_Tbl_ShiftPattern WHERE Isdeleted = 0 and Level_Id = @companyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]
	-- Add the parameters for the stored procedure here
	@companyId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id = @companyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternId]
 AS
  BEGIN
	 SELECT ShiftPattern_Id FROM TA_Tbl_ShiftPattern WHERE Isdeleted=1 				
  END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRequisitionMonth]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_SelectShiftRequisitionMonth]

AS
BEGIN
	declare @staetdate nvarchar(100)
declare @Enddate nvarchar(100)


select @staetdate = '1-'+StartMonth+'-'+ convert(char(10),StartYear) from TA_Tbl_YearSetting where IsActive = 1
select  @Enddate =  '1-' + EndMonth +'-' + convert(char(10),EndYear) from TA_Tbl_YearSetting where IsActive = 1

Create table #tempdate(ROWID int identity(1,1),MonthName varchar(100),MonthYear varchar(100))


declare @start DATE = @staetdate
declare @end DATE = @Enddate
declare @MonthName nvarchar(100)
declare @MonthYear nvarchar(100)
;with months (date)
AS
(
    SELECT @start
    UNION ALL
    SELECT DATEADD(month, 1, date)
    from months
    where DATEADD(month, 1, date) <= @end
)
insert into #tempdate
select     MonthName    = Convert(CHAR(3),DATENAME(mm, date),120) ,
           MonthYear    = DATEPART(yy, date) 
		   
from months


--select * from #tempdate
select  ROWID,MonthName+'-'+ Convert(char(10), MonthYear) as MonYear from #tempdate

drop table #tempdate

--print @staetdate
--print @Enddate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRoaster]  
@usergroupname nvarchar(250),
@UserLevels nvarchar(2000),
@ParentId int
    AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@usergroupname,@ParentID) as LevelId 
DECLARE @Isdel int
declare @Query as varchar(7000)
SET @Isdel=0
if(@usergroupname='SuperAdmin')
	BEGIN
		--set @Query = 'SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id WHERE SR.Isdeleted='+cast(@Isdel as nvarchar(5))+' and SR.Level_Id in ( '+ @UserLevels +' )'
		set @Query = 'SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id WHERE SR.Isdeleted='+cast(@Isdel as nvarchar(5))+''
	END
else
	BEGIN
		--set @Query = 'SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id WHERE SR.Isdeleted='+cast(@Isdel as nvarchar(5))+' and SR.Level_Id in ( '+ @UserLevels +' )'
		set @Query = 'SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id WHERE SR.Isdeleted='+cast(@Isdel as nvarchar(5))+''
	END
             exec(@Query)
drop table #LevelRights
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoasterById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRoasterById]
(@RoasterId int)
 AS
	BEGIN
		SELECT TA_Tbl_ShiftRoaster.*,TA_Tbl_Leveldetails.Name  
		FROM TA_Tbl_ShiftRoaster INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_ShiftRoaster.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE TA_Tbl_ShiftRoaster.ShiftRoaster_Id=@RoasterId and TA_Tbl_ShiftRoaster.IsDeleted=0
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectShiftRosterForShiftAllocation  
Description : select shift roster for respective company
Tables Included : TA_Tbl_ShiftRoaster
Created By : Christopher.S   
Created On : 13-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]
	-- Add the parameters for the stored procedure here
	@companyId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT *  FROM TA_Tbl_ShiftRoaster WHERE Isdeleted = 0 and Level_Id = @companyId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftShortNameGet]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_SelectShiftShortNameGet]
@companyId int	= 1
AS
BEGIN
	
	select Shift_Id,Shift_ShortName from TA_Tbl_Shift where Level_Id = @companyId 

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSGateWayDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016>
-- Description:	<Getting SMS Gateway Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSGateWayDetails]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT id,ServiceUrl,DestinationKey,MessageKey,PhNo,TimeStamp from ta_tbl_SMSGateway
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSLogDeatils]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSLogDeatils]
	-- Add the parameters for the stored procedure here
	@templateId int, 
	@fromDate datetime, 
	@toDate datetime, 
	@status int, 
	@receivers varchar(max), 
	@parentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from ta_tbl_smstemplates
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSTemplateDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan>
-- Create date: <27-08-2016>
-- Description:	<Get the SMS Template details using TemplateID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSTemplateDetails]
	-- Add the parameters for the stored procedure here
	@TemplateId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)	
	DECLARE @TimeFormat as nvarchar(25)	
	select @TimeFormat=TimeFormat,@date=DateFormat from TA_Tbl_DateandTimeFormat
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
    -- Insert statements for procedure here
	if @templateid!=0
	begin
		Create table #UsergroupIDs(id int identity(1,1),ids int)
		insert into #UsergroupIDs 
		select Usergroupid from Ta_Tbl_SMSReceivers where TemplateId=@TemplateId
		Declare @i int
		Declare @count int
		Declare @usergroupid int
		Declare @Receivers varchar(max)
		set @Receivers=''
		set @count=(select COUNT(*) from #UsergroupIDs)
		set @i=1
		while @count>=@i
		begin
			select @usergroupid=ids from #UsergroupIDs where id=@i			
			if @Receivers!=''
			begin
				set @Receivers=@Receivers+';'+(select groupName from TA_Tbl_Usergroup where groupId=@usergroupid)
			end
			else
			begin
				set @Receivers=(select groupName from TA_Tbl_Usergroup where groupId=@usergroupid)
			end
			set @i=@i+1
		end	
		SELECT ST.id as Templateid,TemplateName,Message as Message,case when Status=1 then 'Enabled' else 'Disabled' end as status,LastModified,ModifiedBy,
		First_TriggeringTime,Second_TriggeringTime,ToEmployee,LessHrsLimitation,Continue_AbsentDays,@Receivers as Receivers,STF.Filters,STF.ReportType,Tags 
		from Ta_Tbl_SMSTemplates ST
		left outer join Ta_tbl_SMSTemplateFilters STF on ST.id=STF.TemplateId
		where ST.id=@TemplateId
	end
	else
	begin
		SELECT id as Templateid,TemplateName,Message+' '+ Tags as Message,case when Status=1 then 'Enabled' else 'Disabled' end as status,
		case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, LastModified,@dateFormat),' ','-') 
	else CONVERT(VARCHAR, LastModified, @dateFormat) end 
	+' '+	
	case	when convert(varchar(20),@TimeFormat)='hh:mm' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,LastModified,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),LastModified),13,2),' ',''))=1 then '0'+ replace(substring(CONVERT(varchar(20),LastModified),12,6),' ','')
					else substring(CONVERT(varchar(20),LastModified),12,6) end
			+' ' + substring(CONVERT(varchar(20),LastModified),18,2)
	end LastModified,ModifiedBy,First_TriggeringTime,Second_TriggeringTime,ToEmployee,LessHrsLimitation,Continue_AbsentDays,''as Receivers 
	,'' as Filters,'' ReportType,Tags
	from Ta_Tbl_SMSTemplates 
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpellCountByLeaveType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_SelectSpellCountByLeaveType 202, 52
Description		:	Select Spell count of Leave applications based on leaveTypeId and EmployeeAutoId
Tables Included	:	TA_Tbl_LeaveApplication
Created By		:	Prabakaran
Created On		:	11-Aug-07
Modified By		:
Modified On		:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectSpellCountByLeaveType] 
@Employee_Id int,
@leaveType_Id int
AS
BEGIN
	SET NOCOUNT ON;
	select isnull(Count(la.NumberOfDays),0) as SpellCount from TA_Tbl_LeaveApplication la
	inner join Ta_Tbl_yearsetting ys on (la.Leave_FromDate between ys.FromDate and ys.ToDate) and ys.YearSettings_Id=la.YearSettings_Id
	Where la.Employee_Id=@Employee_Id and la.leaveType_Id=@leaveType_Id and la.Status!='Rejected' and la.Type='Leave' and la.Isdeleted=0
	and ys.IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpouseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectSpouseDetails]
(
@empID INT
)
AS
BEGIN
	SELECT ChildEmp_ID,Emp_ID,Name,CONVERT(NVARCHAR,DOB,101) AS DOB FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID=@empID AND Spouse_Child='S' AND Isdeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSuccessiveDates]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--	Modified by		:	Manjula.P
--	Modified On		:	21-Apr-2014
--	Descriptinos	:	Changing select 0 as NoOfSuccessiveDaysInYear from select 0 to avoiding invalid column NoOfSuccessiveDaysInYear error
--Proc_TA_SelectSuccessiveDates 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectSuccessiveDates]
	@levelId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if exists (select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@levelId)
	BEGIN
		select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@levelId
	END
	else if exists(select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=-1)
	BEGIN 
		select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=-1
	END
	else
	BEGIN
	   select 0 as NoOfSuccessiveDaysInYear
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSwipesHandling]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectSwipesHandling '1','','',0,0,'01/01/2019','05/31/2019','All','All','1','','superadmin',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectSwipesHandling]
	@Employee_ID int,
	@EmployeeID as varchar(100),
	@EmployeeName as varchar(100),
	@employeeCategory as int,
	@employeeType as int,
	@FromDate as datetime,
	@ToDate as datetime,
	@SwipesType as varchar(15), 
	@VoidUnVoid as varchar(15),
	@LevelID as varchar(8000),
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
    @ParentID int  
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	--Temporary table's creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	CREATE TABLE #TempClockDetails
	(
		[CLK_ID] [bigint],
		[CLK_CARDID] [nvarchar](20) NULL,
		[CLK_DEVICEID] [nvarchar](20) NULL,
		[CLK_DATE] [datetime] NULL,
		[CLK_TIME] [nvarchar](25) NULL,			
		[ReasonId] [int] NULL,
		employee_code_id varchar(50)
	)
	Declare @DynamicSQL varchar(max)
	set @DynamicSQL=''
	set @DynamicSQL=@DynamicSQL+'insert into #TempClockDetails
	select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME,ReasonId,e.Employee_Code_Id
	from TA_Tbl_Clk_RawData CR
	inner join TA_Tbl_Employee E on CR.CLK_CARDID=E.SwipeCardNo
	inner join #EmpLevel el on el.employeeid=e.employee_id
	where CLK_DATE between'''+CONVERT(varchar(20),@FromDate)+'''and'''+CONVERT(varchar(20),@ToDate)+''''
	if(@VoidUnVoid='Void')
	begin
		set @DynamicSQL=@DynamicSQL+ ' and isnull(ReasonId,0)=6'
	end
	else if(@VoidUnVoid='un-Void')
	begin
		set @DynamicSQL=@DynamicSQL+ ' and isnull(ReasonId,0)=0'
	end
	else
	begin
		set @DynamicSQL=@DynamicSQL+ ' and isnull(ReasonId,0) in(6,0)'
	end
	Execute(@DynamicSQL)
	Declare @SelectSQL As Varchar(6000)      
	Set @EmployeeName = @EmployeeName + '%'      
	Set @SelectSQL = ' '        
	
	Set @SelectSQL = @SelectSQL + 'SELECT	CD.Clk_ID,
											ED.employee_code_id AS EmployeeCode,
											ED.Employee_FirstName + '' '' + isnull(ED.Employee_LastName,'''') AS ''EmpName'',
											CONVERT(VARCHAR,CD.CLK_DATE,'+ cast(@dateFormat as varchar(100)) +') as InDate,
											Convert(varchar(10),CD.CLK_TIME,108) as InTime,
											case when ReasonId=6 then ''True'' else ''False'' end as IsVoid,
											'''' as ClockDate,
											'''' as OutDate,
											'''' as OutTime
											'
	Set @SelectSQL = @SelectSQL + ' FROM TA_Tbl_Employee ED '      
	Set @SelectSQL = @SelectSQL + ' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.CLK_CARDID'	
	set @SelectSQL = @SelectSQL + ' Inner join #EmpLevel on  #EmpLevel.employeeid=ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'
	set @SelectSQL = @SelectSQL + ' Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id '
	set @SelectSQL = @SelectSQL + ' Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id '
	Set @SelectSQL = @SelectSQL + ' Where  ED.IsDeleted = ''0'' and ED.report_exclude=0 and ED.employee_status=1 
	and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '' '' + cast(ED.Employee_MiddleName as varchar(50)) 
	else '' '' end + isnull(ED.Employee_LastName,'''') like ''' + @EmployeeName + ''' '  
	If Not (@EmployeeId = '')      
		Begin      
			Set @SelectSQL = @SelectSQL + 'And ED.employee_code_id = ''' + @EmployeeId + ''' '      
		End      	      
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + ' and (ED.Employee_ID IN (select * from #EmployeeIds)) '  
            END
	If Not (@EmpSwipeCard = '')  
		Begin  
			Set @SelectSQL = @SelectSQL + ' And ED.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
		End
	if(@employeeCategory<>0 and @employeeCategory<>'')
		begin
			set @SelectSQL = @SelectSQL + ' And #EmpCategory.CategoryId = ' + cast(@employeeCategory as nvarchar) 
		end
	if(@employeeType<>0 and @employeeType<>'')
		begin
			set @SelectSQL = @SelectSQL + ' And #EmpType.TypeId = ' + cast(@employeeType as nvarchar) 
		end     
	--if (@VoidUnVoid='Void')
	--	Begin
	--		set @SelectSQL = @SelectSQL + ' And CD.ReasonId=6'
	--	End
	--if (@VoidUnVoid='Un-Void')
	--	Begin
	--		set @SelectSQL = @SelectSQL + '  And CD.ReasonId=0'
	--	End
	Exec (@SelectSQL)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_SelectTATblLicenseInfo  
Description : Selects license from protection table
Tables Included : TA_Tbl_LIC_Details
Created By : Christopher S  
Created On : 21-Mar-08  
Modified By :  
Modified On :  
*/  
-- Exec Proc_TA_SelectTA_Tbl_LIC_Details 'eDTwx5/xztpwt0pKDW+e2U7v3kW7I4RJbqPxV1Q5xEA='
CREATE PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_LIC_Details
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_SelectTATblLicenseInfo  
Description : Selects license from protection table
Tables Included : TA_Tbl_LIC_Details
Created By : Christopher S  
Created On : 21-Mar-08  
Modified By :  
Modified On :  
*/  
-- Exec Proc_TA_SelectTA_Tbl_LIC_Details 'eDTwx5/xztpwt0pKDW+e2U7v3kW7I4RJbqPxV1Q5xEA='
CREATE PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]
@macAddress nvarchar(200)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_LIC_Details where MACAddress = @macAddress
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Service]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create  PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Service]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_LIC_Details
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-09-2016 17:14>
-- Description:	<Getting Tag Details Using Template>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from ta_tbl_SMSTags where TemplateName=@TemplateName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <19-09-2016>
-- Description:	<Getting Template and Gateway details for SMS triggering>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF EXISTS(SELECT ServiceUrl FROM TA_TBL_SMSGATEWAY)
	BEGIN
		SELECT * FROM Ta_Tbl_SMSGateway
		SELECT * FROM Ta_Tbl_SMSTemplates WHERE TemplateName in('Late Entry','Early Exit','Less Hours Worked','Absent - Single Day','Continuous Absent','Leave Application - Apply', 'Leave Application - Forward', 'Leave Application - Approved', 'Permission Application - Apply', 'Permission Application - Forward','Permission Application - Approved', 'OnDuty - Apply', 'OnDuty - Forward', 'OnDuty - Approved')
		and status=1		
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateFilterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTemplateFilterDetails]	
	-- Add the parameters for the stored procedure here
	@Templateid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
	-- Insert statements for procedure here
	Declare @Filters varchar(max)
	Declare @Count int
	Declare @start int
	Declare @TempTable varchar(max)
	Declare @TempTableInsert varchar(max)
	Declare @TempFiltersvalue varchar(max)
	Declare @TempFiltersvalues varchar(max)
	if exists(select Filters  from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid)
	begin
	set @TempTable='Create Table TempSMSFinalFilters('
	set @TempTableInsert='Insert into TempSMSFinalFilters values('
	set @start=1
	select @Filters=Filters  from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid
	select @Count=COUNT(*) from dbo.Split(@Filters,',')
	Create table #TempSMSFilters(id int identity(1,1),Filters varchar(max))
	insert into #TempSMSFilters select Value from dbo.Split(@Filters,',')
	--select * from #TempFilters
	while @start<=@Count 
	begin
		select @TempFiltersvalue=replace(substring(Filters,0,charindex('=',Filters)),'@',''),
		@TempFiltersvalues=replace(substring(Filters,charindex('=',Filters)+1,LEN(Filters)),'~',',')
		from #TempSMSFilters where id=@start 
		if(@start!=@Count)
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max),'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''','
		end
	else
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+' varchar(max)'
			set @TempTableInsert=@TempTableInsert+''''+@TempFiltersvalues+''''
		end			
		set @start=@start+1
	end
	set @TempTable=@TempTable+')'
	set @TempTableInsert=@TempTableInsert+')'	
	Execute(@TempTable)
	Execute(@TempTableInsert)
	select * from TempSMSFinalFilters
	Select ReportType from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid
	drop table TempSMSFinalFilters
	end
	else
	begin
		Create table #TempFinalSMSFilters(id int identity(1,1))
		select * from #TempFinalSMSFilters
		Select 1 as ReportType 
		drop table #TempFinalSMSFilters
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectTemporarayShiftAllocationForDates  '01/01/2009','01/03/2009','3'
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07    
*/  
CREATE     PROCEDURE [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]  
 @fromDate datetime,  
 @toDate datetime,
 @EmployeeId varchar(50)   
AS  
BEGIN  
  declare @sqlQuery as nvarchar(4000)  
  set @sqlQuery=''  
  create table #tblShiftDetails (ShiftDate datetime,ShiftId int,EmployeeId int)
while(@fromdate <= @toDate)
begin
	set @sqlQuery = @sqlQuery + ' SELECT  convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId '     
 	set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation ' 
	set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'        
	set @fromdate=DateAdd(dd,1,@fromdate)
	INSERT INTO #tblShiftDetails exec(@sqlQuery)
set @sqlQuery=''  
end
select convert(varchar,ShiftDate,101) as ShiftDate,ShiftId ,EmployeeId from #tblShiftDetails
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftForDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================          
-- Author:  Prabakaran    Proc_TA_SelectTemporaryShiftForDate '01/01/2009','174'  
-- Created  date:   
-- Description: Report Permanent Shift          
-- =============================================          
CREATE   PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftForDate]           
(          
 @fromDate datetime,  
 @EmployeeId varchar(50)
)          
AS          
BEGIN          
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''    
 set @sqlQuery = @sqlQuery + ' SELECT  convert(varchar,CONVERT(datetime,''' + cast(@fromDate as nvarchar(50))  + ''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_TemporaryShiftAllocation.Day' + cast (day(@fromDate) as nvarchar(10)) + 'Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId '       
 set @sqlQuery = @sqlQuery + ' FROM dbo.TA_Tbl_TemporaryShiftAllocation '   
 set @sqlQuery = @sqlQuery + ' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId=' + @EmployeeId + ' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year =' + cast (year(@fromDate) as nvarchar(10)) + ') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = ' + cast (month(@fromDate) as nvarchar(10)) + ')'          
exec(@sqlQuery)  
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftId] (@Employeecode varchar(15),@year varchar(5) ,@month varchar(5),@date varchar(2))
AS
DECLARE @Ssql NVARCHAR(2000)
SET @Ssql='SELECT (psa.Day'+ @date + 'Shift)  from TA_Tbl_TemporaryShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= ' + @year + '  and  psa.[Month]= ' + @month + ' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''' + @Employeecode +''' '
EXEC(@Ssql)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTempPayrollDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Procedure Name : Proc_TA_SelectTempPayrollDetails 9,'',''
-- Purpose        : Used to select the payroll details from temporary table
-- Author         : Kumuthini.L
-- Created Date   : 18-May-09
CREATE PROCEDURE [dbo].[Proc_TA_SelectTempPayrollDetails]
(
   @MonthClosure_Id int,
   @EmpId Varchar(25),
   @EmployeeName Varchar(50)
)
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @Query AS VARCHAR(2000)
  SET @Query = ''
  SET @Query = @Query + 'SELECT E.Employee_Code_Id,ISNULL(E.Employee_FirstName,'''') + Space(1) + ISNULL(E.Employee_LastName,'''') AS ''EmployeeName'',TPD.HrsWork,TPD.NormOT,TPD.OffOT,TPD.HolOT,TPD.LateIn,TPD.EarlyOut,TPD.PresentDays,TPD.LeaveDays,TPD.Holidays,TPD.AbsentDays,TPD.LOPDays,TPD.TotalPermissionHours FROM TA_Tbl_TempPayrollProcessDetails TPD '  
  SET @Query = @Query + 'INNER JOIN TA_Tbl_Employee E ON TPD.Employee_Id = E.SwipeCardNo ' 
  SET @Query = @Query + 'WHERE TPD.MonthClosure_Id = ''' + CAST(@MonthClosure_Id AS NVARCHAR(50)) + ''' '        
  IF NOT(@EmpId = '')		
  BEGIN
     SET @Query = @Query + 'AND E.Employee_Code_Id = ''' + CAST(@EmpId AS NVARCHAR(50)) + ''' '
  END
  IF NOT(@EmployeeName = '')		
  BEGIN
     SET @Query = @Query + 'AND E.Employee_FirstName LIKE ''' + CAST(@EmployeeName+'%' AS NVARCHAR(100)) + ''' '
  END
  EXEC(@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDatatype]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDatatype] 
(
	@type CHAR(1),
	@TerminalDatatypeId INT=0,
	@UserGroupName nVarchar(100)
)
AS
BEGIN
	Declare @Common varchar(max)
	set @Common='SELECT	TerminalDatatype_ID, Raw_Data_Format, FileType, File_SourcePath, File_BackupPath, File_BackupType, Delimiter_NoOfFields, Delimiter_Delimiter, 
				Delimiter_StringEnclosedBy, Delimiter_ReaderNo, Delimiter_CardNo, Delimiter_DateTimeBit, Delimiter_Date, Delimiter_Time, Delimiter_DateTime, 
				Delimiter_Type, Delimiter_TransactionIdentifier, FixedLength_ReaderNoFrom, FixedLength_ReaderNoTo, FixedLength_CardNoFrom, FixedLength_CardNoTo, 
				FixedLength_DateTimeBit, FixedLength_DateFrom, FixedLength_DateTo, FixedLength_TimeFrom, FixedLength_TimeTo, FixedLength_DateTimeFrom, 
				FixedLength_DateTimeTo, FixedLength_TypeFrom, FixedLength_TypeTo, FixedLength_TransactionIdentifierFrom, FixedLength_TransactionIdentifierTo, 
				ConnectionString, TableName, MDB_ReaderNo, MDB_CardNo, MDB_DateTimeBit, MDB_Date, MDB_Time, MDB_DateTime, MDB_Type, MDB_TransactionIdentifier, 
				RDBMS_ReaderNo, RDBMS_CardNo, RDBMS_DateTimeBit, RDBMS_Date, RDBMS_Time, RDBMS_DateTime, RDBMS_Type, RDBMS_TransactionIdentifier, RDBMS_MDB_Flag, 
				IsEmployeeId, DateTimeFormat, DateFormat, TimeFormat, IsEncrypted, TransactionIdentifierBit, TransactionIdentifierValue, Emp_Id, TimeStamp,
				case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted , isnull(IsFreeScan,0)IsFreeScan,ISUTCTime'
	IF @type='A'
	BEGIN
		IF(@UserGroupName = 'SuperAdmin') 
		BEGIN
			set @Common=@Common+ ' ,BrandId FROM TA_tbl_TerminalDatatype '
		END 
		ELSE 
		BEGIN
			set @Common=@Common+ ' ,BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted = 0'
		END 
	END
	ELSE IF @type='P'
	BEGIN
		IF(@UserGroupName = 'SuperAdmin') 
		BEGIN
			set @Common=@Common+ ' ,TA_Tbl_TerminalBrand.DisplayName FROM TA_tbl_TerminalDatatype
			inner join TA_Tbl_TerminalBrand on TA_Tbl_TerminalBrand.BrandId=TA_tbl_TerminalDatatype.BrandId
			WHERE TerminalDatatype_ID='+convert(varchar,@TerminalDatatypeId)
		END 
		ELSE 
		BEGIN
			set @Common=@Common+ ',TA_Tbl_TerminalBrand.DisplayName 
			FROM TA_tbl_TerminalDatatype 
			inner join TA_Tbl_TerminalBrand on TA_Tbl_TerminalBrand.BrandId=TA_tbl_TerminalDatatype.BrandId
			WHERE IsDeleted = 0 AND TerminalDatatype_ID='+convert(varchar,@TerminalDatatypeId)
		END
	END
	Execute(@Common)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails] 
(  
	@Type CHAR(1),  
	@TerminalID INT=0,  
	@UserGroupName nVarchar(50)
)  
AS
BEGIN
	DECLARE @dynamicquery VARCHAR(MAX)
	IF(@Type='A')  
	BEGIN
		set @dynamicquery='
			SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,
			case when T.IsDeleted=1 then ''True'' else ''False'' end IsDeleted
			FROM TA_Tbl_Terminal T LEFT OUTER JOIN TA_tbl_TerminalDatatype TD ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
			Where Terminal_ReaderID not in(''787'',''788'')'
		IF(@UserGroupName = 'SuperAdmin')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN
			Execute(@dynamicquery+ ' and T.IsDeleted=0')
		END
	END    
	IF(@Type='P')  
	BEGIN
		set @dynamicquery='SELECT Terminal_Id, Terminal_ReaderID, Terminal_Name, Terminal_Description, TerminalDatatype_ID, Time_Stamp, Emp_ID, 
			case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted  FROM TA_Tbl_Terminal Where Terminal_ReaderID not in(''787'',''788'')
			and Terminal_Id ='+convert(varchar(20),@TerminalID)
		IF(@UserGroupName = 'SuperAdmin')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN   
			Execute(@dynamicquery + ' AND IsDeleted=0')
		END
	END
	IF(@Type='C')  
	BEGIN   
		Select Count(TerminalDatatype_ID) as TerminalCount from TA_Tbl_Terminal Where TerminalDatatype_ID =@TerminalID  and Terminal_ReaderID not in('787','788')
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails_CMITech]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails_CMITech] 
AS
BEGIN
			SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,
			case when T.IsDeleted=1 then 'True' else 'False' end IsDeleted
			FROM TA_Tbl_Terminal T LEFT OUTER JOIN TA_tbl_TerminalDatatype TD ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
			Where Terminal_ReaderID not in('787','788')
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails_SyncService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails_SyncService] 
(  
	@Type CHAR(1),  
	@TerminalID INT=0,  
	@UserGroupName nVarchar(50)
)  
AS
BEGIN
	DECLARE @dynamicquery VARCHAR(MAX)
	IF(@Type='A')  
	BEGIN
		set @dynamicquery='
			SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,
			case when T.IsDeleted=1 then ''True'' else ''False'' end IsDeleted
			FROM TA_Tbl_Terminal T LEFT OUTER JOIN TA_tbl_TerminalDatatype TD ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
			Where Terminal_ReaderID not in(''787'',''788'')'
		IF(@UserGroupName = 'SuperAdmin')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN
			Execute(@dynamicquery+ ' and T.IsDeleted=0')
		END
	END    
	IF(@Type='P')  
	BEGIN
		set @dynamicquery='SELECT Terminal_Id, Terminal_ReaderID, Terminal_Name, Terminal_Description, TerminalDatatype_ID, Time_Stamp, Emp_ID, 
			case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted  FROM TA_Tbl_Terminal Where Terminal_ReaderID not in(''787'',''788'')
			and Terminal_Id ='+convert(varchar(20),@TerminalID)
		IF(@UserGroupName = 'SuperAdmin')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN   
			Execute(@dynamicquery + ' AND IsDeleted=0')
		END
	END
	IF(@Type='C')  
	BEGIN   
		Select Count(TerminalDatatype_ID) as TerminalCount from TA_Tbl_Terminal Where TerminalDatatype_ID =@TerminalID  and Terminal_ReaderID not in('787','788')
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForEntrance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForEntrance] 
@Type Char(1),
@EntranceId int
AS
--Select Terminal details during Insert 
IF(@Type='I')
BEGIN
	SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name FROM TA_Tbl_Terminal T  
	where T.Terminal_Id Not IN (SELECT DISTINCT D.Reader_Id FROM TA_Tbl_Entrance E 
	INNER JOIN TA_Tbl_Entrance_inoutdetails D on E.Entrance_Id=D.Entrance_Id where E.Isdeleted=0)
END
--Select Terminal details during Modify
IF(@Type='U')
BEGIN
	SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name FROM TA_Tbl_Terminal T  
	where T.Terminal_Id Not IN (SELECT DISTINCT D.Reader_Id FROM TA_Tbl_Entrance E 
	INNER JOIN TA_Tbl_Entrance_inoutdetails D on E.Entrance_Id=D.Entrance_Id where E.Isdeleted=0 and E.Entrance_id <>  @EntranceId)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]
	@Type CHAR(1),  
	@TerminalID INT=0,  
	@UserGroupName nVarchar(250)
AS
BEGIN
	SET NOCOUNT ON;
	Select Count(TerminalDatatype_ID) as TerminalCount from TA_Tbl_Terminal	Where TerminalDatatype_ID =@TerminalID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalName]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Terminal_Id, Terminal_Name From TA_Tbl_Terminal Where IsDeleted ='1'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTransportation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_SelectTransportation]
(
	@Type CHAR(1),
	@VehicleNo INT=0
)
AS
	DECLARE @Del BIT
	SET @Del=1
--Select All Title Records
	IF(@Type='A')
	 BEGIN 
		SELECT * FROM TA_UI_Transportation WHERE IsDeleted=@Del
	 END
--Select Title Records For CompanyName  Based on TitleId
	IF(@Type='P')
	 BEGIN 
		SELECT * FROM TA_UI_Transportation WHERE VehicleNo=@VehicleNo and  IsDeleted=@Del
--		SELECT A.Companyid,A.TitleID,A.titleName,A.TitleDescription,B.Company_Name,B.Company_Id
--		FROM TA_Tbl_Title A
--		INNER JOIN TA_Tbl_CompanyDetails B ON A.Companyid = B.Company_Id
---		WHERE A.titleid = @TitleId
	 END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectType]	
	@TypeID as int
AS
BEGIN
	select TypeName,TypeId,isnull(IsFlexible,0) 'IsFlexible',isnull(Isdisply_MyProf,0)as Isdisply_MyProf From Ta_tbl_Type where TypeId=@TypeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_SelectTypeDetails]    
(    
	@TYPE CHAR(1)='',    
	@TypeId INT,
	@UserGroupName nVarchar(250)    
)    
AS    
BEGIN    
IF (@TYPE='A')    
BEGIN
   IF(@UserGroupName = 'SuperAdmin')
      BEGIN 
		SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type
      END
   ELSE
      BEGIN   
  		SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
  		WHERE IsDeleted=0    
      END
 END    
-- P Refers Particular   
ELSE IF (@TYPE='P')    
 BEGIN
     IF(@UserGroupName = 'SuperAdmin')
      BEGIN 
        SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
        WHERE TypeId=@TypeId
      END
    ELSE
      BEGIN    
        SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
        WHERE TypeId=@TypeId AND IsDeleted=0    
      END
 END    
ELSE If (@TYPE='I')    
  BEGIN    
	SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  WHERE IsDeleted=0 
  END    
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUsergroupDetailsForSMS]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016>
-- Description:	<Getting Usergroup details for sms template using templateID>
-- execute Proc_TA_SelectUsergroupDetailsForSMS 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectUsergroupDetailsForSMS] 
	-- Add the parameters for the stored procedure here
	@TemplateID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if not exists(select Usergroupid from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID)
	begin
		select groupId,groupName,0 as Status from TA_Tbl_Usergroup where isDeleted=0
	end
	else
	begin
		select groupId,groupName,
		isnull((select 1 from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID and Usergroupid=ug.groupId),0)as status from TA_Tbl_Usergroup ug
		where isDeleted=0
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUserName]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_SelectUserName]
(
	@username NVARCHAR(10),
	@password NVARCHAR(50)
)
AS
BEGIN
	Select Employee_Id,Employee_FirstName + ' ' + Employee_LastName AS 'Employee Name',
	Employee_Code_Id,EmailId,Photo  
	From TA_Tbl_Employee WHERE UserName=@username AND Emp_password=@password 
	AND IsDeleted=0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectVersion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectVersion] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select top 1 * from ta_tbl_version order by VersionId desc 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectWhatsAppScheduleBasedOnId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_SelectWhatsAppScheduleBasedOnId 4
CREATE PROCEDURE [dbo].[Proc_TA_SelectWhatsAppScheduleBasedOnId]
(
  @ScheduleId int = ''
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @ToEmailList VARCHAR(8000)
	DECLARE @CCEmailList VARCHAR(8000)
	SELECT @ToEmailList = COALESCE(@ToEmailList + ';', '') + CAST(MobileNum AS VARCHAR(100))
	FROM   TA_tbl_WhatsAppNumberForTriggeringMessage
	WHERE  ScheduleId = @ScheduleId and WhatsAppType = 'To'
	--SELECT @CCEmailList = COALESCE(@CCEmailList + ';', '') + CAST(MobileNum AS VARCHAR(100))
	--FROM   TA_tbl_WhatsAppNumberForTriggeringMessage
	--WHERE  ScheduleId = @ScheduleId and WhatsAppType = 'CC'
	Declare @reportId int
	select @reportId=ReportId from TA_Tbl_WhatsAppSchedule where ScheduleId=@ScheduleId
	if(@reportId=248 or @reportId=249)
	BEGIN
		select ES.*,F.*,E.*,@ToEmailList as ToEmailList,
		p.pageId,displayName=case when @reportId=248 then 'Leave Approval' else 'Onduty Approval' end, path, parentId, orderBy, ParentIdForSubMenu
		from TA_Tbl_WhatsAppSchedule ES
		--inner join TA_Tbl_EmailTemplate ET on ES.ScheduleId = ET.ScheduleId
		inner join TA_Tbl_WhatsAppScheduleFilters F on ES.ScheduleId = F.ScheduleId
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner Join TA_Tbl_Employee E on E.Employee_Id=ES.EmployeeId
		where ES.ScheduleId = @ScheduleId
	END
	ELSE
	BEGIN
	
		select *,@ToEmailList as ToEmailList from TA_Tbl_WhatsAppSchedule ES
		--inner join TA_Tbl_EmailTemplate ET on ES.ScheduleId = ET.ScheduleId
		inner join TA_Tbl_WhatsAppScheduleFilters F on F.ScheduleId = ES.ScheduleId
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner Join TA_Tbl_Employee E on E.Employee_Id=ES.EmployeeId
		where ES.ScheduleId = @ScheduleId
	end
END

--Select WhatsAppSendType From TA_Tbl_WhatsAppSchedule

--Select * From TA_Tbl_WhatsAppScheduleFilters

--Select * From TA_Tbl_Page where pageI


--Select * From TA_tbl_WhatsAppNumberForTriggeringMessage
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectWorkingDays]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectWorkingDays 5,2009
-- =============================================
CREATE PROCEDURE  [dbo].[Proc_TA_SelectWorkingDays]
	 @SelectedMonth nvarchar(20),  
	 @SelectedYear nvarchar(20) 
AS
BEGIN
	declare @FromDate as nvarchar(15)
	declare @ToDate as nvarchar(15)
	set @FromDate = cast(@SelectedMonth as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
	if (@SelectedMonth=12)
		Begin
			set @ToDate =  '01/' + '01/' + cast(@SelectedYear+1 as nvarchar(20))
		End
	Else
		Begin
			set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + '/' + '01/' + cast(@SelectedYear as nvarchar(20))
		End	
	select dbo.fn_TA_CountNumberOfWorkingDays(@FromDate,@ToDate) as TotalWokingDays
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosuredetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--	Proc_TA_SelectYearClosuredetails 5,'1','SuperAdmin'
CREATE  procedure [dbo].[Proc_TA_SelectYearClosuredetails]     
(    
@YearSettingId INT,    
@OrgLeavelID nvarchar(4000),
@UserGroupName varchar(250)  
)    
AS 
Begin
	declare @sql nvarchar(2000)  
	set @sql=''    
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@OrgLeavelID) as LevelId 
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	--SELECT * FROM #EmpLevel
	set @sql=@sql+ 'select * from TA_Tbl_YearClosure '
	set @sql=@sql + 'inner join #EmpLevel on #EmpLevel.LevelId=TA_Tbl_YearClosure.OrgLevelId and #EmpLevel.EmployeeId=TA_Tbl_YearClosure.Employee_Id'
	set @sql=@sql + ' where Year_SettingID='+ cast(@YearSettingId as nvarchar) + ''  
	exec(@sql)
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosureDetailsForModify]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_SelectYearClosureDetailsForModify  '','','0,1',0,0,'SuperAdmin','0','',0
Tables  : TA_Tbl_Employee, TA_Tbl_YearClosure 
Created By : Prabakaran  
Created on : 15-Oct-07    
Modified By		:	Manjula.P
Modified On		:	07-Feb-2014
Descriptions	:	Added  and ys.IsActive=1 becuase the Leave_Taken is wrongly displayed when the year closure is done then added new employee in that year 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_SelectYearClosureDetailsForModify]  
 @EmployeeName varchar(50), 
 @EmployeeId varchar(50), 
 @LevelID varchar(8000),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
@EmpSwipeCard varchar(20),
@ParentId int  		
AS  
BEGIN  
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table's creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--CREATE TABLE #TempTblRecord (EmpId INT, NoOfDays DECIMAL(18, 1), YearSettingId INT)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 

--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null

declare @sqlQuery as varchar(8000)  
SET @sqlQuery='' 
SET @sqlQuery='select yc.YearClosureId,emp.Employee_code_Id,(emp.Employee_FirstName + '' '' + emp.Employee_LastName) as EmployeeName, '
SET @sqlQuery = @sqlQuery + ' lt.LeaveType,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Leave_Taken,yc.Available_Leaves,Encashment 
,emp.Gender,yc.LeaveTypeID,emp.Employee_Id' 
--,ISNULL(YC.Carry_PrevYearCompOff, TR.NoOfDays) [Carry_PrevYearCompOff] '
SET @sqlQuery = @sqlQuery + ' from ta_tbl_yearclosure yc '
SET @sqlQuery = @sqlQuery + ' inner join Ta_tbl_employee emp  on emp.Employee_Id=yc.Employee_Id '
SET @sqlQuery = @sqlQuery + ' inner join Ta_tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeId '
  SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeLevel on emp.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId'
  SET @sqlQuery = @sqlQuery + ' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id'
  SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON emp.Employee_Id=EDesig.EmployeeID'
  SET @sqlQuery = @sqlQuery + ' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId '
  SET @sqlQuery = @sqlQuery + ' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'
SET @sqlQuery = @sqlQuery + ' inner join Ta_tbl_Yearsetting ys on ys.YearSettings_Id=yc.Year_SettingId '
  SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeCategory  on emp.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId'
  SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId'
  SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_EmployeeType  on emp.Employee_Id = TA_Tbl_EmployeeType.EmployeeId'
  SET @sqlQuery = @sqlQuery + ' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'
set @sqlQuery = @sqlQuery + ' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId '
set @sqlQuery = @sqlQuery + ' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId '
set @sqlQuery = @sqlQuery + ' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId '
set @sqlQuery = @sqlQuery + ' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId '
set @sqlQuery = @sqlQuery + ' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId '	
--SET @sqlQuery = @sqlQuery + ' LEFT JOIN #TempTblRecord TR ON TR.EmpId = emp.Employee_Id AND ys.YearSettings_Id = TR.YearSettingId'
SET @sqlQuery = @sqlQuery + ' where emp.Isdeleted=0 and emp.employee_Status=1 and lt.Isdeleted=0 and ys.IsActive=1'  
  if(@UserGroupName<>'SuperAdmin')
  begin
	SET @sqlQuery = @sqlQuery + ' AND TA_Tbl_Grade.Grade_Level>=' + @GradeLevel + ''
  end
  --if not(@LevelID='' or @LevelID='0')  
  --begin  
   --SET @sqlQuery = @sqlQuery + ' And (#EmpLevel.levelId In (' + @LevelID + '))'  
  --End  
  if not(@EmployeeName='' or @EmployeeName='0')  
  begin  
   --set @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'  
   SET @sqlQuery = @sqlQuery + 'and (emp.Employee_FirstName + '' '' + isnull(emp.Employee_LastName,'''') like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'
  end  
  if not(@EmployeeId='' or @EmployeeId='0')  
  begin  
   SET @sqlQuery = @sqlQuery + 'and (emp.Employee_Code_Id=''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
  end  
 If Not (@EmpSwipeCard = '')  
    Begin  
		  Set @sqlQuery = @sqlQuery + ' And emp.SwipeCardNo = ''' + @EmpSwipeCard + ''' '  
	End
  if(@employeeCategory<>0)
	begin
		SET @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeCategory.CategoryId = ' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + ' And TA_Tbl_EmployeeType.TypeId = ' + cast(@employeeType as nvarchar(8)) 
	end	
  SET @sqlQuery = @sqlQuery + ' order by emp.Employee_FirstName'   
	Create table #final(YearClosureId int,Employee_Code_Id nvarchar(200),
		EmployeeName nvarchar(200),LeaveType nvarchar(20),Carry_PrevYear decimal(18,1),
		Current_Quota decimal(18,1),Borrow_NextYear decimal(18,1),Leave_Taken decimal(18,1),
		Available_Leaves decimal(18,1),Encashment decimal(18,1),Gender varchar(10),LeaveTypeID int,EmployeeAutoId int)
	insert into #final exec(@sqlQuery) 
	update #final set Available_Leaves=RemainingNoOfLeaves,Leave_Taken=a.numberofdayAvailed from #final 
	inner join(
	Select yc.Employee_Id,(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		,yc.LeaveTypeID,ISNULL(sum(la.NumberOfDays),0.0)as numberofdayAvailed from TA_tbl_Yearclosure yc
		--Added  and ys.IsActive=1 becuase the Leave_Taken is wrongly displayed when the year closure is done then added new employee in that year by MAnjula.P on 07-Feb-2014
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id and ys.IsActive=1
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id and la.Status<>'Rejected' and la.IsDeleted=0
		Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,yc.Employee_Id
		)
		as a on #final.EmployeeAutoId=a.Employee_Id and #final.LeaveTypeID =a.LeaveTypeID
select * from #final
--Remove the temporary tables here
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
--DROP TABLE #TempTblRecord
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectYearSetting]
AS
BEGIN
	SET NOCOUNT ON;
	select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + ' - ' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting,
	convert(nvarchar(20),FromDate,102) as YearSettingFromDate,convert(nvarchar(20),ToDate,102) as YearSettingToDate, 
	YearSettings_Id, StartMonth, StartYear, EndMonth, EndYear, FromDate, ToDate, TimeStamp, Emp_Id, IsActive from Ta_Tbl_Yearsetting where IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingbyId]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectYearSettingbyId]      
(  
@YearSettingId int  
)  
AS      
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + ' - ' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting ,     
convert(varchar,fromdate,102) as fromdate,convert(varchar,todate,102) as todate
from Ta_Tbl_Yearsetting    where yearsettings_Id=@YearSettingId  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingForLeaveReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectYearSettingForLeaveReport]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select convert(varchar(20),FromDate,111) as YearSettingFromDate,CONVERT(varchar(20),ToDate,111) as YearSettingToDate
	from Ta_Tbl_Yearsetting where IsActive=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_SelectYearSettings]    
AS    
select YearSettings_Id,Fromdate,Todate,StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + ' - ' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting,isTimezoneEnable  from Ta_Tbl_Yearsetting  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ServerUTCTime]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>		
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ServerUTCTime]

@EmployeeID Nvarchar(Max)

AS
BEGIN
	
	Select * from TA_Tbl_UTCTimeZonesCountryDetails where ServerDefault=1

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllcation_Import]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	21-Aug-2014
 EXEC [Proc_TA_ShiftAllcation_Import] @ShiftData = '<Dst_ShiftAlloc>
  <Tbl_ShiftAlloc>
    <Employee_Code_Id>104</Employee_Code_Id>
    <Employee_Name>Anbu </Employee_Name>
    <Company_Name>Shift Company </Company_Name>
    <Year>2017</Year>
    <Mon>Jan</Mon>
    <Day1>EMS</Day1>
    <Day2>EMS</Day2>
    <Day3>EMS</Day3>
    <Day4>EMS</Day4>
    <Day5>EMS</Day5>
    <Day6>EMS</Day6>
    <Day7>EMS</Day7>
    <Day8>EMS</Day8>
    <Day9>EMS</Day9>
    <Day10>EMS</Day10>
    <Day11>EMS</Day11>
    <Day12>EMS</Day12>
    <Day13>EMS</Day13>
    <Day14>EMS</Day14>
    <Day15>EMS</Day15>
    <Day16>EMS</Day16>
    <Day17>EMS</Day17>
    <Day18>EMS</Day18>
    <Day19>EMS</Day19>
    <Day20>EMS</Day20>
    <Day21>EMS</Day21>
    <Day22>EMS</Day22>
    <Day23>EMS</Day23>
    <Day24>EMS</Day24>
    <Day25>EMS</Day25>
    <Day26>EMS</Day26>
    <Day27>EMS</Day27>
    <Day28>EMS</Day28>
    <Day29>EMS</Day29>
    <Day30>EMS</Day30>
    <Day31>EMS</Day31>
  </Tbl_ShiftAlloc></Dst_ShiftAlloc>', @WeekOff = '6', @SkipValid = 0
-- =============================================
*/
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllcation_Import]
	-- Add the parameters for the stored procedure here
	@ShiftData XML = NULL,
	@WeekOff VARCHAR(15),
	@SkipValid BIT
AS
BEGIN
	set nocount on
	--insert into TestingShiftAllocation values(@ShiftData,@WeekOff,@SkipValid)
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX),ImportID bigint)		
	DELETE FROM [TA_Tbl_ImportShiftAllocation]
	BEGIN TRY
		BEGIN TRAN ImportShiftMaster
			SELECT @YearSettingId = [YearSettings_Id], @StartDate = [FromDate] FROM [TA_Tbl_YearSetting] WHERE [IsActive] = 1 
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
			CREATE TABLE #TempImportShiftAllocation(
	[Employee_Id] [int] NULL,
	[Employee_Code_Id] [varchar](100) NULL,
	[Company_Id] [int] NULL,
	[Company_Name] [varchar](250) NULL,
	[Year] [varchar](5) NULL,
	[Mon] [varchar](20) NULL,
	[Day1] [varchar](8) NULL,
	[Day2] [varchar](8) NULL,
	[Day3] [varchar](8) NULL,
	[Day4] [varchar](8) NULL,
	[Day5] [varchar](8) NULL,
	[Day6] [varchar](8) NULL,
	[Day7] [varchar](8) NULL,
	[Day8] [varchar](8) NULL,
	[Day9] [varchar](8) NULL,
	[Day10] [varchar](8) NULL,
	[Day11] [varchar](8) NULL,
	[Day12] [varchar](8) NULL,
	[Day13] [varchar](8) NULL,
	[Day14] [varchar](8) NULL,
	[Day15] [varchar](8) NULL,
	[Day16] [varchar](8) NULL,
	[Day17] [varchar](8) NULL,
	[Day18] [varchar](8) NULL,
	[Day19] [varchar](8) NULL,
	[Day20] [varchar](8) NULL,
	[Day21] [varchar](8) NULL,
	[Day22] [varchar](8) NULL,
	[Day23] [varchar](8) NULL,
	[Day24] [varchar](8) NULL,
	[Day25] [varchar](8) NULL,
	[Day26] [varchar](8) NULL,
	[Day27] [varchar](8) NULL,
	[Day28] [varchar](8) NULL,
	[Day29] [varchar](8) NULL,
	[Day30] [varchar](8) NULL,
	[Day31] [varchar](8) NULL,
	[ImportID] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
			INSERT INTO #TempImportShiftAllocation
				SELECT E.Employee_Id, E.SwipeCardNo, LD.Id, Tbl.Company_Name, [Year], [Mon],
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '01-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day1 END) Day1,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '02-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day2 END) Day2,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '03-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day3 END) Day3,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '04-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day4 END) Day4,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '05-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day5 END) Day5,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '06-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day6 END) Day6,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '07-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day7 END) Day7,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '08-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day8 END) Day8,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '09-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day9 END) Day9,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '10-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day10 END) Day10,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '11-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day11 END) Day11,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '12-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day12 END) Day12,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '13-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day13 END) Day13,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '14-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day14 END) Day14,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '15-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day15 END) Day15,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '16-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day16 END) Day16,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '17-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day17 END) Day17,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '18-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day18 END) Day18,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '19-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day19 END) Day19,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '20-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day20 END) Day20,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '21-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day21 END) Day21,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '22-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day22 END) Day22,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '23-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day23 END) Day23,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '24-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day24 END) Day24,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '25-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day25 END) Day25,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '26-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day26 END) Day26,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '27-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day27 END) Day27,
					(CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '28-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day28 END) Day28,
					(CASE WHEN ([Mon] <> 'Feb') THEN (CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '29-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day29 END) ELSE (CASE WHEN (([Mon] = 'Feb') AND (datepart(d,DATEADD(D, -1, ('01-Mar-' + [Year]))) = 29)) THEN (CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '29-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day29 END) ELSE NULL END) END) Day29,
					(CASE WHEN ([Mon] <> 'Feb') THEN (CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '30-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day30 END) ELSE NULL END) Day30,
					(CASE WHEN ([Mon] NOT IN ('Feb', 'Apr', 'Jun', 'Sep', 'Nov')) THEN (CASE WHEN @WeekOff LIKE '%' + CAST(DATEPART(DW, '31-' + [Mon] + '-' + [Year]) AS VARCHAR(8)) + '%' THEN 'Off' ELSE Day31 END) ELSE NULL END) Day31
				FROM OPENXML (@XMLParams, '/Dst_ShiftAlloc/Tbl_ShiftAlloc', 2) WITH 
				  (Employee_Code_Id VARCHAR(50), Company_Name VARCHAR(250), [Year] VARCHAR(5), Mon VARCHAR(20), Day1 VARCHAR(8), Day2 VARCHAR(8), Day3 VARCHAR(8), 
				   Day4 VARCHAR(8), Day5 VARCHAR(8), Day6 VARCHAR(8), Day7 VARCHAR(8), Day8 VARCHAR(8), Day9 VARCHAR(8), Day10 VARCHAR(8),
				   Day11 VARCHAR(8), Day12 VARCHAR(8), Day13 VARCHAR(8), Day14 VARCHAR(8), Day15 VARCHAR(8), Day16 VARCHAR(8), Day17 VARCHAR(8),
				   Day18 VARCHAR(8), Day19 VARCHAR(8), Day20 VARCHAR(8), Day21 VARCHAR(8), Day22 VARCHAR(8), Day23 VARCHAR(8), Day24 VARCHAR(8),
				   Day25 VARCHAR(8), Day26 VARCHAR(8), Day27 VARCHAR(8), Day28 VARCHAR(8), Day29 VARCHAR(8), Day30 VARCHAR(8), Day31 VARCHAR(8)) Tbl
				LEFT OUTER JOIN TA_Tbl_LevelDetails LD ON LD.[Name] = Tbl.Company_Name AND LD.ParentId = 0
				LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
				 AND E.IsDeleted = 0 AND E.Employee_Status = 1
				 insert into [TA_Tbl_ImportShiftAllocation](Employee_Id, Employee_Code_Id, Company_Id, Company_Name, Year, Mon, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day17, Day18, Day19, Day20, Day21, Day22, Day23, Day24, Day25, Day26, Day27, Day28, Day29, Day30, Day31, RecordNumber)
				 select Employee_Id, Employee_Code_Id, Company_Id, Company_Name, Year, Mon, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day17, Day18, Day19, Day20, Day21, Day22, Day23, Day24, Day25, Day26, Day27, Day28, Day29, Day30, Day31,1+ROW_NUMBER()over(order by importid) from #TempImportShiftAllocation
			--It will Remove Duplication Records From Import Table
			--by Manikandan.RR on 11-01-2016 11.12 AM
			--Delete from [TA_Tbl_ImportShiftAllocation] where ImportID in
			--(
			--	SELECT ImportID FROM 
			--	(
			--		SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
			--				ImportID FROM [TA_Tbl_ImportShiftAllocation]
			--	)AS A WHERE duplicate>1
			--)			
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation])
			BEGIN
				SET @ErrMsg = 'There is no record in the file'
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END
			IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Employee_Id, '') = '')
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], 'Invalid Employee Code Id',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Employee_Id, '') = ''
			END
			IF ((EXISTS(SELECT Company_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Company_Id, '') = '')))
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], 'Invalid Company Name',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Company_Id, '') = ''			
			END
			IF Exists(
			SELECT ImportID FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
						ImportID FROM [TA_Tbl_ImportShiftAllocation]
			)AS A WHERE duplicate>1)
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon],'Duplication Records are Entered',RecordNumber from
					(
						SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
						Employee_Code_Id,[Year], [Mon],RecordNumber FROM [TA_Tbl_ImportShiftAllocation] where Employee_Code_Id is not null
					)AS A WHERE duplicate>1
			END
			IF ((EXISTS(SELECT [Year] FROM [TA_Tbl_ImportShiftAllocation] WHERE (CAST(('01-' + [Mon] + '-' + [Year]) AS DATETIME))  < @StartDate)))
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], 'Past Year Not Allowed',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE (CAST(('01-' + [Mon] + '-' + [Year]) AS DATETIME))  < @StartDate
			END
			IF(NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			BEGIN
				SELECT @NosId = ISNULL(Shift_Id, -2) FROM TA_Tbl_Shift WHERE Shift_ShortName LIKE 'NOS'
				Declare @i int
				set @i=1
				declare @SQl as nvarchar(MAx)
				set @NosId = ISNULL(@NosId,0)
				while @i<=31
				begin
					set @SQl='UPDATE [TA_Tbl_ImportShiftAllocation] SET Day'+cast(@i as nvarchar(3)) +' = (CASE WHEN ISNULL([Day'+cast(@i as nvarchar(3)) +'], '''') = '''' THEN 0 
					WHEN Day'+cast(@i as nvarchar(3)) +' = ''Off'' THEN -1 
					WHEN Day'+cast(@i as nvarchar(3)) +' = ''NOS'' THEN '''+cast(@NosId as nvarchar(3)) +''' ELSE ISNULL(S1.Shift_Id, -2) END)
									FROM [TA_Tbl_ImportShiftAllocation] SA
									LEFT JOIN TA_Tbl_Shift S1 ON S1.Shift_ShortName = SA.Day'+cast(@i as nvarchar(3)) +' AND S1.Level_Id = SA.Company_Id AND S1.Isdeleted = 0'
					Execute(@SQl)
					set @i=@i+1
				end				
				IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE (-2) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31]))
				BEGIN
					INSERT INTO @ErrorMsg
						SELECT DISTINCT Employee_Code_Id, [Year], [Mon], 'Invalid Shift Short Name',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE (-2) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31])
				END
			END
			--Commented by Manikandan.R as per the team suggestion on 25-11-2015 11.20 AM
			--IF( NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			--BEGIN
			--	UPDATE [TA_Tbl_ImportShiftAllocation] SET 
			--		Day1 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day1, ('01-' + [Mon] + '-' + [Year])),
			--		Day2 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day2, ('01-' + [Mon] + '-' + [Year])),
			--		Day3 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day3, ('01-' + [Mon] + '-' + [Year])),
			--		Day4 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day4, ('01-' + [Mon] + '-' + [Year])),
			--		Day5 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day5, ('01-' + [Mon] + '-' + [Year])),
			--		Day6 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day6, ('01-' + [Mon] + '-' + [Year])),
			--		Day7 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day7, ('01-' + [Mon] + '-' + [Year])),
			--		Day8 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day8, ('01-' + [Mon] + '-' + [Year])),
			--		Day9 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day9, ('01-' + [Mon] + '-' + [Year])),
			--		Day10 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day10, ('01-' + [Mon] + '-' + [Year])),
			--		Day11 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day11, ('01-' + [Mon] + '-' + [Year])),
			--		Day12 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day12, ('01-' + [Mon] + '-' + [Year])),
			--		Day13 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day13, ('01-' + [Mon] + '-' + [Year])),
			--		Day14 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day14, ('01-' + [Mon] + '-' + [Year])),
			--		Day15 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day15, ('01-' + [Mon] + '-' + [Year])),
			--		Day16 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day16, ('01-' + [Mon] + '-' + [Year])),
			--		Day17 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day17, ('01-' + [Mon] + '-' + [Year])),
			--		Day18 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day18, ('01-' + [Mon] + '-' + [Year])),
			--		Day19 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day19, ('01-' + [Mon] + '-' + [Year])),
			--		Day20 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day20, ('01-' + [Mon] + '-' + [Year])),
			--		Day21 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day21, ('01-' + [Mon] + '-' + [Year])),
			--		Day22 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day22, ('01-' + [Mon] + '-' + [Year])),
			--		Day23 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day23, ('01-' + [Mon] + '-' + [Year])),
			--		Day24 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day24, ('01-' + [Mon] + '-' + [Year])),
			--		Day25 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day25, ('01-' + [Mon] + '-' + [Year])),
			--		Day26 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day26, ('01-' + [Mon] + '-' + [Year])),
			--		Day27 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day27, ('01-' + [Mon] + '-' + [Year])),
			--		Day28 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day28, ('01-' + [Mon] + '-' + [Year])),
			--		Day29 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day29, ('01-' + [Mon] + '-' + [Year])),
			--		Day30 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day30, ('01-' + [Mon] + '-' + [Year])),
			--		Day31 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day31, ('01-' + [Mon] + '-' + [Year]))
			--	FROM [TA_Tbl_ImportShiftAllocation]
			--	IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE (-3) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31]))
			--	BEGIN
			--		INSERT INTO @ErrorMsg
			--			SELECT DISTINCT Employee_Code_Id, [Year], [Mon], 'Shift Is Overlapped' FROM [TA_Tbl_ImportShiftAllocation] WHERE (-3) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31])
			--	END
			--END
			IF( NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			BEGIN
				INSERT INTO TA_Tbl_PermanentShiftAllocation
					SELECT SI.Employee_Id, SI.[Year], MONTH(CAST(('01-' + SI.[Mon] + '-' + SI.[Year]) AS DATETIME)), [Day1], [Day2], [Day3], [Day4], 
					[Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19],
					 [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31], 1, GETDATE(), 
					 CAST(('01-' + SI.[Mon] + '-' + SI.[Year]) AS DATETIME) FROM [TA_Tbl_ImportShiftAllocation] SI
						LEFT JOIN TA_Tbl_PermanentShiftAllocation PS ON PS.EmployeeId = SI.Employee_Id AND PS.[Year] = SI.[Year] AND PS.[Month] = MONTH(CAST(('01-' + SI.[Mon] + '-' + SI.[Year]) AS DATETIME))
					WHERE ISNULL(PS.EmployeeId, '') = ''
				UPDATE [TA_Tbl_PermanentShiftAllocation] SET
					[Day1Shift] = (CASE WHEN [Day1] = 0 THEN [Day1Shift] ELSE [Day1] END),
					[Day2Shift] = (CASE WHEN [Day2] = 0 THEN [Day2Shift] ELSE [Day2] END),
					[Day3Shift] = (CASE WHEN [Day3] = 0 THEN [Day3Shift] ELSE [Day3] END),
					[Day4Shift] = (CASE WHEN [Day4] = 0 THEN [Day4Shift] ELSE [Day4] END),
					[Day5Shift] = (CASE WHEN [Day5] = 0 THEN [Day5Shift] ELSE [Day5] END),
					[Day6Shift] = (CASE WHEN [Day6] = 0 THEN [Day6Shift] ELSE [Day6] END),
					[Day7Shift] = (CASE WHEN [Day7] = 0 THEN [Day7Shift] ELSE [Day7] END),
					[Day8Shift] = (CASE WHEN [Day8] = 0 THEN [Day8Shift] ELSE [Day8] END),
					[Day9Shift] = (CASE WHEN [Day9] = 0 THEN [Day9Shift] ELSE [Day9] END),
					[Day10Shift] = (CASE WHEN [Day10] = 0 THEN [Day10Shift] ELSE [Day10] END),
					[Day11Shift] = (CASE WHEN [Day11] = 0 THEN [Day11Shift] ELSE [Day11] END),
					[Day12Shift] = (CASE WHEN [Day12] = 0 THEN [Day12Shift] ELSE [Day12] END),
					[Day13Shift] = (CASE WHEN [Day13] = 0 THEN [Day13Shift] ELSE [Day13] END),
					[Day14Shift] = (CASE WHEN [Day14] = 0 THEN [Day14Shift] ELSE [Day14] END),
					[Day15Shift] = (CASE WHEN [Day15] = 0 THEN [Day15Shift] ELSE [Day15] END),
					[Day16Shift] = (CASE WHEN [Day16] = 0 THEN [Day16Shift] ELSE [Day16] END),
					[Day17Shift] = (CASE WHEN [Day17] = 0 THEN [Day17Shift] ELSE [Day17] END),
					[Day18Shift] = (CASE WHEN [Day18] = 0 THEN [Day18Shift] ELSE [Day18] END),
					[Day19Shift] = (CASE WHEN [Day19] = 0 THEN [Day19Shift] ELSE [Day19] END),
					[Day20Shift] = (CASE WHEN [Day20] = 0 THEN [Day20Shift] ELSE [Day20] END),
					[Day21Shift] = (CASE WHEN [Day21] = 0 THEN [Day21Shift] ELSE [Day21] END),
					[Day22Shift] = (CASE WHEN [Day22] = 0 THEN [Day22Shift] ELSE [Day22] END),
					[Day23Shift] = (CASE WHEN [Day23] = 0 THEN [Day23Shift] ELSE [Day23] END),
					[Day24Shift] = (CASE WHEN [Day24] = 0 THEN [Day24Shift] ELSE [Day24] END),
					[Day25Shift] = (CASE WHEN [Day25] = 0 THEN [Day25Shift] ELSE [Day25] END),
					[Day26Shift] = (CASE WHEN [Day26] = 0 THEN [Day26Shift] ELSE [Day26] END),
					[Day27Shift] = (CASE WHEN [Day27] = 0 THEN [Day27Shift] ELSE [Day27] END),
					[Day28Shift] = (CASE WHEN [Day28] = 0 THEN [Day28Shift] ELSE [Day28] END),
					[Day29Shift] = (CASE WHEN [Day29] = 0 THEN [Day29Shift] ELSE [Day29] END),
					[Day30Shift] = (CASE WHEN [Day30] = 0 THEN [Day30Shift] ELSE [Day30] END),
					[Day31Shift] = (CASE WHEN [Day31] = 0 THEN [Day31Shift] ELSE [Day31] END),
					Emp_Id =1,
					[TimeStamp] = GETDATE()
				FROM [TA_Tbl_PermanentShiftAllocation] PS
					LEFT JOIN [TA_Tbl_ImportShiftAllocation] SI ON PS.EmployeeId = SI.Employee_Id AND PS.[Year] = SI.[Year] AND PS.[Month] = MONTH(CAST(('01-' + SI.[Mon] + '-' + SI.[Year]) AS DATETIME))
				WHERE ISNULL(SI.Employee_Id, '') <> ''
				Create table #TempShiftImport(Autoid int identity(1,1),Employee_Code_id varchar(50),date datetime)
				insert into #TempShiftImport 
				select employee_code_id,'01-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day1!=0 union all
				select employee_code_id,'02-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day2!=0 union all
				select employee_code_id,'03-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day3!=0 union all
				select employee_code_id,'04-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day4!=0 union all
				select employee_code_id,'05-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day5!=0 union all
				select employee_code_id,'06-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day6!=0 union all
				select employee_code_id,'07-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day7!=0 union all
				select employee_code_id,'08-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day8!=0 union all
				select employee_code_id,'09-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day9!=0 union all
				select employee_code_id,'10-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day10!=0 union all
				select employee_code_id,'11-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day11!=0 union all
				select employee_code_id,'12-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day12!=0 union all
				select employee_code_id,'13-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day13!=0 union all
				select employee_code_id,'14-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day14!=0 union all
				select employee_code_id,'15-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day15!=0 union all
				select employee_code_id,'16-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day16!=0 union all
				select employee_code_id,'17-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day17!=0 union all
				select employee_code_id,'18-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day18!=0 union all
				select employee_code_id,'19-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day19!=0 union all
				select employee_code_id,'20-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day20!=0 union all
				select employee_code_id,'21-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day21!=0 union all
				select employee_code_id,'22-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day22!=0 union all
				select employee_code_id,'23-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day23!=0 union all
				select employee_code_id,'24-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day24!=0 union all
				select employee_code_id,'25-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day25!=0 union all
				select employee_code_id,'26-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day26!=0 union all
				select employee_code_id,'27-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day27!=0 union all
				select employee_code_id,'28-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day28!=0 union all
				select employee_code_id,'29-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day29!=0 union all
				select employee_code_id,'30-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day30!=0 union all
				select employee_code_id,'31-'+MON+'-'+Year as date from TA_Tbl_ImportShiftAllocation where Day31!=0 
				--Delete The [TA_Tbl_ProcessedData] To Reprocess The Allocated Days
				DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=SI.date
				--select * from #TempShiftImport 
				
				DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=DATEADD(d,1,SI.date)
				
				DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=DATEADD(d,-1,SI.date)

				--Delete The [ta_tbl_MatchedPunches] To Reprocess The Allocated Days
				--Added By Manikandan.R -- on 04-09-2014
				DELETE FROM [ta_tbl_MatchedPunches] FROM [ta_tbl_MatchedPunches] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.Clk_Date=SI.date

				--Delete The [TA_Tbl_ClockDetails] To Reprocess The Allocated Days
				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_Date=SI.date

				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_InDate=DATEADD(d,0,SI.date)

				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_OutDate=DATEADD(d,0,SI.date)

				--Update The Clk_Process = 'N' To [TA_Tbl_ManualTimeEntry] To Reprocess The Allocated Days
				UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' FROM TA_Tbl_ManualTimeEntry MTE 
				INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND MTE.ManualTimeEntry_InDate=SI.date

				UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' FROM TA_Tbl_ManualTimeEntry MTE 
				INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND MTE.ManualTimeEntry_OutDate=SI.date


				--Update The Clk_Flag = 0, Clk_Process = 0 To [TA_Tbl_Clk_RawData] To Reprocess The Allocated Days
				UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND 
				Clk_Date BETWEEN DateAdd(d,-1,SI.date) AND DateAdd(d,1,SI.date)				
				--UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND RD.Clk_Date=SI.date
				--UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND RD.Clk_Date=SI.date
				DELETE FROM [TA_Tbl_ImportShiftAllocation]						
			END
			ELSE 
			BEGIN
				update IM set IM.Employee_Id=E.Employee_Code_ID from @ErrorMsg IM inner join TA_Tbl_Employee E on E.SwipeCardNo=IM.Employee_Id
				SELECT * FROM @ErrorMsg
			END
		COMMIT TRAN ImportShiftMaster
			SELECT 'Msg:ShiftImportSuccessfully' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = (CASE WHEN ERROR_MESSAGE() LIKE 'Conversion failed%' THEN 'Kindly Check Year/Month Format' ELSE ERROR_MESSAGE() END )
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportShiftMaster
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
		--SELECT 'Error:' + (CASE WHEN @ErrMsg LIKE 'Conversion failed when converting date and/or time from character string.' THEN 'Kindly Check Year/Month Format' ELSE @ErrMsg END) [Message]
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllcation_Import_Samsung]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	21-Aug-2014
 EXEC Proc_TA_ShiftAllcation_Import_Samsung @ShiftData = 
 '<Dst_ShiftAlloc>
  <Tbl_ShiftAlloc>
    <Si_x0020_No />
    <Employee_Id>7613298</Employee_Id>
    <In_Date>20210424</In_Date>
    <In_Time>2.02E+13</In_Time>
    <In_Punch_Type>Shift in</In_Punch_Type>
    <Out_Date />
    <Out_Time />
    <Out_Punch_Type />
    <Reason>TestingBew</Reason>
    <Work_x0020_Type>Import(08:00-17:00)</Work_x0020_Type>
    <Day_x0020_Type>Weekday</Day_x0020_Type>
    <Work_x0020_Date>20210424</Work_x0020_Date>
  </Tbl_ShiftAlloc>
  <Tbl_ShiftAlloc>
    <Si_x0020_No />
    <Employee_Id>7613298</Employee_Id>
    <In_Date>20210429</In_Date>
    <In_Time>2.02E+13</In_Time>
    <In_Punch_Type>Shift in</In_Punch_Type>
    <Out_Date />
    <Out_Time />
    <Out_Punch_Type />
    <Reason>TestingBew</Reason>
    <Work_x0020_Type>Import123(08:00-17:00)</Work_x0020_Type>
    <Day_x0020_Type>Weekday</Day_x0020_Type>
    <Work_x0020_Date>20210425</Work_x0020_Date>
  </Tbl_ShiftAlloc>
  <Tbl_ShiftAlloc>
    <Si_x0020_No />
    <Employee_Id>7613298</Employee_Id>
    <In_Date>20210430</In_Date>
    <In_Time />
    <In_Punch_Type />
    <Out_Date>20210430</Out_Date>
    <Out_Time>2.02E+13</Out_Time>
    <Out_Punch_Type>Shift out</Out_Punch_Type>
    <Reason>TestingBew</Reason>
    <Work_x0020_Type>ImportMorningShift(08:00-17:00)</Work_x0020_Type>
    <Day_x0020_Type>Weekday</Day_x0020_Type>
    <Work_x0020_Date>20210426</Work_x0020_Date>
  </Tbl_ShiftAlloc>
</Dst_ShiftAlloc>'
-- =============================================
*/
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllcation_Import_Samsung]
	-- Add the parameters for the stored procedure here
	@ShiftData XML = NULL
AS
BEGIN
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1)
	)
	
	BEGIN TRY
		BEGIN TRAN ImportShiftMaster_Samsung
			SELECT @YearSettingId = [YearSettings_Id], @StartDate = [FromDate] FROM [TA_Tbl_YearSetting] WHERE [IsActive] = 1 
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
			CREATE TABLE #TempImportShiftAllocation_Samsung(
			Employee_Id varchar(20),
			In_Date	 varchar(20),
			In_Time	 varchar(20),
			In_Punch_Type	varchar(20),
			Out_Date	varchar(20),
			Out_Time	varchar(20),
			Out_Punch_Type	varchar(20),
			Reason	varchar(20),
			[Work Type]	varchar(100),
			[Day Type]	varchar(100),
			[Work Date] varchar(100),
			Employee_code_id varchar(50),
			[ImportID] [int] IDENTITY(1,1) NOT NULL
			) ON [PRIMARY]
			INSERT INTO #TempImportShiftAllocation_Samsung
				SELECT 
					tbl.Employee_Id,
					In_Date	,
					In_Time	 ,
					In_Punch_Type	,
					Out_Date	,
					Out_Time	,
					Out_Punch_Type	,
					Reason	,
					[Work Type]	,
					[Day Type]	,
					[Work Date],
					E.Employee_Code_Id
				FROM OPENXML (@XMLParams, '/Dst_ShiftAlloc/Tbl_ShiftAlloc', 2) WITH 
				  (
					Employee_Id varchar(20),
					In_Date	 varchar(20),
					In_Time	 varchar(20),
					In_Punch_Type	varchar(20),
					Out_Date	varchar(20),
					Out_Time	varchar(20),
					Out_Punch_Type	varchar(20),
					Reason	varchar(20),
					[Work Type]	varchar(100),
					[Day Type]	varchar(100),
					[Work Date] varchar(100)
					) Tbl
				
				LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
				 AND E.IsDeleted = 0 AND E.Employee_Status = 1
				 
			
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung)
			BEGIN
				SET @ErrMsg = 'There is no record in the file'
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
			END
			INSERT INTO @ErrorMsg
			SELECT ImportID,Employee_Code_Id,'',1 FROM #TempImportShiftAllocation_Samsung
			
			--select * from #TempImportShiftAllocation_Samsung
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL(Employee_Id, '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'This employee is not created in timecheck, please remove it and then try import;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.Employee_Id, '') = ''
			END
			IF EXISTS(SELECT ss.Employee_Id FROM #TempImportShiftAllocation_Samsung ss
			left outer join TA_Tbl_Employee e on e.Employee_Code_Id=ss.Employee_code_id
			WHERE ISNULL(e.Employee_Id, '') = '')
			BEGIN
				
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'This employee is not created in timecheck, please remove it and then try import;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID
				left outer join TA_Tbl_Employee e on e.Employee_Code_Id=tot.Employee_code_id
				WHERE ISNULL(e.Employee_Id, '') = ''				
			END
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Work Date], '') = '')
			BEGIN				
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Work Date should not be empty for shift allocation;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Work Date], '') = ''
			END
			
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Work Date], '') != '' and (LEN([Work Date])<8 or len([Work Date])>8))
			BEGIN				
				
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Date format of Work date is not correct. Please check it;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Work Date], '') != '' and  (LEN([Work Date])<8 or len([Work Date])>8)
				
			END
			
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Work Date], '') != '' and LEN([Work Date])=8 and (SUBSTRING([Work Date],5,2)='00' or SUBSTRING([Work Date],7,2)='00'))
			BEGIN				
				
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Date format of Work date is not correct. Please check it;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Work Date], '') != '' and LEN([Work Date])=8 and (SUBSTRING([Work Date],5,2)='00' or SUBSTRING([Work Date],7,2)='00')
			END
			
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Day Type], '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Day Type should not be empty for shift allocation;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Day Type], '') = ''
			END		
			
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Day Type], '') != '' and ISNULL([Day Type],'') not in('WeekDay','Holiday'))
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Day Type should be Week day or Holiday. Other day types are not considered for import;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Day Type], '') != ''and ISNULL([Day Type],'') not in('WeekDay','Holiday')
			END
			IF EXISTS(SELECT Employee_Id FROM #TempImportShiftAllocation_Samsung WHERE ISNULL([Work Type], '') = '')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'')+'Work Type should not be empty for shift allocation;<br />',flag=0 FROM @ErrorMsg EM
				inner join #TempImportShiftAllocation_Samsung tot on tot.ImportID=EM.RecordID 
				WHERE ISNULL(tot.[Work Type], '') = ''
			END
			

			
			IF Exists(
			SELECT ImportID FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,[work date] ORDER BY Employee_Id ASC)AS duplicate,
						ImportID FROM #TempImportShiftAllocation_Samsung
			)AS A WHERE duplicate>1)
			BEGIN
				Declare @alertmsg varchar(max)
				set @alertMsg='Duplication Record Found;Please find and remove duplicate record in excel file;<br />'				
				UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,fromdate ORDER BY Employee_Code_Id ASC)AS duplicate,
					Employee_Code_Id,ImportID FROM #TempImportShiftAllocation_Samsung
				)AS A on EM.RecordID=a.ImportID WHERE a.duplicate>1
				and ISNULL(a.Employee_Code_Id, '') != ''
			END			
			
			
			IF NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg WHERE flag=0)
			BEGIN
				/* Insert Shift Details into Timecheck*/
				delete from Ta_tbl_DummyShiftDetails
				
				insert into Ta_tbl_DummyShiftDetails
				select [New work type],ROW_NUMBER()over(order by [New work type]),[Work Type] from(
				select  distinct
				
				[New work type]=rtrim(ltrim([work type])),[work type] from #TempImportShiftAllocation_Samsung 
				where rtrim(ltrim([work type])) not in(select Shift_Name from TA_Tbl_Shift)
				) as shifts
				
				--select * from Ta_tbl_DummyShiftDetails 
				Declare @TotalShift int
				Declare @startShift int
				Set @startShift=1
				select @TotalShift= COUNT(*) from Ta_tbl_DummyShiftDetails
				while @startShift<=@TotalShift
				begin
					Declare @ShiftName varchar(100)
					Declare @FullShiftName varchar(100)
					select @ShiftName= ShiftName,@FullShiftName=FullShiftName
					from Ta_tbl_DummyShiftDetails where recordid=@startShift
					
					if not exists(select * from TA_Tbl_Shift where Shift_Name=@FullShiftName)
					begin
						Declare @starttime varchar(20)
						Declare @EndTime varchar(20)
						
						select @starttime=starttime from(
						select row=ROW_NUMBER()over(order by @shiftname),starttime= right('00'+ltrim(substring(convert(varchar(50),convert(datetime,Value),109),13,5)),5)+' ' +
				right(convert(varchar(50),convert(datetime,Value),109),2) from split(replace(SUBSTRING(rtrim(ltrim(@ShiftName)),charindex('(',rtrim(ltrim(@ShiftName)))+1,len(rtrim(ltrim(@ShiftName)))),')',''),'-')
						)as sub where row=1
						
						select @EndTime=endTime from(
						select row=ROW_NUMBER()over(order by @shiftname),			
						endTime= 
						right('00'+ltrim(substring(convert(varchar(50),convert(datetime,Value),109),13,5)),5)+' ' +
				right(convert(varchar(50),convert(datetime,Value),109),2) from split(replace(SUBSTRING(rtrim(ltrim(@ShiftName)),charindex('(',rtrim(ltrim(@ShiftName)))+1,len(rtrim(ltrim(@ShiftName)))),')',''),'-')
						)as sub where row=2
						--select @starttime,@EndTime,@FullShiftName
						Declare @levelid bigint
						select top 1 @levelid=levelId  from Ta_Tbl_levelDetails where parentId=0 order by levelId
						Declare @maxID bigint
						select @maxID=max(shift_id)from TA_Tbl_Shift
						set @maxID=@maxID+1
						
						insert into TA_Tbl_Shift(Level_Id,Shift_Name,Shift_ShortName,Shift_StartTime,Shift_EndTime,Shift_FirstHalf_StartTime,
						Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_MinTimeOT,Shift_MaxTimeOT,Shift_WorkingDay_OverTime,
						Shift_TotalWorkingHours,Isdeleted,Emp_ID,Shift_FirstHalfWorkingHours,DefaultShift,ShiftType,CreatedDate,[24HrsShift],isStraightShift,StraightPresentTime,empCategory,specialOvertime_start1,specialOvertime_start2,MaxShiftWorkHours,Shift_GraceInTime,Shift_GraceOutTime )
						values
						(
							@levelid,@FullShiftName,'S'+convert(varchar(10),@maxID),@starttime,@EndTime,@starttime,@EndTime,@starttime,@EndTime,'00:45','04:00',1,
											case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
								 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
								 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
							end,
							0,1,
											case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
								 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
								 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
							end,
							0,
							1,getdate(),0,1,
											case when right(@starttime,2)='AM' and RIGHT(@endtime,2)='PM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
								 when right(@starttime,2)='PM' and RIGHT(@endtime,2)='AM' then dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,DATEADD(d,1,@EndTime)))
								 else dbo.ConvertMinsToHours(DATEDIFF(MINUTE,@starttime,@EndTime))
							end,
							0,0,0,'00:00','',''
						)
					end
					
					set @startShift=@startShift+1
				end
				
				Declare @Employee_ID varchar(50)				
				Declare @Work_Type varchar(100)
				Declare @Work_Date varchar(20)
				Declare @Day_Type varchar(100)
				CREATE TABLE #TEMP (SHIFTID INT)	
				DECLARE @Totalrecordcount int
				DECLARE @start int
				SET @Totalrecordcount = 0
				SET @start = 1 
				SELECT @Totalrecordcount = COUNT(*) FROM #TempImportShiftAllocation_Samsung
				WHILE (@start<= @Totalrecordcount)
				BEGIN
					SELECT 
						@Employee_ID=Employee_Id,
						@Work_Type=[Work Type] ,
						@Work_Date=[Work Date] ,
						@Day_Type=[Day Type]						
					FROM #TempImportShiftAllocation_Samsung WHERE ImportID = @start
					IF(0=0)
					BEGIN
						--select @Work_Type,@Day_Type
						Declare @Shift_Id int
						set @Shift_Id=0
						if(@Day_Type='HOliday')
						begin
							--print 'manikandan'
							set @Shift_Id=-1
						end
						DECLARE @QUERY VARCHAR(max)  
						set @QUERY=''
						Declare @ShiftDate datetime
						
						Declare @AllocatedShiftID bigint			
						Declare @updateQuery varchar(max)			
						Declare @EMPLOYEEAUTOID bigint
						select @EMPLOYEEAUTOID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employee_ID
						if(@Shift_Id!=-1)
						begin
							if not Exists(select Shift_Id from TA_Tbl_Shift where Shift_Name=@Work_Type)
							begin
								--select 'Shift is not available'
								continue;
							end
							else
							begin								
								select @Shift_Id=Shift_Id from TA_Tbl_Shift where Shift_Name=@Work_Type					
								set @ShiftDate=CONVERT(datetime,@Work_Date)
								SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
										WHERE PSA.[YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  PSA.[MONTH]= ' + convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' +CONVERT(varchar(20), @EMPLOYEEAUTOID)
								print (@QUERY )
								INSERT INTO #TEMP EXEC(@QUERY)
								SELECT @AllocatedShiftID =ISNULL(SHIFTID,0) FROM #TEMP	
								
								set @updateQuery=''
								if((select COUNT(*) from #TEMP)>0)
								begin
									if(@AllocatedShiftID=0 or @AllocatedShiftID!=@Shift_Id)
									begin							
										set @updateQuery=@updateQuery+ ' update TA_TBL_PERMANENTSHIFTALLOCATION set DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT='+CONVERT(varchar(20),@Shift_Id)
										set @updateQuery=@updateQuery+ ' WHERE [YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  [MONTH]= ' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = '  + CONVERT(varchar(20), @EMPLOYEEAUTOID )
										 execute(@updateQuery)
										 print(@updateQuery)
									end
									--else
									--begin
									--	select 'shift updation skipped due to same shift'
									--end
								end
								else
								begin
									set @updateQuery=@updateQuery+ ' Insert into TA_TBL_PERMANENTSHIFTALLOCATION(DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT,year,month,Employeeid,Emp_Id,DateShift)'
									set @updateQuery=@updateQuery+ ' values('+Convert(varchar(20),@Shift_Id)+','+ convert(varchar(20), DATEPART(year,@ShiftDate)) + ',' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ','+convert(varchar(20),@EMPLOYEEAUTOID )
									set @updateQuery=@updateQuery+ ',1,'''+CONVERT(varchar(20),getdate())+''')'
									execute(@updateQuery)
								end
								set @updateQuery=''
								DELETE FROM #TEMP
							end
						end
						else
						begin				
							set @ShiftDate=CONVERT(datetime,@Work_Date)
							
							SET @QUERY = '	SELECT (PSA.DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
									WHERE PSA.[YEAR]= ' + CONVERT(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  PSA.[MONTH]= ' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' + CONVERT(varchar(20), @EMPLOYEEAUTOID)
							INSERT INTO #TEMP EXEC(@QUERY)
							SELECT @AllocatedShiftID =ISNULL(SHIFTID,0) FROM #TEMP	
							print (@QUERY)
							set @updateQuery=''
							
							if((select COUNT(*) from #TEMP)>0)
							begin
								if(@AllocatedShiftID=0 or @AllocatedShiftID!=-1)
								begin						
									
									set @updateQuery=@updateQuery+ ' update TA_TBL_PERMANENTSHIFTALLOCATION set DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT='+CONVERT(varchar(20),@Shift_Id)
									set @updateQuery=@updateQuery+ ' WHERE [YEAR]= ' + convert(varchar(20), DATEPART(year,@ShiftDate)) + '  AND  [MONTH]= ' + convert(varchar(20), DATEPART(month,@ShiftDate)) + ' AND EMPLOYEEID = ' + CONVERT(varchar(20), @EMPLOYEEAUTOID)
									print(@updateQuery)
									execute(@updateQuery)
								end
							end
							else
							begin
								set @updateQuery=@updateQuery+ ' Insert into TA_TBL_PERMANENTSHIFTALLOCATION(DAY'+ CONVERT(VARCHAR(10),DATEPART(d,@ShiftDate)) + 'SHIFT,year,month,Employeeid,Emp_Id,DateShift)'
									set @updateQuery=@updateQuery+ ' values('+Convert(varchar(20),@Shift_Id)+','+ convert(varchar(20), DATEPART(year,@ShiftDate)) + ',' +convert(varchar(20), DATEPART(month,@ShiftDate)) + ','+convert(varchar(20),@EMPLOYEEAUTOID )
									set @updateQuery=@updateQuery+ ',1,'''+CONVERT(varchar(20),getdate())+''')'
								execute(@updateQuery)
							end
							set @updateQuery=''
							DELETE FROM #TEMP
						end		
						--select @Shift_Id
					END					
					SET @start=@start+1	
				END					
			END
			ELSE 
			BEGIN
				SELECT	SlNO=RecordID+1,
						Employee_Id, 
						ErrorMsg=Error_Msg
				FROM @ErrorMsg where flag=0
			END
		COMMIT TRAN ImportShiftMaster_Samsung
			SELECT 'Msg:ShiftImportSuccessfully' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = (CASE WHEN ERROR_MESSAGE() LIKE 'Conversion failed%' THEN 'Kindly Check all the field values mentioned correctly in excel sheet. Like Work Type, Day type and Work Date' ELSE ERROR_MESSAGE() END )
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportShiftMaster_Samsung
		RAISERROR(@ErrMsg, 16, @ErrIds, 'Error')
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationReprocess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocationReprocess '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','11442,3480,3482,3483,3490,3500,3503,3537,3538,3539,3657,3665,4441,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457,11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,11470,11471,11472,11473,11474,11475,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486,11487,11488,11489,11490,11491,11492,11493,11494,11495,11496,11497,11498,11499,11500,11501,11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517,11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,11530,11531,11532,11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548,11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578,11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,11592,11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,11605,11606,11607,11608,11609,11610,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622,11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638,11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654,11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670,11671,11672,11673,11674,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685,11686,11687,11688,11689,11690,11691,11692,11693,11694,11695,11696,11697,11698,11699,11700,11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716,11717,11718,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,11741,11742,11743,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776,11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,11791,11792,11793,11794,11795,11796,11797,11798,11799,11800,11801,11802,11803,11804,11805,11806,11807,11808,11809,11810,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821,11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,11835,11836,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850,11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866,11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882,11883,11884,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897,11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913,11914,11915,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928,11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944,11945,11946,11947,11948,11949,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959,11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975,11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,11988,11989,11990,11991,11992,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005,12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021,12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037,12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053,12054,12055,12056,12057,12058,12059,12060,12061,12062,12063,12064,12065,12066,12067,12068,12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084,12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100,12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116,12117,12118,12119,12120,12121,12122,12123,12124,12125,12126,12127,12128,12129,12130,12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146,12147,12148,12149,12150,12151,12152,12153,12154,12155,12156,12157,12158,12159,12160,12161,12162,12163,12164,12165,12166,12167,12168,12169,12170,12171,12172,12173,12174,12175,12176,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188,12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204,12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220,12221,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,12246,12247,12248,12249,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264,12265,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278,12279,12280,12281,12282,12283,12284,12285,12286,12287,12288,12289,12290,12291,12292,12293,12294,12295,12296,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308,12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,12320,12321,12322,12323,12324,12325,12326,12327,12328,12329,12330,12331,12332,12333,12334,12335,12336,12337,12338,12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,12436,12437,12438,12439,12440,12441,12442,12443,12444,12445,12446,12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539,12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600,12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616,12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632,12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,12647,12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663,12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679,12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695,12696,12697,12698,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710,12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726,12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742,12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758,12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774,12775,12776,12777,12778,12779,12780,12781,12782,12783,12784,12785,12786,12787,12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803,12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819,12820,12821,12822,12823,12824,12825,12826,12827,12828,12829,12830,12831,12832,12833,12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849,12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,12862,12863,12864,12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880,12881,12882,12883,12884,12885,12886,12887,12888,12889,12890,12891,12892,12893,12894,12895,12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911,12912,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926,12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942,12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,12957,12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973,12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989,12990,12991,12992,12993,12994,12995,12996,12997,12998,12999,13000,13001,13002,13003,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018,13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,13030,13031,13032,13033,13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049,13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065,13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081,13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097,13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113,13114,13115,13116,13117,13118,13119,13120,13121,13122,13123,13124,13125,13126,13127,13128,13129,13130,13131,13132,13133,13134,13135,13136,13137,13138,13139,13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155,13156,13157,13158,13159,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170,13171,13172,13173,13174,13175,13176,13177,13178,13179,13180,13181,13182,13183,13184,13185,13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201,13202,13203,13204,13205,13206,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216,13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,13228,13229,13230,13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,13241,13242,13243,13244,13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260,13261,13262,13263,13264,13265,13266,13267,13268,13269,13270,13271,13272,13273,13274,13275,13276,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290,13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,13303,13304,13305,13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321,13322,13323,13324,13325,13326,13327,13328,13329,13330,13331,13332,13333,13334,13335,13336,13337,13338,13339,13340,13341,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351,13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382,13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398,13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414,13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430,13431,13432,13433,13434,13435,13436,13437,13438,13439,13440,13441,13442,13443,13444,13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,13458,13459,13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,13471,13472,13473,13474,13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490,13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506,13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522,13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538,13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554,13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570,13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586,13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602,13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618,13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634,13635,13636,13637,13638,13639,13640,13641,13642,13643,13644,13645,13646,13647,13648,13649,13650,13651,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664,13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680,13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696,13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712,13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728,13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744,13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760,13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,13775,13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791,13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807,13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823,13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839,13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855,13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871,13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887,13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903,13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919,13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935,13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951,13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967,13968,13969,13970,13971,13972,13973,13974,13975,13976,13977,13978,13979,13980,13981,13982,13983,13984,13985,13986,13987,13988,13989,13990,13991,13992,13993,13994,13995,13996,13997,13998,13999,14000,14001,14002,14003,14004,14005,14006,14007,14008,14009,14010,14011,14012,14013,14014,14015,14016,14017,14018,14019,14020,14021,14022,14023,14024,14025,14026,14027,14028,14029,14030,14031,14032,14033,14034,14035,14036,14037,14038,14039,14040,14041,14042,14043,14044,14045,14046,14047,14048,14049,14050,14051,14052,14053,14054,14055,14056,14057,14058,14059,14060,14061,14062,14063,14064,14065,14066,14067,14068,14069,14070,14071,14072,14073,14074,14075,14076,14077,14078,14079,14080,14081,14082,14083,14084,14085,14086,14087,14088,14089,14090,14091,14092,14093,14094,14095,14096,14097,14098,14099,14100,14101,14102,14103,14104,14105,14106,14107,14108,14109,14110,14111,14112,14113,14114,14115,14116,14117,14118,14119,14120,14121,14122,14123,14124,14125,14126,14127,14128,14129,14130,14131,14132,14133,14134,14135,14136,14137,14138,14139,14140,14141,14142,14143,14144,14145,14146,14147,14148,14149,14150,14151,14152,14153,14154,14155,14156,14157,14158,14159,14160,14161,14162,14163,14164,14165,14166,14167,14168,14169,14170,14171,14172,14173,14174,14175,14176,14177,14178,14179,14180,14181,14182,14183,14184,14185,14186,14187,14188,14189,14190,14191,14192,14193,14194,14195,14196,14197,14198,14199,14200,14201,14202,14203,14204,14205,14206,14207,14208,14209,14210,14211,14212,14213,14214,14215,14216,14217,14218,14219,14220,14221,14222,14223,14224,14225,14226,14227,14228,14229,14230,14231,14232,14233,14234,14235,14236,14237,14238,14239,14240,14241,14242,14243,14244,14245,14246,14247,14248,14249,14250,14251,14252,14253,14254,14255,14256,14257,14258,14259,14260,14261,14262,14263,14264,14265,14266,14267,14268,14269,14270,14271,14272,14273,14274,14275,14276,14277,14278,14279,14280,14281,14282,14283,14284,14285,14286,14287,14288,14289,14290,14291,14292,14293,14294,14295,14296,14297,14298,14299,14300,14301,14302,14303,14304,14305,14306,14307,14308,14309,14310,14311,14312,14313,14314,14315,14316,14317,14318,14319,14320,14321,14322,14323,14324,14325,14326,14327,14328,14329,14330,14331,14332,14333,14334,14335,14336,14337,14338,14339,14340,14341,14342,14343,14344,14345,14346,14347,14348,14349,14350,14351,14352,14353,14354,14355,14356,14357,14358,14359,14360,14361,14362,14363,14364,14365,14366,14367,14368,14369,14370,14371,14372,14373,14374,14375,14376,14377,14378,14379,14380,14381,14382,14383,14384,14385,14386,14387,14388,14389,14390,14391,14392,14393,14394,14395,14396,14397,14398,14399,14400,14401,14402,14403,14404,14405,14406,14407,14408,14409,14410,14411,14412,14413,14414,14415,14416,14417,14418,14419,14420,14421,14422,14423,14424,14425,14426,14427,14428,14429,14430,14431,14432,14433,14434,14435,14436,14437,14438,14439,14440,14441,14442,14443,14444,14445,14446,14447,14448,14449,14450,14451,14452,14453,14454,14455,14456,14457,14458,14459,14460,14461,14462,14463,14464,14465,14466,14467,14468,14469,14470,14471,14472,14473,14474,14475,14476,14477,14478,14479,14480,14481,14482,14483,14484,14485,14486,14487,14488,14489,14490,14491,14492,14493,14494,14495,14496,14497,14498,14499,14500,14501,14502,14503,14504,14505,14506,14507,14508,14509,14510,14511,14512,14513,14514,14515,14516,14517,14518,14519,14520,14521,14522,14523,14524,14525,14526,14527,14528,14529,14530,14531,14532,14533,14534,14535,14536,14537,14538,14539,14540,14541,14542,14543,14544,14545,14546,14547,14548,14549,14550,14551,14552,14553,14554,14555,14556,14557,14558,14559,14560,14561,14562,14563,14564,14565,14566,14567,14568,14569,14570,14571,14572,14573,14574,14575,14576,14577,14578,14579,14580,14581,14582,14583,14584,14585,14586,14587,14588,14589,14590,14591,14592,14593,14594,14595,14596,14597,14598,14599,14600,14601,14602,14603,14604,14605,14606,14607,14608,14609,14610,14611,14612,14613,14614,14615,14616,14617,14618,14619,14620,14621,14622,14623,14624,14625,14626,14627,14628,14629,14630,14631,14632,14633,14634,14635,14636,14637,14638,14639,14640,14641,14642,14643,14644,14645,14646,14647,14648,14649,14650,14651,14652,14653,14654,14655,14656,14657,14658,14659,14660,14661,14662,14663,14664,14665,14666,14667,14668,14669,14670,14671,14672,14673,14674,14675,14676,14677,14678,14679,14680,14681,14682,14683,14684,14685,14686,14687,14688,14689,14690,14691,14692,14693,14694,14695,14696,14697,14698,14699,14700,14701,14702,14703,14704,14705,14706,14707,14708,14709,14710,14711,14712,14713,14714,14715,14716,14717,14718,14719,14720,14721,14722,14723,14724,14725,14726,14727,14728,14729,14730,14731,14732,14733,14734,14735,14736,14737,14738,14739,14740,14741,14742,14743,14744,14745,14746,14747,14748,14749,14750,14751,14752,14753,14754,14755,14756,14757,14758,14759,14760,14761,14762,14763,14764,14765,14766,14767,14768,14769,14770,14771,14772,14773,14774,14775,14776,14777,14778,14779,14780,14781,14782,14783,14784,14785,14786,14787,14788,14789,14790,14791,14792,14793,14794,14795,14796,14797,14798,14799,14800,14801,14802,14803,14804,14805,14806,14807,14808,14809,14810,14811,14812,14813,14814,14815,14816,14817,14818,14819,14820,14821,14822,14823,14824,14825,14826,14827,14828,14829,14830,14831,14832,14833,14834,14835,14836,14837,14838,14839,14840,14841,14842,14843,14844,14845,14846,14847,14848,14849,14850,14851,14852,14853,14854,14855,14856,14857,14858,14859,14860,14861,14862,14863,14864,14865,14866,14867,14868,14869,14870,14871,14872,14873,14874,14875,14876,14877,14878,14879,14880,14881,14882,14883,14884,14885,14886,14887,14888,14889,14890,14891,14892,14893,14894,14895,14896,14897,14898,14899,14900,14901,14902,14903,14904,14905,14906,14907,14908,14909,14910,14911,14912,14913,14914,14915,14916,14917,14918,14919,14920,14921,14922,14923,14924,14925,14926,14927,14928,14929,14930,14931,14932,14933,14934,14935,14936,14937,14938,14939,14940,14941,14942,14943,14944,14945,14946,14947,14948,14949,14950,14951,14952,14953,14954,14955,14956,14957,14958,14959,14960,14961,14962,14963,14964,14965,14966,14967,14968,14969,14970,14971,14972,14973,14974,14975,14976,14977,14978,14979,14980,14981,14982,14983,14984,14985,14986,14987,14988,14989,14990,14991,14992,14993,14994,14995,14996,14997,14998,14999,15000,15001,15002,15003,15004,15005,15006,15007,15008,15009,15010,15011,15012,15013,15014,15015,15016,15017,15018,15019,15020,15021,15022,15023,15024,15025,15026,15027,15028,15029,15030,15031,15032,15033,15034,15035,15036,15037,15038,15039,15040,15041,15042,15043,15044,15045,15046,15047,15048,15049,15050,15051,15052,15053,15054,15055,15056,15057,15058,15059,15060,15061,15062,15063,15064,15065,15066,15067,15068,15069,15070,15071,15072,15073,15074,15075,15076,15077,15078,15079,15080,15081,15082,15083,15084,15085,15086,15087,15088,15089,15090,15091,15092,15093,15094,15095,15096,15097,15098,15099,15100,15101,15102,15103,15104,15105,15106,15107,15108,15109,15110,15111,15112,15113,15114,15115,15116,15117,15118,15119,15120,15121,15122,15123,15124,15125,15126,15127,15128,15129,15130,15131,15132,15133,15134,15135,15136,15137,15138,15139,15140,15141,15142,15143,15144,15145,15146,15147,15148,15149,15150,15151,15152,15153,15154,15155,15156,15157,15158,15159,15160,15161,15162,15163,15164,15165,15166,15167,15168,15169,15170,15171,15172,15173,15174,15175,15176,15177,15178,15179,15180,15181,15182,15183,15184,15185,15186,15187,15188,15189,15190,15191,15192,15193,15194,15195,15196,15197,15198,15199,15200,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15238,15239,15240,15241,15242,15243,15244,15245,15246,15247,15248,15249,15250,15251,15252,15253,15254,15255,15256,15257,15258,15259,15260,15261,15262,15263,15264,15265,15266,15267,15268,15269,15270,15271,15272,15273,15274,15275,15276,15277,15278,15279,15280,15281,15282,15283,15284,15285,15286,15287,15288,15289,15290,15291,15292,15293,15294,15295,15296,15297,15298,15299,15300,15301,15302,15303,15304,15305,15306,15307,15308,15309,15310,15311,15312,15313,15314,15315,15316,15317,15318,15319,15320,15321,15322,15323,15324,15325,15326,15327,15328,15329,15330,15331,15332,15333,15334,15335,15336,15337,15338,15339,15340,15341,15342,15343,15344,15345,15346,15347,15348,15349,15350,15351,15352,15353,15354,15355,15356,15357,15358,15359,15360,15361,15362,15363,15364,15365,15366,15367,15368,15369,15370,15371,15372,15373,15374,15375,15376,15377,15378,15379,15380,15381,15382,15383,15384,15385,15386,15387,15388,15389,15390,15391,15392,15393,15394,15395,15396,15397,15398,15399,15400,15401,15402,15403,15404,15405,15406,15407,15408,15409,15410,15411,15412,15413,15414,15415,15416,15417,15418,15419,15420,15421,15422,15423,15424,15425,15426,15427,15428,15429,15430,15431,15432,15433,15434,2247,2248,2250,2252,2253,2254,2255,2256,2258,2259,2260,2262,2263,2266,2268,2270,2271,2273,2274,2277,2278,2280,2281,2282,2283,2284,2285,2287,2288,2289,2290,2291,2293,2294,2295,2297,2298,2299,2301,2305,632,3681,706,731,2313,2314,2320,3697,2322,2461,2325,3002,3437,3439,3446,3447,3448'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocationReprocess]  
(   
@FromDate Datetime,  
@ToDate Datetime,  
@EmployeeId varchar(8000)   
)  
AS  
BEGIN
	DECLARE @SwipeCardNo AS nvarchar(20)  
	DECLARE @Employee_Code_Id AS nvarchar(20)  
	DECLARE @dtFromDate as datetime
	CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	(  
		[SwipeCardNo] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempEmployee_Code_Id]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	create table #TempSwipeCardNo(SwipeCardNo nvarchar(20),Employee_Code_Id nvarchar(20)) 
	insert into #TempSwipeCardNo SELECT SwipeCardNo,Employee_Code_Id FROM TA_Tbl_Employee inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id where SwipeCardNo is not null
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
	where Date BETWEEN @FromDate AND @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	set @dtFromDate=@FromDate
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@dtFromDate and Clk_InDate between @dtFromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@dtFromDate and Clk_InDate is null and Clk_OutDate between @dtFromDate and @ToDate
	
	-- below Code DataReprocess CLK Rawdata ReasonId=1 convert the UCT timezone developed by Maria Prasanth on 29th jan 
	Declare @Count int
	Select @Count= isnull(Count(*),0) from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId=1

	if (@Count>0)
		Begin
			
			
			Declare @TempRawdataTbl Table (tempRawId int identity(1,1),CLK_DATE DateTime,CLK_TIME nvarchar(20),CLK_CARDID varchar(20),
			CLK_DEVICEID nvarchar(20),CLK_Id nvarchar(max))

			Insert into @TempRawdataTbl
			Select CLK_DATE,CLK_TIME,CLK_CARDID,CLK_DEVICEID,CLK_ID From TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId=1
			Declare @i int=1

			while(@i<=@Count)
			Begin
				Declare @CLK_Date DateTime
				Declare @Clk_Time nvarchar(20)
				Declare @CLK_CARDID nvarchar(20)
				Declare @CLK_DEVICEID nvarchar(20)
				Declare @CLK_Id nvarchar(20)

				Select @CLK_Date=CLK_DATE,@Clk_Time=CLK_TIME,@CLK_CARDID=CLK_CARDID,@CLK_DEVICEID=CLK_DEVICEID,@CLK_Id=CLK_Id From @TempRawdataTbl where tempRawId=@i

				if((Select Count(*) From TA_tbl_TerminalDatatype TD inner join TA_Tbl_Terminal T on T.TerminalDatatype_ID=TD.TerminalDatatype_ID where T.Terminal_ReaderID=@CLK_DEVICEID and TD.ISUTCTime=1)>0)
				Begin
				
					Declare @UTC_CLKDate dateTime
					Declare @UTC_CLKTime nvarchar(10)

					Select @UTC_CLKDate=UTC_CLKDate,@UTC_CLKTime=UTC_CLKTime From [dbo].[Fn_TA_ConvertTimeZoneDT](@CLK_DATE,@CLK_TIME,@CLK_CARDID)

					update TA_Tbl_Clk_RawData set Clk_Flag =0,Clk_Process = 0,ReasonId=0,CLK_DATE=@UTC_CLKDate,CLK_TIME=@UTC_CLKTime where Clk_Id = @CLK_ID
				End
				Set @i=@i+1
			End
			
		End
		Else
		begin
			UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)
		End


	--UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)  
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' from TA_Tbl_ManualTimeEntry inner join #TempSwipeCardNo on #TempSwipeCardNo.Employee_Code_Id=TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	drop table #TempSwipeCardNo
	drop table  #TempEmployee_Code_Id 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationView]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_RptShiftAllocation '12/17/2007','01/31/2008','','','' 
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By :Kumuthini.L
Created on : 3-Aug-07    
*/  
CREATE      PROCEDURE [dbo].[Proc_TA_ShiftAllocationView] 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(1000), 
 @EmployeeId varchar(50) 
AS  
BEGIN  
  declare @sqlQuery as nvarchar(4000)  
  set @sqlQuery=''  
  set @sqlQuery = 'select  e.Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.UserId,ps.TimeStamp,ps.DateShift from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId where e.Isdeleted=1 and e.employee_Status=1 and e.Report_exclude=0 '
  /*set @sqlQuery = @sqlQuery + ' and((month(dateShift) >= month(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102))) or (month(dateShift) <= month(CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102))))'  
  set @sqlQuery = @sqlQuery + ' and((year(dateShift) >= year(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(11)) + ''', 102))) and (year(dateShift) <= year(CONVERT(DATETIME, ''' + cast(@toDat as nvarchar(11)) + ''', 102))))'  
    */
set @sqlQuery=@sqlQuery + ' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@fromDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, '''+  cast(@fromDat as nvarchar(20)) +''', 102 ))as nvarchar(10)),102) '
set @sqlQuery=@sqlQuery + ' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102)) as nvarchar(20))+''/''+ cast(1 as nvarchar(1)) +''/''+ cast(year(CONVERT(DATETIME, ''' + cast(@ToDat as nvarchar(20)) + ''', 102 ))as nvarchar(10)),102)'
if not(@LevelID='' or @LevelID='0')  
  begin  
   set @sqlQuery = @sqlQuery + ' And (e.levelId IN (' + @LevelID  + '))'  
  End  
if not(@EmployeeName='' or @EmployeeName='0')  
  begin  
   set @sqlQuery = @sqlQuery + 'and (e.Employee_FirstName like ''' + cast(@EmployeeName+'%' as nvarchar(100)) + ''')'  
  end  
if not(@EmployeeId='' or @EmployeeId='0')  
  begin  
   set @sqlQuery = @sqlQuery + 'and (e.Employee_Code_Id = ''' + cast(@EmployeeId as nvarchar(100)) + ''')'  
  end  
  set @sqlQuery = @sqlQuery + ' order by e.Employee_FirstName,ps.Year,ps.Month'   
exec(@sqlQuery)  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_ClockDetails '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]  
(   
	 @FromDate Datetime,  
	 @ToDate Datetime,
	 @LoginEmployeeId varchar(50)
)  
AS  
BEGIN
	DECLARE @SwipeCardNo AS nvarchar(20)  
	DECLARE @Employee_Code_Id AS nvarchar(20)  
	create table #TempSwipeCardNo(SwipeCardNo nvarchar(20)) 
	--#TempSwipeCardNo Indexes    
	/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 05/27/2009 16:28:22 ******/  
	CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	(  
		[SwipeCardNo] ASC  
	) ON [PRIMARY]  
	 --select * from TA_Tbl_TempShiftAllocation
	insert into #TempSwipeCardNo SELECT SwipeCardNo FROM TA_Tbl_Employee
	inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	where SwipeCardNo is not null and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	--Matched Punches
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	drop table #TempSwipeCardNo
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_ManualEntry '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS  
BEGIN
	SET NOCOUNT ON;
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' from TA_Tbl_TempShiftAllocation
	inner join TA_Tbl_Employee on TA_Tbl_TempShiftAllocation.EmpID = TA_Tbl_Employee.Employee_Id
	inner join TA_Tbl_ManualTimeEntry on TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id 
	AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	where TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_ProcessedData '01/01/2011 12:00:00 AM','04/30/2011 12:00:00 AM','1'
--update a set day1shift= 0 from TA_Tbl_PermanentShiftAllocation  a
--inner join TA_Tbl_TempShiftAllocation b on b.EmpID = a.EmployeeId
--inner join TA_Tbl_AutoShiftConfiguration c on c.EmployeeId = a.EmployeeId
--where
--month=8 and year=2019 
--and (c.ShiftId1!=0 or c.ShiftId2!=0 or c.ShiftId3!=0 or c.ShiftId4!=0 or c.ShiftId5!=0)
--Proc_TA_ShiftAllocReprocess_ProcessedData '2022-05-26 00:00:00.000','2022-05-27 00:00:00.000','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS
BEGIN	
	set nocount on
	--Autoshift employee Reprocessing
	--insert into tempreprocess values(@FromDate,@ToDate,@LoginEmployeeId)
	declare @Fromdate1 datetime
	set @Fromdate= @FromDate
	set @Fromdate1= @FromDate
	set @todate= dateadd(DAY,1,@ToDate) 
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	declare @DynamicQuery varchar(max)
	set @DynamicQuery = '';
	while (@Fromdate < @todate)
	Begin
		if (@Fromdate < @todate)
		begin	
			set @day =DATEPART(DAY,@Fromdate)
			SET @YEAR=DATEPART(YEAR,@Fromdate)
			SET @MONTH=DATEPART(MONTH,@Fromdate)	
			set @DynamicQuery=''
			SET @DynamicQuery = @DynamicQuery +' update a set day'+CONVERT(VARCHAR(2),@day)+'shift= 0 from TA_Tbl_PermanentShiftAllocation  a
			inner join TA_Tbl_TempShiftAllocation b on b.EmpID = a.EmployeeId
			inner join TA_Tbl_AutoShiftConfiguration c on c.EmployeeId = a.EmployeeId
			where
			month='+ CONVERT(VARCHAR(2),@month)  +'and year='+CONVERT(VARCHAR(4),@year)+' 
			and (c.ShiftId1!=0 or c.ShiftId2!=0 or c.ShiftId3!=0 or c.ShiftId4!=0 or c.ShiftId5!=0)'
			exec (@DynamicQuery)
			set @Fromdate =  dateadd(DAY,1,@Fromdate)			
			continue;
		End
		else
		begin
			break;
		End
	End
	set @DynamicQuery=''

	-- Non Auto shift employee
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_TempShiftAllocation
	inner join TA_Tbl_Employee on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	inner join TA_Tbl_ProcessedData on TA_Tbl_Employee.SwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id
	where (Date BETWEEN @Fromdate1 AND @ToDate)
	and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_RawData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_RawData '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
-- exec Proc_TA_ShiftAllocReprocess_RawData @FromDate='2024-01-29 00:00:00',@ToDate='2024-01-31 00:00:00',@LoginEmployeeId='1'
-- exec Proc_TA_ShiftAllocReprocess_RawData @FromDate='2024-01-28 00:00:00',@ToDate='2024-02-05 00:00:00',@LoginEmployeeId='1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_RawData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS  
BEGIN
	create table #TempSwipeCardNo(SwipeCardNo nvarchar(20)) 
	----#TempSwipeCardNo Indexes    
	--/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 05/27/2009 16:28:22 ******/  
	CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	(  
	 [SwipeCardNo] ASC  
	) ON [PRIMARY]  
	-- --select * from TA_Tbl_TempShiftAllocation
	insert into #TempSwipeCardNo SELECT SwipeCardNo FROM TA_Tbl_Employee 
	inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	where SwipeCardNo is not null and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	-- below Code DataReprocess CLK Rawdata ReasonId=1 convert the UCT timezone developed by Maria Prasanth on 29th jan 
	Declare @Count int
	Select @Count= isnull(Count(*),0) from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId=1

	if (@Count>0)
		Begin
			
			
			Declare @TempRawdataTbl Table (tempRawId int identity(1,1),CLK_DATE DateTime,CLK_TIME nvarchar(20),CLK_CARDID varchar(20),
			CLK_DEVICEID nvarchar(20),CLK_Id nvarchar(max))

			Insert into @TempRawdataTbl
			Select CLK_DATE,CLK_TIME,CLK_CARDID,CLK_DEVICEID,CLK_ID From TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId=1
			Declare @i int=1

			while(@i<=@Count)
			Begin
				Declare @CLK_Date DateTime
				Declare @Clk_Time nvarchar(20)
				Declare @CLK_CARDID nvarchar(20)
				Declare @CLK_DEVICEID nvarchar(20)
				Declare @CLK_Id nvarchar(20)

				Select @CLK_Date=CLK_DATE,@Clk_Time=CLK_TIME,@CLK_CARDID=CLK_CARDID,@CLK_DEVICEID=CLK_DEVICEID,@CLK_Id=CLK_Id From @TempRawdataTbl where tempRawId=@i

				if((Select Count(*) From TA_tbl_TerminalDatatype TD inner join TA_Tbl_Terminal T on T.TerminalDatatype_ID=TD.TerminalDatatype_ID where T.Terminal_ReaderID=@CLK_DEVICEID and TD.ISUTCTime=1)>0)
				Begin
				
					Declare @UTC_CLKDate dateTime
					Declare @UTC_CLKTime nvarchar(10)

					Select @UTC_CLKDate=UTC_CLKDate,@UTC_CLKTime=UTC_CLKTime From [dbo].[Fn_TA_ConvertTimeZoneDT](@CLK_DATE,@CLK_TIME,@CLK_CARDID)

					update TA_Tbl_Clk_RawData set Clk_Flag =0,Clk_Process = 0,ReasonId=0,CLK_DATE=@UTC_CLKDate,CLK_TIME=@UTC_CLKTime where Clk_Id = @CLK_ID
				End
				Set @i=@i+1
			End
			
		End
		Else
		begin
			UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)
		End



	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0,ReasonId = 0 FROM TA_Tbl_Employee 
	inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	inner join TA_Tbl_Clk_RawData on TA_Tbl_Employee.SwipeCardNo = TA_Tbl_Clk_RawData.Clk_CardId 
	AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId!=6
	where TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	-- and isnull(ReasonId,0)=0
	--drop table #TempSwipeCardNo
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsById]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
	Procedure Name : Proc_TA_ShiftDetailsById  
	Description : Get the Shift Details by passing Shift Id
	Tables Included : TA_Tbl_Shift   
	Created By : Janakaraj  
	Created On : 3-Sep-07  
	Modified By : Kumuthini.L
	Modified On :19-Feb-08
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_ShiftDetailsById]
(
@ShiftId INT
)
AS
declare @LevelId as int
BEGIN
	set @LevelId=(select Level_Id FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftId)
	if(@LevelId!=0)
	BEGIN
		SELECT TA_Tbl_Shift.*, TA_Tbl_Leveldetails.Name,CategoryName=(select top 1 CategoryName from TA_Tbl_Category where CategoryId=empCategory) FROM TA_Tbl_Shift 
		INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_Shift.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE Shift_Id=@ShiftId
	END
	ELSE
	BEGIN
		SELECT TA_Tbl_Shift.*, '' as Name,CategoryName=(select top 1 CategoryName from TA_Tbl_Category where CategoryId=empCategory) FROM TA_Tbl_Shift 
		WHERE Shift_Id=@ShiftId
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsByIdForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Exec Proc_TA_ShiftDetailsByIdForService 4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftDetailsByIdForService]
	-- Add the parameters for the stored procedure here
	@intShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select Shift_Id, Level_Id, Shift_Name, Shift_ShortName, Shift_Description, Shift_StartTime, Shift_EndTime, Shift_FirstHalf_StartTime, 
	Shift_FirstHalf_EndTime, Shift_SecondHalf_StartTime, Shift_SecondHalf_EndTime, Shift_GraceInTime, Shift_GraceOutTime, Shift_BreakStartTime1, 
	Shift_BreakEndTime1, Shift_BreakStartTime2, Shift_BreakEndTime2, Shift_BreakStartTime3, Shift_BreakEndTime3, Shift_MinTimeOT, Shift_MaxTimeOT, 
	Shift_WorkingDay_OverTime, Shift_TotalWorkingHours, Isdeleted, Emp_ID, Shift_FirstHalfWorkingHours, Shift_SecondHalfWorkingHours, IsBreakDeducted, 
	DefaultShift, ShiftType, CreatedDate, ModifiedDate,[24HrsShift],isStraightShift,StraightPresentTime,
	BreakMins=substring(BreakHours,0,CHARINDEX(':',BreakHours))*60+substring(BreakHours,CHARINDEX(':',BreakHours)+1,LEN(BreakHours))
    From TA_Tbl_Shift Where Shift_Id =@intShiftId and Isdeleted = 0
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_ClockDetails '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
    Declare @Index int
    Set @Index = 0;
    EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	Exec sp_xml_removedocument @Index 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftAllocReprocess_ManualEntry '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
	SET NOCOUNT ON;
    Declare @Index int
    Set @Index = 0;
    EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N'  
	from OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ManualTimeEntry on TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id = TA_Tbl_Employee.Employee_Code_Id
	AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	Exec sp_xml_removedocument @Index 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml,
 @ShiftId int    
)  
AS  
BEGIN
 Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	DELETE FROM TA_Tbl_ProcessedData FROM 
	OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = xm.EmployeeAutoID
	inner join TA_Tbl_ProcessedData on TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo
	where TA_Tbl_ProcessedData.Date BETWEEN @FromDate AND @ToDate and TA_Tbl_ProcessedData.Shift_Id = @ShiftId
	Exec sp_xml_removedocument @Index  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_ShiftReAlloc_Reprocess_RawData '04/01/2011 12:00:00 AM','12/31/2011 12:00:00 AM','1'
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from  
	OpenXML(@Index, '/DocumentElement/Table') With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = xm.EmployeeAutoID
	inner join TA_Tbl_Clk_RawData on TA_Tbl_Clk_RawData.CLK_CARDID = TA_Tbl_Employee.SwipeCardNo
	AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) 
  Exec sp_xml_removedocument @Index 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	Update the shift Id for shift re-allocation
-- Proc_TA_ShiftReAllocation 'Day1Shift=17,Day2Shift=17,Day3Shift=17,Day4Shift=17,Day5Shift=17,Day6Shift=17,Day7Shift=17,Day8Shift=17,Day9Shift=17,Day10Shift=17,Day11Shift=17,Day12Shift=17,Day13Shift=17,Day14Shift=17,Day15Shift=17',2011,4,1,'<DocumentElement><Table><EmployeeAutoID>14594</EmployeeAutoID></Table></DocumentElement>'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAllocation]
(
@ColName varchar(3000),
@Year int,
@Month int,
@loginEmployeeId varchar(50),
@xml xml
)
AS
BEGIN
create table #Tempemployee (EmployeeAutoId bigint)
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
  insert into #Tempemployee select xm.EmployeeAutoID
  from OpenXML(@Index, '/DocumentElement/Table')
  With (EmployeeAutoID Bigint 'EmployeeAutoID') As xm 
  Exec sp_xml_removedocument @Index
  DECLARE @sSql  varchar(8000)
  SET @sSql = 'UPDATE TA_Tbl_PermanentShiftAllocation SET  ' + @ColName + '' 
  SET @sSql = @sSql + ' from TA_Tbl_PermanentShiftAllocation PS inner join #Tempemployee TE on TE.EmployeeAutoId = PS.EmployeeId '
  SET @sSql = @sSql + ' where [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ''
  exec(@sSql)
  DECLARE @sSql1  varchar(8000)
  SET @sSql1 = 'UPDATE TA_Tbl_TemporaryShiftAllocation SET  ' + @ColName + '' 
  SET @sSql1 = @sSql1 + ' from TA_Tbl_TemporaryShiftAllocation TS inner join  #Tempemployee TE on TE.EmployeeAutoId = TS.EmployeeId '
  SET @sSql1 = @sSql1 + ' where [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ''
  exec(@sSql1)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftRequisitionApprovalUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_ShiftRequisitionApprovalUpdate]


@ShiftRequisitionID int,

@MonthDate datetime ='',
@Tag int='1',
@Status nvarchar(100) =''
AS
BEGIN
	
	declare @Month nvarchar(10), @Year nvarchar(10)
	Set @Month= Month(@MonthDate)
	Set  @Year= Year(@MonthDate)

	--Declare   @DAY1 int, @DAY2 int, @DAY3 int, @DAY4 int, @DAY5 int, @DAY6 int, @DAY7 int, @DAY8 int, @DAY9 int, @DAY10 int, 
	--@DAY11 int, @DAY12 int, @DAY13 int, @DAY14 int, @DAY15 int, @DAY16 int, @DAY17 int, @DAY18 int, @DAY19 int, 
 --  @DAY20 int, @DAY21 int, @DAY22 int, @DAY23 int, @DAY24 int, @DAY25 int, @DAY26 int, @DAY27 int, @DAY28 int, @DAY29 int, @DAY30 int, @DAY31 int


	 Update TA_Tbl_ShiftRequisition Set Status =@Status where ShiftRequisitionID=@ShiftRequisitionID

	 if (@Tag=1)
	 begin 
	 Update  TA_Tbl_PermanentShiftAllocation set 
     TA_Tbl_PermanentShiftAllocation.Day1Shift= case when TA_Tbl_ShiftRequisition.DAY1=''then TA_Tbl_PermanentShiftAllocation.Day1Shift  else TA_Tbl_ShiftRequisition.DAY1 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day2Shift= case when TA_Tbl_ShiftRequisition.DAY2='' then TA_Tbl_PermanentShiftAllocation.Day2Shift else  TA_Tbl_ShiftRequisition.DAY2 end ,
	 TA_Tbl_PermanentShiftAllocation.Day3Shift= case when TA_Tbl_ShiftRequisition.DAY3='' then TA_Tbl_PermanentShiftAllocation.Day3Shift else TA_Tbl_ShiftRequisition.DAY3 end ,
	 TA_Tbl_PermanentShiftAllocation.Day4Shift= case when TA_Tbl_ShiftRequisition.DAY4= '' then TA_Tbl_PermanentShiftAllocation.Day4Shift else TA_Tbl_ShiftRequisition.DAY4 end,
	 TA_Tbl_PermanentShiftAllocation.Day5Shift= case when TA_Tbl_ShiftRequisition.DAY5=''then TA_Tbl_PermanentShiftAllocation.Day5Shift else TA_Tbl_ShiftRequisition.DAY5 end,
	 TA_Tbl_PermanentShiftAllocation.Day6Shift= case when TA_Tbl_ShiftRequisition.DAY6=''then TA_Tbl_PermanentShiftAllocation.Day6Shift else TA_Tbl_ShiftRequisition.DAY6 end ,
	 TA_Tbl_PermanentShiftAllocation.Day7Shift=case when TA_Tbl_ShiftRequisition.DAY7=''then TA_Tbl_PermanentShiftAllocation.Day7Shift else TA_Tbl_ShiftRequisition.DAY7 end ,
	 TA_Tbl_PermanentShiftAllocation.Day8Shift=case when  TA_Tbl_ShiftRequisition.DAY8=''then TA_Tbl_PermanentShiftAllocation.Day8Shift else TA_Tbl_ShiftRequisition.DAY8 end ,
	 TA_Tbl_PermanentShiftAllocation.Day9Shift=case when TA_Tbl_ShiftRequisition.DAY9 =''then TA_Tbl_PermanentShiftAllocation.Day9Shift else TA_Tbl_ShiftRequisition.DAY9 end ,
	 TA_Tbl_PermanentShiftAllocation.Day10Shift= case when TA_Tbl_ShiftRequisition.DAY10=''then TA_Tbl_PermanentShiftAllocation.Day10Shift else TA_Tbl_ShiftRequisition.DAY10 end ,
	 TA_Tbl_PermanentShiftAllocation.Day11Shift=case when TA_Tbl_ShiftRequisition.DAY11=''then TA_Tbl_PermanentShiftAllocation.Day11Shift else TA_Tbl_ShiftRequisition.DAY11 end ,
	 TA_Tbl_PermanentShiftAllocation.Day12Shift=case when TA_Tbl_ShiftRequisition.DAY12=''then TA_Tbl_PermanentShiftAllocation.Day12Shift  else TA_Tbl_ShiftRequisition.DAY12 end ,
	 TA_Tbl_PermanentShiftAllocation.Day13Shift= case when TA_Tbl_ShiftRequisition.DAY13=''then TA_Tbl_PermanentShiftAllocation.Day13Shift else TA_Tbl_ShiftRequisition.DAY13  end ,
	 TA_Tbl_PermanentShiftAllocation.Day14Shift=case when TA_Tbl_ShiftRequisition.DAY14=''then TA_Tbl_PermanentShiftAllocation.Day14Shift else TA_Tbl_ShiftRequisition.DAY14 end ,
	 TA_Tbl_PermanentShiftAllocation.Day15Shift=case when TA_Tbl_ShiftRequisition.DAY15=''then TA_Tbl_PermanentShiftAllocation.Day15Shift else TA_Tbl_ShiftRequisition.DAY15 end ,
	 TA_Tbl_PermanentShiftAllocation.Day16Shift=case when TA_Tbl_ShiftRequisition.DAY16=''then TA_Tbl_PermanentShiftAllocation.Day16Shift else TA_Tbl_ShiftRequisition.DAY16 end ,
	 TA_Tbl_PermanentShiftAllocation.Day17Shift=case when TA_Tbl_ShiftRequisition.DAY17=''then  TA_Tbl_PermanentShiftAllocation.Day17Shift else TA_Tbl_ShiftRequisition.DAY17 end ,
	 TA_Tbl_PermanentShiftAllocation.Day18Shift=case when TA_Tbl_ShiftRequisition.DAY18=''then TA_Tbl_PermanentShiftAllocation.Day18Shift else TA_Tbl_ShiftRequisition.DAY18 end ,
	 TA_Tbl_PermanentShiftAllocation.Day19Shift=case when TA_Tbl_ShiftRequisition.DAY19=''then TA_Tbl_PermanentShiftAllocation.Day19Shift else TA_Tbl_ShiftRequisition.DAY19 end ,
	 TA_Tbl_PermanentShiftAllocation.Day20Shift=case when TA_Tbl_ShiftRequisition.DAY20=''then TA_Tbl_PermanentShiftAllocation.Day20Shift else TA_Tbl_ShiftRequisition.DAY20 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day21Shift=case when TA_Tbl_ShiftRequisition.DAY21 =''then TA_Tbl_PermanentShiftAllocation.Day21Shift else TA_Tbl_ShiftRequisition.DAY21 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day22Shift=case when TA_Tbl_ShiftRequisition.DAY22=''then TA_Tbl_PermanentShiftAllocation.Day22Shift else TA_Tbl_ShiftRequisition.DAY22 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day23Shift=case when TA_Tbl_ShiftRequisition.DAY23=''then TA_Tbl_PermanentShiftAllocation.Day23Shift else TA_Tbl_ShiftRequisition.DAY23 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day24Shift=case when TA_Tbl_ShiftRequisition.DAY24=''then TA_Tbl_PermanentShiftAllocation.Day24Shift else TA_Tbl_ShiftRequisition.DAY24 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day25Shift=case when TA_Tbl_ShiftRequisition.DAY25=''then TA_Tbl_PermanentShiftAllocation.Day25Shift  else TA_Tbl_ShiftRequisition.DAY25 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day26Shift=case when TA_Tbl_ShiftRequisition.DAY26=''then TA_Tbl_PermanentShiftAllocation.Day26Shift else TA_Tbl_ShiftRequisition.DAY26 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day27Shift=case when TA_Tbl_ShiftRequisition.DAY27=''then TA_Tbl_PermanentShiftAllocation.Day27Shift else TA_Tbl_ShiftRequisition.DAY27 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day28Shift=case when TA_Tbl_ShiftRequisition.DAY28=''then TA_Tbl_PermanentShiftAllocation.Day28Shift else TA_Tbl_ShiftRequisition.DAY28 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day29Shift=case when TA_Tbl_ShiftRequisition.DAY29=''then TA_Tbl_PermanentShiftAllocation.Day29Shift else TA_Tbl_ShiftRequisition.DAY29 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day30Shift=case when TA_Tbl_ShiftRequisition.DAY30=''then TA_Tbl_PermanentShiftAllocation.Day30Shift else TA_Tbl_ShiftRequisition.DAY30 end  ,
	 TA_Tbl_PermanentShiftAllocation.Day31Shift=case when TA_Tbl_ShiftRequisition.DAY31=''then TA_Tbl_PermanentShiftAllocation.Day31Shift else TA_Tbl_ShiftRequisition.DAY31 end 
 from TA_Tbl_PermanentShiftAllocation 
 inner Join TA_Tbl_ShiftRequisition on TA_Tbl_ShiftRequisition.EmployeeId = TA_Tbl_ShiftRequisition.EmployeeID
 Where ShiftRequisitionID=@ShiftRequisitionID  and TA_Tbl_PermanentShiftAllocation.year = @Year 
 and TA_Tbl_PermanentShiftAllocation.month = @Month
	 end

	 


END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftRequisitionSelectGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_ShiftRequisitionSelectGrid]
 @CompanyID int =24,
 @EmployeeCodeID int ='65'
AS
BEGIN

--Select * from TA_Tbl_DateandTimeFormat
	
declare @EmployeeCode nvarchar(100) , @DateFormate nvarchar(100),@FromatCode int 
    set @EmployeeCode =(select TA_Tbl_Employee.Employee_Id from TA_Tbl_Employee 
	where Employee_Id= Case when  @EmployeeCodeID !='1' then @EmployeeCodeID else ' ' end )
	print @EmployeeCode
	Select @DateFormate=DateFormat from TA_Tbl_DateandTimeFormat
	print @DateFormate

	if (@DateFormate ='MM/dd/yyyy')
	begin 
	print @DateFormate
	 set @FromatCode =110
	end 
	else if (@DateFormate ='dd-MMM-yyyy')
	 begin
	 print @DateFormate

	 set @FromatCode =106
	 end 
	 else if (@DateFormate ='dd/MM/yyyy')
	 begin 
	 print @DateFormate
	 set @FromatCode =105
	 end 

	Select ShiftRequisitionID,TA_Tbl_Employee.Employee_Code_Id,EmployeeID, 
	TA_Tbl_Employee.Employee_FirstName+TA_Tbl_Employee.Employee_MiddleName+TA_Tbl_Employee.Employee_LastName as EmployeeName,
	Convert(nvarchar, RequisitionDate,@FromatCode) as RequisitionDate, Status, TA_Tbl_ShiftRequisition.Timestamp, 
	case when TA_Tbl_ShiftRequisition.DAY1='' or TA_Tbl_ShiftRequisition.DAY1='NA' or TA_Tbl_ShiftRequisition.DAY1='NA' or TA_Tbl_ShiftRequisition.DAY1='NA' then TA_Tbl_ShiftRequisition.DAY1 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY1) end as DAY1, 
	case when TA_Tbl_ShiftRequisition.DAY2='' or TA_Tbl_ShiftRequisition.DAY2='NA' then TA_Tbl_ShiftRequisition.DAY2 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY2) end as DAY2,
	case when TA_Tbl_ShiftRequisition.DAY3='' or TA_Tbl_ShiftRequisition.DAY3='NA' then TA_Tbl_ShiftRequisition.DAY3 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY3) end as DAY3,
	case when TA_Tbl_ShiftRequisition.DAY4='' or TA_Tbl_ShiftRequisition.DAY4='NA' then TA_Tbl_ShiftRequisition.DAY4 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY4) end as DAY4,
	case when TA_Tbl_ShiftRequisition.DAY5='' or TA_Tbl_ShiftRequisition.DAY5='NA' then TA_Tbl_ShiftRequisition.DAY5 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY5) end as DAY5, 
	case when TA_Tbl_ShiftRequisition.DAY6='' or TA_Tbl_ShiftRequisition.DAY6='NA' then TA_Tbl_ShiftRequisition.DAY6 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY6) end as DAY6,
	case when TA_Tbl_ShiftRequisition.DAY7='' or TA_Tbl_ShiftRequisition.DAY7='NA' then TA_Tbl_ShiftRequisition.DAY7 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY7) end as DAY7,
	case when TA_Tbl_ShiftRequisition.DAY8='' or TA_Tbl_ShiftRequisition.DAY8='NA' then TA_Tbl_ShiftRequisition.DAY8 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY8) end as DAY8, 
	case when TA_Tbl_ShiftRequisition.DAY9='' or TA_Tbl_ShiftRequisition.DAY9='NA' then TA_Tbl_ShiftRequisition.DAY9 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY9) end as DAY9,
	case when TA_Tbl_ShiftRequisition.DAY10='' or TA_Tbl_ShiftRequisition.DAY10='NA' then TA_Tbl_ShiftRequisition.DAY10 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY10) end as DAY10,
	case when TA_Tbl_ShiftRequisition.DAY11='' or TA_Tbl_ShiftRequisition.DAY11='NA' then TA_Tbl_ShiftRequisition.DAY11 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY11) end as DAY11,
	case when TA_Tbl_ShiftRequisition.DAY12='' or TA_Tbl_ShiftRequisition.DAY12='NA' then TA_Tbl_ShiftRequisition.DAY12 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY12) end as DAY12,
	case when TA_Tbl_ShiftRequisition.DAY13='' or TA_Tbl_ShiftRequisition.DAY13='NA' then TA_Tbl_ShiftRequisition.DAY13 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY13) end as DAY13,
	case when TA_Tbl_ShiftRequisition.DAY14='' or TA_Tbl_ShiftRequisition.DAY14='NA' then TA_Tbl_ShiftRequisition.DAY14 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY14) end as DAY14,
	case when TA_Tbl_ShiftRequisition.DAY15='' or TA_Tbl_ShiftRequisition.DAY15='NA' then TA_Tbl_ShiftRequisition.DAY15 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY15) end as DAY15,
	case when TA_Tbl_ShiftRequisition.DAY16='' or TA_Tbl_ShiftRequisition.DAY16='NA' then TA_Tbl_ShiftRequisition.DAY16 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY16) end as DAY16, 
	case when TA_Tbl_ShiftRequisition.DAY17='' or TA_Tbl_ShiftRequisition.DAY17='NA' then TA_Tbl_ShiftRequisition.DAY17 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY17) end as DAY17, 
	case when TA_Tbl_ShiftRequisition.DAY18='' or TA_Tbl_ShiftRequisition.DAY18='NA' then TA_Tbl_ShiftRequisition.DAY18 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY18) end as DAY18, 
	case when TA_Tbl_ShiftRequisition.DAY19='' or TA_Tbl_ShiftRequisition.DAY19='NA' then TA_Tbl_ShiftRequisition.DAY19 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY19) end as DAY19, 
	case when TA_Tbl_ShiftRequisition.DAY20='' or TA_Tbl_ShiftRequisition.DAY20='NA' then TA_Tbl_ShiftRequisition.DAY20 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY20) end as DAY20,
	case when TA_Tbl_ShiftRequisition.DAY21='' or TA_Tbl_ShiftRequisition.DAY21='NA' then TA_Tbl_ShiftRequisition.DAY21 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY21) end as DAY21,
	case when TA_Tbl_ShiftRequisition.DAY22='' or TA_Tbl_ShiftRequisition.DAY22='NA' then TA_Tbl_ShiftRequisition.DAY22 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY22) end as DAY22,
	case when TA_Tbl_ShiftRequisition.DAY23='' or TA_Tbl_ShiftRequisition.DAY23='NA' then TA_Tbl_ShiftRequisition.DAY23 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY23) end as DAY23,
	case when TA_Tbl_ShiftRequisition.DAY24='' or TA_Tbl_ShiftRequisition.DAY24='NA' then TA_Tbl_ShiftRequisition.DAY24 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY24) end as DAY24, 
	case when TA_Tbl_ShiftRequisition.DAY25='' or TA_Tbl_ShiftRequisition.DAY25='NA' then TA_Tbl_ShiftRequisition.DAY25 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY25) end as DAY25,
	case when TA_Tbl_ShiftRequisition.DAY26='' or TA_Tbl_ShiftRequisition.DAY26='NA' then TA_Tbl_ShiftRequisition.DAY26 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY26) end as DAY26,
	case when TA_Tbl_ShiftRequisition.DAY27='' or TA_Tbl_ShiftRequisition.DAY27='NA' then TA_Tbl_ShiftRequisition.DAY27 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY27) end as DAY27,
	case when TA_Tbl_ShiftRequisition.DAY28='' or TA_Tbl_ShiftRequisition.DAY28='NA' then TA_Tbl_ShiftRequisition.DAY28 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY28) end as DAY28,
	case when TA_Tbl_ShiftRequisition.DAY29='' or TA_Tbl_ShiftRequisition.DAY29='NA' then TA_Tbl_ShiftRequisition.DAY29 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY29) end as DAY29,
	case when TA_Tbl_ShiftRequisition.DAY30='' or TA_Tbl_ShiftRequisition.DAY30='NA' then TA_Tbl_ShiftRequisition.DAY30 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY30) end as DAY30,
	case when TA_Tbl_ShiftRequisition.DAY31='' or TA_Tbl_ShiftRequisition.DAY31='NA' then TA_Tbl_ShiftRequisition.DAY31 else (Select Shift_ShortName from TA_Tbl_Shift where Shift_Id = TA_Tbl_ShiftRequisition.DAY31) end  as DAY31,
	CompanyID 
	from TA_Tbl_ShiftRequisition 
	inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = TA_Tbl_ShiftRequisition.EmployeeID
	inner join TA_Tbl_Usergroup on TA_Tbl_Usergroup.groupId = TA_Tbl_Employee.UserGroup_Id
	where  TA_Tbl_Employee.Employee_Id = case when  @EmployeeCode !='1'then  @EmployeeCode else EmployeeID end 

	order by TA_Tbl_ShiftRequisition.ShiftRequisitionID desc

	--Select * from TA_Tbl_Shift
	--Select * from TA_Tbl_PermanentShiftAllocation
	
	--select TA_Tbl_Employee.Employee_Id,* from TA_Tbl_Employee where Employee_Code_Id= 'tct0003'
	--select *  from TA_Tbl_ShiftRequisition where EmployeeID = 'tct0001'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftRequsitionApprovalShow]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[Proc_TA_ShiftRequsitionApprovalShow]
@Employee_Id int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    Select TA_Tbl_Usergroup.groupName from TA_Tbl_Employee 
inner join TA_Tbl_Usergroup on TA_Tbl_Usergroup.groupId = TA_Tbl_Employee.UserGroup_Id
where TA_Tbl_Employee.Employee_Id = @Employee_Id

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting all Companies shift Setting details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]
	-- Add the parameters for the stored procedure here		
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MaxHoursBeforeShift,MaxHoursAfterShift,WeeklyOffStartHours,CompanyId,IgnoreDuplicatePunch,PunchInterval,MaxHoursBeforeShift_24HrsShift,WeeklyOffStartHours_24HrsShift FROM TA_Tbl_ShiftSettings
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftwiseAttendanceReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_ShiftwiseAttendanceReport 2,1,'2023-03-01 00:00:00'
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_ShiftwiseAttendanceReport]
	-- Add the parameters for the stored procedure here
	@ShiftId int,
	@level_Id int,
	@Date nvarchar(20)
AS
BEGIN

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	SET NOCOUNT ON;
	Declare @ShiftStartTime varchar(20)
	Declare @ShiftEndTime varchar(20)
	Declare @MaxHourBeforeShift DateTime
	
	
	--Set @Date=Convert(datetime,@Date,108)

	--Select @Date


    --Insert statements for procedure here
	--Select * From TA_Tbl_ShiftSettings

	Declare @shiftStarttimeMinutes int
	Declare @shiftStartMinutes int

	Select @shiftStarttimeMinutes=SubString(Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)),0,CHARINDEX(':',Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)))),@ShiftEndTime=Shift_EndTime fROM TA_Tbl_Shift where Level_Id=@level_Id and Shift_Id=@ShiftId

	Select @shiftStartMinutes=( @shiftStarttimeMinutes*60 + SubString(Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)),CHARINDEX(':',Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)))+1,LEN(Shift_StartTime)) -
	substring(MaxHoursBeforeShift,0,CHARINDEX(':',MaxHoursBeforeShift))*60+substring(MaxHoursBeforeShift,CHARINDEX(':',MaxHoursBeforeShift)+1,LEN(MaxHoursBeforeShift)) ) from TA_Tbl_Shift Inner Join TA_Tbl_ShiftSettings on CompanyId=Level_Id where Shift_Id=@ShiftId and CompanyId=@level_Id

	Select @ShiftStartTime=(Case when @shiftStartMinutes>12*60 then Convert(varchar(5),DateAdd(Minute,@shiftStartMinutes,'00:00:00'),108) +' '+'PM' Else Convert(varchar(5),DateAdd(Minute,@shiftStartMinutes,'00:00:00'),108) +' '+'AM' End)

    --  Select the Employee Id Based 
	
	Create Table #TblEmployeeID (EmployeeID int,EmployeeCodeId varchar(20),InDate DateTime)

	insert into #TblEmployeeID
	Select Employee_Id,Employee_Code_Id,Clk_InDate From TA_Tbl_ClockDetails inner join TA_Tbl_Employee on SwipeCardNo=Clk_EmpId where Clk_InTime>= CONVERT(DateTime,@ShiftStartTime) and Clk_InDate=@Date and Clk_InTime<=Convert(DateTime,@ShiftEndTime) and Clk_Remarks!='1'


	Declare @ShiftDate varchar(10)
	Set @ShiftDate='Day'+Convert(varchar(10),DAY(@Date))+'Shift'


	-- Current Shift Employee Details

	Declare @query varchar(200)

    set @query='Select (Day'+CONVERT(varchar(20),Day(@Date))+'Shift),Emp.EmployeeCodeId from TA_Tbl_PermanentShiftAllocation PS inner Join #TblEmployeeID Emp on Emp.EmployeeID=PS.EmployeeId  where Year=Year(Emp.InDate) and Month=Month(Emp.InDate)'

    Declare @TblCurrentDayShiftID as Table (Cur_shiftID int,EmpID varchar(20))

	Insert into @TblCurrentDayShiftID(Cur_shiftID,EmpID) Exec(@query)

	Declare @TblCurretShiftEmpDetails as Table(AllocatedshiftId int,shiftName varchar(20),EmployeeCodeId varchar(20),InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))
	
	Insert into @TblCurretShiftEmpDetails
	Select S.shift_Id,S.Shift_Name,PD.Employee_Code_Id As Actual_Allocated_Shift,PD.InTime,isNull(PD.OutTime,'00:00'),PD.FNAttendanceCode,PD.ANAttendanceCode,PD.IsOnduty,PD.PermissionHrs,PD.LeaveStatus
	From TA_Tbl_ProcessedData PD Left Join TA_Tbl_Shift S on S.Shift_Id =PD.Shift_Id Left Join @TblCurrentDayShiftID TDS on TDS.EmpID=PD.Employee_Code_Id where Date=@Date and PD.Shift_Id=@ShiftId

	
	-- Exception Entry in Shift

	-- Previous Shift Day Not in Night shift Employee ID get the Temporary Table
	
	Declare @PreviousDate DateTime
	
	set @PreviousDate=DATEADD(day,-1,@Date)

	Declare @TblNightShift as Table (shift_Id int)

	Declare @TblClockDetails as Table (EmployeeId int,EmployeeCodeId varchar(20),InDate DateTime,InTime DateTime,OutDate DateTime, OutTime DateTime)

	insert into @TblClockDetails
	Select Employee_Id,Employee_Code_Id,Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime From TA_Tbl_ClockDetails inner join TA_Tbl_Employee on SwipeCardNo=Clk_EmpId where Clk_InTime>= CONVERT(DateTime,@ShiftStartTime) and Clk_InDate=@Date and Clk_InTime<=Convert(DateTime,@ShiftEndTime) and Clk_Remarks!='1'

	insert into @TblNightShift
	Select Shift_Id From TA_Tbl_Shift where Convert(DateTime,Shift_StartTime)<Convert(Datetime,'08:00 PM')

	Declare @TblProcessDate As Table (EmpCodeId varchar(20),PrevShiftId int,Attendance varchar(20))

	--Select * From @TblClockDetails


	Declare @TblDiffShiftEmpDetails as Table(AllocatedshiftId int,shiftName varchar(20),EmployeeCodeId varchar(20),InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))


	insert into @TblProcessDate 
	Select PD.Employee_Code_Id,PD.Shift_Id,PD.Attendance From TA_Tbl_ProcessedData PD Left Join #TblEmployeeID TE on TE.EmployeeCodeId=PD.Employee_Code_Id Left Join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id where  Date=@PreviousDate and PD.Shift_Id IN (Select shift_Id From @TblNightShift)
	
	insert into @TblDiffShiftEmpDetails
	Select shift_Id,Shift_Name,EmpID,CONVERT(VARCHAR(5), InTime, 108) As InTime,isNull(Convert(varchar(10),OutTime,108),'00:00')As OutTime,Case when InTime!='' then 'Present'Else 'Absent' End As FirstSession,Case when OutTime!='' then 'Present'Else 'Absent' End As SecondSession,'','',''
	From @TblCurrentDayShiftID inner Join TA_Tbl_Shift on Shift_Id=Cur_shiftID Inner join @TblClockDetails on EmployeeCodeId=EmpID  where Shift_Id !=@ShiftId

	Declare @TblEmployeShiftDetail As Table (shiftId int,ShiftName varchar(200),Actual_Allocated_Shift varchar(20),From_Other_Shift varchar(20),
	InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),
	Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))
	
	insert into @TblEmployeShiftDetail(shiftId,ShiftName,Actual_Allocated_Shift,From_Other_Shift
	,InTime,OutTime,FirstSession,SecondSession,Onduty,Permissionhrs,IsLeave)
	Select AllocatedshiftId,shiftName,Case when AllocatedshiftId=@ShiftId then EmployeeCodeId Else ' ' End,Case when AllocatedshiftId!=@ShiftId then EmployeeCodeId Else ' ' End
	,InTime,ISNULL(OutTime,' '),FirstSession,SecondSession
	,Case when AllocatedshiftId=@ShiftId then Case when Onduty=0 then ' ' Else  isNull(CONVERT(varchar(20),Onduty),'') End Else '-' End
	,Case when AllocatedshiftId=@ShiftId then isNull(Permissionhrs,'') Else '-' End,
	Case when AllocatedshiftId=@ShiftId then isNull(IsLeave,'') Else '-' End
	From @TblCurretShiftEmpDetails
	 Union All
	Select AllocatedshiftId,shiftName,Case when AllocatedshiftId=@ShiftId then EmployeeCodeId Else ' ' End,Case when AllocatedshiftId!=@ShiftId then EmployeeCodeId Else ' ' End
	,InTime,ISNULL(OutTime,' '),FirstSession,SecondSession,Case when AllocatedshiftId=@ShiftId then Case when Onduty=0 then ' ' Else  isNull(CONVERT(varchar(20),Onduty),'') End Else '-' End,Case when AllocatedshiftId=@ShiftId then isNull(Permissionhrs,'') Else '-' End,
	Case when AllocatedshiftId=@ShiftId then isNull(IsLeave,'') Else '-' End 
	From @TblDiffShiftEmpDetails 


	--Select * From @TblCurretShiftEmpDetails Union All Select * From @TblDiffShiftEmpDetails

	Select * From @TblEmployeShiftDetail

	Drop Table #TblEmployeeID

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftwiseAttendanceReport_back20230330]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_ShiftwiseAttendanceReport_back20230330 2,1,'2023-03-01 00:00:00.000'
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_ShiftwiseAttendanceReport_back20230330]
	-- Add the parameters for the stored procedure here
	@ShiftId int,
	@level_Id int,
	@Date DateTime
AS
BEGIN

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.

	SET NOCOUNT ON;
	Declare @ShiftStartTime varchar(20)
	Declare @ShiftEndTime varchar(20)
	Declare @MaxHourBeforeShift DateTime
	

    --Insert statements for procedure here
	--Select * From TA_Tbl_ShiftSettings

	Declare @shiftStarttimeMinutes int
	Declare @shiftStartMinutes int

	Select @shiftStarttimeMinutes=SubString(Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)),0,CHARINDEX(':',Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)))),@ShiftEndTime=Shift_EndTime fROM TA_Tbl_Shift where Level_Id=@level_Id and Shift_Id=@ShiftId

	Select @shiftStartMinutes=( @shiftStarttimeMinutes*60 + SubString(Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)),CHARINDEX(':',Substring(Shift_StartTime,0,CHARINDEX(' ',Shift_StartTime)))+1,LEN(Shift_StartTime)) -
	substring(MaxHoursBeforeShift,0,CHARINDEX(':',MaxHoursBeforeShift))*60+substring(MaxHoursBeforeShift,CHARINDEX(':',MaxHoursBeforeShift)+1,LEN(MaxHoursBeforeShift)) ) from TA_Tbl_Shift Inner Join TA_Tbl_ShiftSettings on CompanyId=Level_Id where Shift_Id=@ShiftId and CompanyId=@level_Id

	Select @ShiftStartTime=(Case when @shiftStartMinutes>12*60 then Convert(varchar(5),DateAdd(Minute,@shiftStartMinutes,'00:00:00'),108) +' '+'PM' Else Convert(varchar(5),DateAdd(Minute,@shiftStartMinutes,'00:00:00'),108) +' '+'AM' End)

    --  Select the Employee Id Based 
	
	Create Table #TblEmployeeID (EmployeeID int,EmployeeCodeId varchar(20),InDate DateTime)

	insert into #TblEmployeeID
	Select Employee_Id,Employee_Code_Id,Clk_InDate From TA_Tbl_ClockDetails inner join TA_Tbl_Employee on SwipeCardNo=Clk_EmpId where Clk_InTime>= CONVERT(DateTime,@ShiftStartTime) and Clk_InDate=@Date and Clk_InTime<=Convert(DateTime,@ShiftEndTime) and Clk_Remarks!='1'


	Declare @ShiftDate varchar(10)
	Set @ShiftDate='Day'+Convert(varchar(10),DAY(@Date))+'Shift'


	-- Current Shift Employee Details

	Declare @query varchar(200)

    set @query='Select (Day'+CONVERT(varchar(20),Day(@Date))+'Shift),Emp.EmployeeCodeId from TA_Tbl_PermanentShiftAllocation PS inner Join #TblEmployeeID Emp on Emp.EmployeeID=PS.EmployeeId  where Year=Year(Emp.InDate) and Month=Month(Emp.InDate)'

    Declare @TblCurrentDayShiftID as Table (Cur_shiftID int,EmpID varchar(20))

	Insert into @TblCurrentDayShiftID(Cur_shiftID,EmpID) Exec(@query)

	Declare @TblCurretShiftEmpDetails as Table(AllocatedshiftId int,shiftName varchar(20),EmployeeCodeId varchar(20),InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))
	
	Insert into @TblCurretShiftEmpDetails
	Select S.shift_Id,S.Shift_Name,PD.Employee_Code_Id As Actual_Allocated_Shift,PD.InTime,isNull(PD.OutTime,'00:00'),PD.FNAttendanceCode,PD.ANAttendanceCode,PD.IsOnduty,PD.PermissionHrs,PD.LeaveStatus
	From TA_Tbl_ProcessedData PD Left Join TA_Tbl_Shift S on S.Shift_Id =PD.Shift_Id Left Join @TblCurrentDayShiftID TDS on TDS.EmpID=PD.Employee_Code_Id where Date=@Date and PD.Shift_Id=@ShiftId

	
	-- Exception Entry in Shift

	-- Previous Shift Day Not in Night shift Employee ID get the Temporary Table
	
	Declare @PreviousDate DateTime
	
	set @PreviousDate=DATEADD(day,-1,@Date)

	Declare @TblNightShift as Table (shift_Id int)

	Declare @TblClockDetails as Table (EmployeeId int,EmployeeCodeId varchar(20),InDate DateTime,InTime DateTime,OutDate DateTime, OutTime DateTime)

	insert into @TblClockDetails
	Select Employee_Id,Employee_Code_Id,Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime From TA_Tbl_ClockDetails inner join TA_Tbl_Employee on SwipeCardNo=Clk_EmpId where Clk_InTime>= CONVERT(DateTime,@ShiftStartTime) and Clk_InDate=@Date and Clk_InTime<=Convert(DateTime,@ShiftEndTime) and Clk_Remarks!='1'

	insert into @TblNightShift
	Select Shift_Id From TA_Tbl_Shift where Convert(DateTime,Shift_StartTime)<Convert(Datetime,'08:00 PM')

	Declare @TblProcessDate As Table (EmpCodeId varchar(20),PrevShiftId int,Attendance varchar(20))

	--Select * From @TblClockDetails


	Declare @TblDiffShiftEmpDetails as Table(AllocatedshiftId int,shiftName varchar(20),EmployeeCodeId varchar(20),InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))


	insert into @TblProcessDate 
	Select PD.Employee_Code_Id,PD.Shift_Id,PD.Attendance From TA_Tbl_ProcessedData PD Left Join #TblEmployeeID TE on TE.EmployeeCodeId=PD.Employee_Code_Id Left Join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id where  Date=@PreviousDate and PD.Shift_Id IN (Select shift_Id From @TblNightShift)
	
	insert into @TblDiffShiftEmpDetails
	Select shift_Id,Shift_Name,EmpID,CONVERT(VARCHAR(5), InTime, 108) As InTime,isNull(Convert(varchar(10),OutTime,108),'00:00')As OutTime,Case when InTime!='' then 'Present'Else 'Absent' End As FirstSession,Case when OutTime!='' then 'Present'Else 'Absent' End As SecondSession,'','',''
	From @TblCurrentDayShiftID inner Join TA_Tbl_Shift on Shift_Id=Cur_shiftID Inner join @TblClockDetails on EmployeeCodeId=EmpID  where Shift_Id !=@ShiftId

	Declare @TblEmployeShiftDetail As Table (shiftId int,ShiftName varchar(200),Actual_Allocated_Shift varchar(20),From_Other_Shift varchar(20),
	InTime varchar(20),OutTime varchar(20),FirstSession varchar(20),SecondSession varchar(20),
	Onduty int,Permissionhrs varchar(20),IsLeave varchar(20))
	
	insert into @TblEmployeShiftDetail(shiftId,ShiftName,Actual_Allocated_Shift,From_Other_Shift
	,InTime,OutTime,FirstSession,SecondSession,Onduty,Permissionhrs,IsLeave)
	Select AllocatedshiftId,shiftName,Case when AllocatedshiftId=@ShiftId then EmployeeCodeId Else ' ' End,Case when AllocatedshiftId!=@ShiftId then EmployeeCodeId Else ' ' End
	,InTime,ISNULL(OutTime,' '),FirstSession,SecondSession
	,Case when AllocatedshiftId=@ShiftId then Case when Onduty=0 then ' ' Else  isNull(CONVERT(varchar(20),Onduty),'') End Else '-' End
	,Case when AllocatedshiftId=@ShiftId then isNull(Permissionhrs,'') Else '-' End,
	Case when AllocatedshiftId=@ShiftId then isNull(IsLeave,'') Else '-' End
	From @TblCurretShiftEmpDetails
	 Union All
	Select AllocatedshiftId,shiftName,Case when AllocatedshiftId=@ShiftId then EmployeeCodeId Else ' ' End,Case when AllocatedshiftId!=@ShiftId then EmployeeCodeId Else ' ' End
	,InTime,ISNULL(OutTime,' '),FirstSession,SecondSession,Case when AllocatedshiftId=@ShiftId then Case when Onduty=0 then ' ' Else  isNull(CONVERT(varchar(20),Onduty),'') End Else '-' End,Case when AllocatedshiftId=@ShiftId then isNull(Permissionhrs,'') Else '-' End,
	Case when AllocatedshiftId=@ShiftId then isNull(IsLeave,'') Else '-' End 
	From @TblDiffShiftEmpDetails 


	--Select * From @TblCurretShiftEmpDetails Union All Select * From @TblDiffShiftEmpDetails

	Select * From @TblEmployeShiftDetail

	Drop Table #TblEmployeeID

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Show Employee info in Grid - CMI Tech>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	
	--New Employee Records
	Select isnull(EmployeeId,'') as EmployeeId, isnull(EmployeeName,'') as EmployeeName,
	CONVERT(VARCHAR, getdate(), @DATEFORMAT)  as DOJ
	,'Staff' as Designation
	,'Angler Technologies India Pvt Ltd' as CompanyName
	from TA_Tbl_CMITechSyncEmployeeInfo a
	left outer join TA_Tbl_Employee b on b.Employee_Code_Id = a.EmployeeId
	where b.Employee_Code_Id is null
	
	--Already Existing records	
	Select isnull(b.Employee_Id,'') as EmployeeId, isnull(b.Employee_FirstName,'') as EmployeeName,
	CONVERT(VARCHAR, b.DateOfJoining, @DATEFORMAT)  as DOJ
	,c.TitleName as Designation
	,e.name as CompanyName
	from TA_Tbl_CMITechSyncEmployeeInfo a
	inner join TA_Tbl_Employee b on b.Employee_Code_Id = a.EmployeeId
	inner join TA_Tbl_EmployeeDesignation f on f.EmployeeID = b.Employee_Id
	inner join TA_Tbl_Title c on c.TitleId = f.DesignationID
	inner join TA_Tbl_EmployeeLevel d on d.EmployeeId = b.Employee_Id
	inner join Ta_Tbl_levelDetails e on e.id =d.LevelId

END



GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShrinkDatabase]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_ShrinkDatabase]
AS
BEGIN
	SET NOCOUNT ON
	CREATE TABLE #tFileList
	(
	databaseName sysname,
	logSize decimal(18,5),
	logUsed decimal(18,5),
	status INT
	)
	Declare @intSize as int
	declare @inStrdatabaseName as varchar(200)
	--Get Database Name
	set @inStrdatabaseName=(select db_name(dbid) from master..sysprocesses where spid=@@SPID)
	INSERT INTO #tFileList EXEC Proc_TA_GetLogFileSize
	set @intSize=(SELECT  cast(logSize as int) FROM #tFileList where databasename=@inStrdatabaseName)
	if(@intSize>=512)
		begin
			--Database Shrink done here
			--BACKUP LOG @inStrdatabaseName WITH TRUNCATE_ONLY 
			DBCC SHRINKDATABASE (@inStrdatabaseName, 10, TRUNCATEONLY)
		end
DROP TABLE #tFileList 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SkipErroredDataForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SkipErroredDataForService]
	-- Add the parameters for the stored procedure here
	@Process_Rec_ID bigint,
	@errorMessage varchar(max)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	insert into TA_Tbl_ErrorLog_ProcessedData (Process_Rec_ID,ErrorMessage) values
	(@Process_Rec_ID,@errorMessage )
	UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 1 WHERE Process_Rec_Id = @Process_Rec_ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Slab]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Create Table SlabTable (id int identity(1,1),slabrow int,policyId int)

--Alter Table SlabTable Add policyId int

CREATE Proc [dbo].[Proc_TA_Slab]
(
	@tag char(2),
	@policyId int =null,
	@slabValue int =null
)
As
Begin

	if(@tag='U')
	Begin
		Update SlabTable set slabrow=@slabvalue where policyId =0
		Select slabrow From SlabTable where policyId=0
	End
	else if(@tag='SS')
	Begin
		Select slabrow From SlabTable where policyId=0
	End
	else if(@tag='N')
	Begin
		Update SlabTable set slabrow=3,policyId=0 where policyId =0
		insert into SlabTable(slabrow,policyId) values (@slabvalue, @policyId)
	End
	else if(@tag='S')
	Begin
		Select 3 as slabrow From SlabTable where policyId=0
		update SlabTable set slabrow=3 where policyId=0
	End
End

--Select * From SlabTable
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SuccessiveYearSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SuccessiveYearSettings] 
	-- Add the parameters for the stored procedure here
	AS
BEGIN	
	SET NOCOUNT ON;
    select top 1 Yearsettings_Id as SuccessiveYearSetting from ta_tbl_yearSetting 
    where Yearsettings_Id > (select Yearsettings_Id from ta_tbl_yearSetting where Isactive=1)	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SwipeCardNoExists]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Created By : Prabakaran.P  
Created On : 26-Feb-09  
Proc_TA_SwipeCardNoExists 101  
*/  
CREATE procedure [dbo].[Proc_TA_SwipeCardNoExists]  
@SwipeCardNo varchar(20)  
AS  
BEGIN  
	DECLARE @rawdatacount as BIGINT  
	SELECT @rawdatacount=count(CLK_ID) from Ta_Tbl_clk_rawdata where CLK_CARDID=@SwipeCardNo
	IF(@rawdatacount>0)  
	BEGIN  
		SELECT 1 as RawDataCount  
	END  
	ELSE  
	BEGIN  
		SELECT 0 as RawDataCount  
	END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_TaxSlabDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Maria Prasanth>
-- Create date: <Create Date,,05-Dec-2022>
-- Description:	<Description,,TDS Slab Value Insert Table>
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_TaxSlabDetails]
	@tag char(4),
	@TaxPolicyId int,
	@TDSSlabName nvarchar(10)=null,
	@TDSSalaryFrom bigint=null,
	@TDSSalaryTO bigint=null,
	@TDSPercentage float=null,
	@TDSCessPercentage float=null,
	@ProfSlabName nvarchar(20)=null,
	@ProfSalaryFrom bigint=null,
	@ProfSalaryTO bigint=null,
	@ProfTaxAmount nvarchar(50)=null,
	@ProfTaxPercentage nvarchar(50)=null,
	@ProfISFlag bit=0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from 
	-- interfering with SELECT statements.

	SET NOCOUNT ON;

	if(@tag='TDS')
	Begin
		
		Insert into TA_Tbl_TDSSlab (Tax_PolicyId,Tds_SlabNo,Tds_RangeFrom,Tds_RangeTo,Tds_Percentage,Tds_CessPercentage) 
		values (@TaxPolicyId,@TDSSlabName,@TDSSalaryFrom,@TDSSalaryTO,@TDSPercentage,@TDSCessPercentage)
	End

	Else if(@tag='TDD')
	Begin
			Delete From TA_Tbl_TDSSlab where Tds_SlabNo=@TDSSlabName and Tax_PolicyId=@TaxPolicyId
	End

	Else if(@tag='PSD')
	Begin
		Delete From TA_Tbl_ProfSlab where Prof_SlabName=@ProfSlabName and Tax_PolicyId=@TaxPolicyId
	End

	IF(@tag='PROF')
	Begin
		Insert into TA_Tbl_ProfSlab (Prof_SlabName,Tax_PolicyId,Prof_RangeFrom,Prof_RangeTO,Prof_Amount,IsPercentage) 
		values (@ProfSlabName,@TaxPolicyId,@ProfSalaryFrom,@ProfSalaryTO,@ProfTaxAmount,@ProfISFlag)
	End
	Else If(@tag='UTS')
	BEgin
		 Declare @slabName varchar(50)
		 Set @slabName= (select Count(Tds_SlabNo) From TA_Tbl_TDSSlab where Tds_SlabNo=@TDSSlabName and Tax_PolicyId=@TaxPolicyId)
		if(@slabName=0)
			Begin
				Insert into TA_Tbl_TDSSlab (Tax_PolicyId,Tds_SlabNo,Tds_RangeFrom,Tds_RangeTo,Tds_Percentage,Tds_CessPercentage) 
				values (@TaxPolicyId,@TDSSlabName,@TDSSalaryFrom,@TDSSalaryTO,@TDSPercentage,@TDSCessPercentage)
			End
		Else
		Begin
			Update TA_Tbl_TDSSlab set Tds_RangeFrom=@TDSSalaryFrom,Tds_RangeTo=@TDSSalaryTO,Tds_Percentage=@TDSPercentage,Tds_CessPercentage=@TDSCessPercentage where Tds_SlabNo=@TDSSlabName and Tax_PolicyId=@TaxPolicyId
		End		
	End

  Else If(@tag='UPS')
	BEgin
		

		 Declare @slabPSName varchar(50)
		 Set @slabPSName= (select Count(Prof_SlabName) From TA_Tbl_ProfSlab where Prof_SlabName=@ProfSlabName and Tax_PolicyId=@TaxPolicyId)
		if(@slabPSName=0 )
			Begin
			
				Insert into TA_Tbl_ProfSlab (Prof_SlabName,Tax_PolicyId,Prof_RangeFrom,Prof_RangeTO,Prof_Amount,IsPercentage) 
				values (@ProfSlabName,@TaxPolicyId,@ProfSalaryFrom,@ProfSalaryTO,Case when @ProfISFlag=1 then @ProfTaxPercentage else @ProfTaxAmount End,@ProfISFlag)
			End
		Else
		Begin
			Update TA_Tbl_ProfSlab set Prof_RangeFrom=@ProfSalaryFrom,Prof_RangeTO=@ProfSalaryTO,Prof_Amount=Case when @ProfISFlag=1 then @ProfTaxPercentage else @ProfTaxAmount End,IsPercentage=@ProfISFlag where Prof_SlabName=@ProfSlabName and Tax_PolicyId=@TaxPolicyId
		End		
	End

	

END


-- Select * From TA_Tbl_TDSSlab

-- Select * From TA_Tbl_TaxMasterdetails

-- Select * From TA_Tbl_ProfSlab

--Delete From  TA_Tbl_TaxMasterdetails where TaxPolicy_Id in (128,129,130)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_LeaveApplication_FileUpload]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<ANTANIJABARAJ J>
-- Create date: <10-05-2018>
-- Description:	<Leave Application File Upload>

-- =============================================
create PROCEDURE [dbo].[Proc_TA_Tbl_LeaveApplication_FileUpload]
	-- Add the parameters for the stored procedure here
		@FileName varchar(50) =NULL,  
        @FilePath nvarchar(200)=NULL,  
        @Emp_Id int=NULL,
        @LeaveApplication_Id int=NULL,
        @Type nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@Type = 'InsertMedicalCertificate')
	begin
	insert into TA_Tbl_LeaveApplication_FileUpload values(@FileName,@FilePath,@Emp_Id,@LeaveApplication_Id);
	end
	else if(@Type = 'SelectMedicalCertificate')
	begin
	select FilePath from TA_Tbl_LeaveApplication_FileUpload where LeaveApplication_Id=@LeaveApplication_Id
	end
	else if(@Type = 'DeleteMedicalCertificate')
	begin
	Delete from TA_Tbl_LeaveApplication_FileUpload where LeaveApplication_Id=@LeaveApplication_Id
	end
	else if(@Type = 'GetCountMedicalCertificate')
	begin
	select COUNT(*) as GetCount from TA_Tbl_LeaveApplication_FileUpload where LeaveApplication_Id=@LeaveApplication_Id
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempInsertEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[Proc_TA_Tbl_TempInsertEmployee]
/****************************************************************************************/
-- Name				:	Proc_TA_Tbl_TempInsertEmployee
-- Desc				:	To add or update the enties in TA_Tbl_TempInsertEmployee
-- Company			:   Angler Technologies
-- Author			:	P.Santhosh Raj
-- Date				:	29-Feb-2009
-- Update History	:   [Date Updated By (Initials) Reason]
/****************************************************************************************/
AS
BEGIN
delete from TA_Tbl_TempInsertEmployee
DECLARE @employee_code		nvarchar(50)
DECLARE @first_name			nvarchar(50)
DECLARE @last_name			nvarchar(50)    
DECLARE @birth_date			datetime 
DECLARE @local_addr1		nvarchar(50)  
DECLARE @local_addr2		nvarchar(50) 
DECLARE @local_addr3		nvarchar(50)     
DECLARE @join_date			datetime
DECLARE @desg_name			nvarchar(50) 
DECLARE @section_name		nvarchar(50) 
DECLARE @category_name	nvarchar(50)  
DECLARE @basic			nvarchar(50)   
declare DNCList cursor FOR select employee_code,first_name,last_name,birth_date,local_addr1,local_addr2,local_addr3,
join_date,
section_name,desg_name,category_name,[basic] from [Customer].dbo.tbl_Cus where employee_code not in (select Employee_Code_Id from TA_Tbl_Employee)
OPEN DNCList
	FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic   
		while @@fetch_status = 0
		begin
			insert into TA_Tbl_TempInsertEmployee VALUES (@employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic)
			FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic
		end
	CLOSE DNCList
DEALLOCATE DNCList
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempUpdateEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Proc_TA_Tbl_TempUpdateEmployee]
/****************************************************************************************/
-- Name				:	Proc_TA_Tbl_TempUpdateEmployee
-- Desc				:	To add or update the enties in Employee table.
-- Company			:   Angler Technologies
-- Author			:	P.Santhosh Raj
-- Date				:	29-Feb-2009
-- Update History	:   [Date Updated By (Initials) Reason]
/****************************************************************************************/
AS
BEGIN
delete from TA_Tbl_TempUpdateEmployee
update TA_Tbl_Employee Set Isdeleted=1  WHERE [Employee_Code_Id] IN ( select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id not in (select employee_code from [Customer].dbo.tbl_Cus))
DECLARE @employee_code		nvarchar(50)
DECLARE @first_name			nvarchar(50)
DECLARE @last_name			nvarchar(50)    
DECLARE @birth_date			datetime 
DECLARE @local_addr1		nvarchar(50)  
DECLARE @local_addr2		nvarchar(50) 
DECLARE @local_addr3		nvarchar(50)     
DECLARE @join_date			datetime
DECLARE @desg_name			nvarchar(50) 
DECLARE @section_name		nvarchar(50) 
DECLARE @category_name	nvarchar(50)  
DECLARE @basic			nvarchar(50)   
declare DNCList cursor FOR select employee_code,first_name,last_name,birth_date,local_addr1,local_addr2,local_addr3,join_date,
section_name,desg_name,category_name,[basic] from [Customer].dbo.tbl_Cus where employee_code in (select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0)
OPEN DNCList
	FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic   
		while @@fetch_status = 0
		begin
			insert into TA_Tbl_TempUpdateEmployee VALUES (@employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic)
			FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic
		end
	CLOSE DNCList
DEALLOCATE DNCList
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Manikandan.R
-- Create date: 14-Mar-2012
-- Description:	To Get the Temporary Weekdayid's for Viewing the Details of selected TempIds
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]
	-- Add the parameters for the stored procedure here
	 @TempWeekdayId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date='dd/MM/yyyy')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date='MM/dd/yyyy')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END 
	select	distinct case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, TempWeekday_FromDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, TempWeekday_FromDate, @dateFormat) end 'TempWeekday_FromDate',
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, TempWeekday_ToDate,@dateFormat),' ','-') 
			else CONVERT(VARCHAR, TempWeekday_ToDate, @dateFormat) end 'TempWeekday_ToDate',			
			ClosingTime,Reason,TL.LevelId from ta_tbl_TemWeekDay TD
			inner join TA_Tbl_Temporary_WeeklyOff_Levels TL on TD.TempWeekday_Id = TL.TempWeekday_Id 
			where TD.TempWeekday_Id=@TempWeekdayId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_TimezoneApplicableUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_TimezoneApplicableUpdate]
	-- Add the parameters for the stored procedure here
  @isTimezoneID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	update TA_Tbl_YearSetting set isTimezoneEnable=@isTimezoneID 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToCheckLastOutIsManual]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ToCheckLastOutIsManual]
	@EmployeeSwipeCardNumber varchar(50),
	@ClockDate varchar(30),
	@Its24Hrs int
AS
BEGIN
	SET NOCOUNT ON;
	if((SELECT count(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @EmployeeSwipeCardNumber AND (ManualTimeEntry_OutDate + ManualTimeEntry_OutTime)=@ClockDate and Isdeleted=0 and ManualTimeEntry_Status='Approved')>0)
		begin
			select 1
		end
	else
		begin
			if(@Its24Hrs=1)
				begin
					if((SELECT count(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @EmployeeSwipeCardNumber AND (ManualTimeEntry_OutDate + ManualTimeEntry_OutTime)=dateadd(d,1,@ClockDate) and Isdeleted=0 and ManualTimeEntry_Status='Approved')>0)
						begin
							select 1
						end
					else
						begin
							select 0
						end
				end
			else
				begin
					select 0
				end
		end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]
	@ShiftDate datetime,
	@empID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * from Ta_tbl_TaskProgressDetails where TaskSubmittedBy=@empID and Shiftdate=@ShiftDate and isSubmitted_Completely=1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToGetLunchHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- ==========================================================================================
-- Author: R.Manikandan
-- Create date: 10-01-2014
-- Description: This is for Non flexi employees alone.
-- 1. To deduct the lunch hrs based on the punches. if the punches are not availed in device
-- means, that time the procedure will consider the shift break timings.
-- 2. if only one punches are avalied in device means, that time also it will consider the
-- shift break time
-- [dbo].[Proc_Ta_ToGetLunchHours] '2002','08/04/2019',-1,7,0
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_ToGetLunchHours]
-- Add the parameters for the stored procedure here
@EmployeeCodeId varchar(50),
@Clockdate varchar(30),
@ShiftId int,
@levelid int,
@addWeekOff int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	Declare @MaxluncHours datetime
	Declare @MinluncHours datetime
	Declare @Difference datetime
	Declare @Differences varchar(20)
	Declare @ClosingTime datetime
	Declare @Shift_BreakStartTime1 datetime
	Declare @Shift_BreakEndTime1 datetime
	Declare @count int
	declare @weekNumber int
	Declare @employeeId int
	declare @FirstSession varchar(20)
	declare @SecondSession varchar(20)
	--Added by Manjula.P on 02-Apr-2014 for holiday and weekly off lunch hours deduction
	declare @HolidayCount int;
	DECLARE @ParentLevelId int
	declare @ParentId int
	declare @IsLunchDeduction bit
	declare @LunchDeductionHours nvarchar(10)
	set @ParentId=@levelid;
	set @ParentLevelId=@levelid;
	--For Getting parent Levelid to taking values from shift settings table
	while(@ParentId!=0)
		begin
		set @ParentLevelId=(SELECT id FROM Ta_Tbl_levelDetails WHERE ID=@ParentId)
		set @ParentId=(SELECT parentId FROM Ta_Tbl_levelDetails WHERE ID=@ParentId)
	end
	set @IsLunchDeduction=(select isnull(IsLunchDeduction,0) from TA_Tbl_ShiftSettings where CompanyId=@ParentLevelId)
	set @LunchDeductionHours=(select isnull(LunchDeductionHours,'00:00') from TA_Tbl_ShiftSettings where CompanyId=@ParentLevelId)
	set @weekNumber =DATEPART(WK,@Clockdate)
	set @count=0
	set @Difference='00:00' 
	set @ClosingTime=''
	set @employeeId=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeId and Isdeleted=0)
	--select @count=COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@employeeId And IsDeleted=0
	-- And(Leave_FromDate=@Clockdate) and Status<>'Rejected'
	select @count=COUNT(*) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveApplicationExists
	LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId where la.Employee_Id =@employeeId And la.IsDeleted=0
	And(lae.Leave_FromDate=@Clockdate) and la.Status<>'Rejected'
	Select @MaxluncHours= isnull(MAX(Clk_InTime),'9999-12-31 00:00:00.000')
	from ta_tbl_clockdetails where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and Clk_InPunchType='Lunch In'
	AND IsVoid = 0	
	Select @MinluncHours=isnull(Min(Clk_OutTime),'9999-12-31 00:00:00.000')
	from ta_tbl_clockdetails where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and Clk_OutPunchType='Lunch Out'
	AND IsVoid = 0
	--Added by Manjula.P on 02-Apr-2014 for lunch deduction on holdiay and weekly off	
	create table #tempHolidayCount(HolidayCount int,holidaydescription varchar(max))
	insert into #tempHolidayCount
	execute Proc_TA_CheckHolidayBasedOnLevel @Clockdate,@Clockdate,'G',@employeeId
	set @HolidayCount= (select count(*) from #tempHolidayCount where HolidayCount!=0)
	declare @ShiftLunchStart datetime
	declare @ShiftLunchEnd datetime
	declare @ActualShiftIn datetime
	declare @ActualShiftOut datetime
	declare @ShiftStartDate datetime
	declare @ShiftEndDate datetime
	set @ActualShiftIn=(select isnull(min(Clk_InTime),'9999-12-30 00:00:00.000')from ta_tbl_clockdetails 
	where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and (lower(Clk_InPunchType)='shift in' or lower(Clk_InPunchType)='in')	)
	set @ActualShiftOut=(select isnull(MAX(Clk_OutTime),'9999-12-30 00:00:00.000')from ta_tbl_clockdetails 
	where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and (lower(Clk_OutPunchType)='shift out' or lower(Clk_OutPunchType)='out'))
	set @ShiftStartDate=(select isnull(cast(Shift_StartTime as datetime),'9999-12-31 00:00:00.000') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftEndDate=(select isnull(cast(Shift_EndTime as datetime),'9999-12-31 00:00:00.000') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftLunchStart=(select isnull(CAST(Shift_BreakStartTime2 as datetime),'9999-12-31 00:00:00.000') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftLunchEnd=(select  isnull(cast(Shift_BreakEndTime2 as datetime),'9999-12-31 00:00:00.000') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	--Chekcing with night shift Generally PM and AM means that shift is night shift 
	--0 to 11 - AM in 12 hours format and 12 to 23 -PM in 12 hours format	
	if( (datepart(HOUR,@ShiftStartDate) between 12 and 23) and datepart(hour,@ShiftEndDate) between 0 and 11 )
	begin
		--Checking lunch start hours
		if(datepart(HOUR,@ShiftLunchStart) between 0 and 11)
		begin
			set @ShiftLunchStart=DATEADD(day,1,@ShiftLunchStart);
		end
		--Checking lunch end hours
		if(datepart(HOUR,@ShiftLunchEnd) between 0 and 11)
		begin
			set @ShiftLunchEnd=DATEADD(day,1,@ShiftLunchEnd);
		end
		--Checking actual shift start date
		if(datepart(HOUR,@ActualShiftIn) between 0 and 11)
		begin
			set @ActualShiftIn=DATEADD(day,1,@ActualShiftIn);
		end
		--Checking actual shift end date
		if(datepart(HOUR,@ActualShiftOut) between 0 and 11)
		begin
			set @ActualShiftOut=DATEADD(day,1,@ActualShiftOut);
		end
	end	
	--Adding this condition (@MaxluncHours<>'9999-12-31 00:00:00.000' ) and( @MinluncHours<>'9999-12-31 00:00:00.000') for taking lunch deduction hours 
	-- if the time value is exact 12:00 am i.e 9999-12-31 00:00:00.000
	--if((@MaxluncHours<>'' ) and( @MinluncHours<>''))
	if((@MaxluncHours<>'9999-12-31 00:00:00.000' ) and( @MinluncHours<>'9999-12-31 00:00:00.000'))
		begin 			
			set @Difference=@MaxluncHours-@MinluncHours 
		end
	else
		begin		
			if(@ShiftId!=-1 and @HolidayCount<=0 and @addWeekOff<=0)
				begin					
					set @count=@count+@HolidayCount
					if(@addWeekOff>0)
						begin
							set @count=@count+@addWeekOff
						end
						--@count=0 means there is no weekly off, holiday leave on that clockdate
					if(@count=0)
						begin
							select @ClosingTime=TW.ClosingTime from TA_Tbl_TemWeekday TW inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TW.TempWeekday_Id=TWL.TempWeekday_Id 
							where TWL.LevelId=@levelid and TW.IsDeleted=0 and TW.TempWeekday_FromDate=@Clockdate  
							if(@ClosingTime='')
								begin
									set @Difference=(select CONVERT(datetime,Shift_BreakEndTime2)-CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId)
								end
							else
								begin
									select @Shift_BreakEndTime1=CONVERT(datetime,Shift_BreakEndTime2),@Shift_BreakStartTime1=CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId
									if (@ClosingTime >@Shift_BreakEndTime1 or @ClosingTime<@Shift_BreakStartTime1)
										begin
											set @Difference=(select CONVERT(datetime,Shift_BreakEndTime2)-CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId)
										end
									else if (@ClosingTime >@Shift_BreakStartTime1 and @ClosingTime<@Shift_BreakEndTime1)
										begin
											set @Difference=CONVERT(datetime,@ClosingTime)-CONVERT(datetime,@Shift_BreakStartTime1)
										end
								end
						end					
				end
			--This else part for deducting lunch hours on weekly off and holiday and Additional Weekly off : From shift Settings 
			else 
				begin					
					set @Difference='00:00'
					--if the lunch deduction is yes from shift settings for the particular levelid
					if(@IsLunchDeduction=1)
						begin
							--checking one punch type is missning : Means either lunch in or lunch out is missing : then take lunch deduction hours 
							if((@MaxluncHours<>'9999-12-31 00:00:00.000' ) or ( @MinluncHours<>'9999-12-31 00:00:00.000'))
								begin									
									if(@ShiftId=-1 or @HolidayCount>0 or @addWeekOff>0)
									begin
										set @Difference=@LunchDeductionHours;
									end
								end
							else
								if(@ShiftId=-1 or @HolidayCount>0 or @addWeekOff>0)
									begin
										set @Difference=@LunchDeductionHours;
									end								
						end
					--If lunch dedcution is no then no difference
					else
						begin							
							set @Difference='00:00';
						end
				end		
	end	
	set @Differences=CONVERT(VARCHAR(5),isnull(@Difference,'00:00'),108)
	select substring(@Differences,0,CHARINDEX(':',@differences))*60+substring(@Differences,CHARINDEX(':',@differences)+1,LEN(@differences)) 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_TotalBreakHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 26-08-2014
-- Description:	To Get the Total Break Hours Minutes using employeeid and Shift date
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_TotalBreakHours]
	-- Add the parameters for the stored procedure here
	@clk_empid NVARCHAR(20),
	@clk_date DATETIME
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT isnull(SUM(PunchDiffInMin),0)As TotalBreakHours from ta_tbl_MatchedPunches where Clk_Date=@clk_date and Clk_EmpId=@clk_empid
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Transportation_Delete]
		@id INT
	AS
	DECLARE @DEL BIT
	SET @DEL=0
	BEGIN
		UPDATE TA_Tbl_Transportation SET IsDeleted=@DEL WHERE id=@id
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Mapping_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Transportation_Mapping_Delete]  
  @id INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=0  
 BEGIN  
  UPDATE TA_Tbl_Transportation_Mapping SET IsDeleted=@DEL WHERE VehicleId=@id  
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Route_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified by	:	P.Prabakaran
Modified on	:	07-Feb-08
*/
CREATE   PROCEDURE [dbo].[Proc_TA_Transportation_Route_Delete]
@Type NVARCHAR(30),
@RouteIds NVARCHAR(50),
@auditEmpId int
AS
DECLARE @DEL VARCHAR
DECLARE @RESTORE VARCHAR
SET @DEL=1
SET @RESTORE=0
DECLARE @QUERY NVARCHAR(2000)
SET @QUERY=''
IF (@Type='TemporaryDelete')
	BEGIN
		SET @QUERY='UPDATE TA_Tbl_RouteMaster SET IsDeleted=' + @DEL +  ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE [Id] IN  (' + @RouteIds + ')'
		EXEC (@QUERY)
	END
ELSE IF (@Type='PermanentDelete')
	BEGIN
		SET @QUERY='UPDATE TA_Tbl_RouteMaster SET Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE [Id] IN  (' + @RouteIds + ')'
		EXEC (@QUERY)
		SET @QUERY=''
		SET @QUERY='DELETE FROM TA_Tbl_RouteMaster WHERE [Id] IN  (' + @RouteIds + ')'
		EXEC (@QUERY)
	END
ELSE IF (@Type='Restore')
	BEGIN
		SET @QUERY='UPDATE TA_Tbl_RouteMaster SET IsDeleted=' + @RESTORE +  ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE [Id] IN  (' + @RouteIds + ')'
		EXEC (@QUERY)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Vehicle_Delete]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [dbo].[Proc_TA_Transportation_Vehicle_Delete]
@Type NVARCHAR(50),		
@Vehicles NVARCHAR(25),
@auditEmpId int
AS
DECLARE @Query NVARCHAR(2000)
SET @Query=''
DECLARE @DEL VARCHAR
DECLARE @RESTORE VARCHAR
SET @DEL=1
SET @RESTORE=0
IF (@Type='TemporaryDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Transportation_Vehicle SET IsDeleted= ' + @DEL + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE VehicleId IN ('+ @Vehicles +')'
		EXEC (@Query)
	END
ELSE IF (@Type='PermanentDelete')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Transportation_Vehicle SET Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE VehicleId IN ('+ @Vehicles +')'
		EXEC (@Query)
		SET @Query = ''
		SET @Query = 'DELETE FROM TA_Tbl_Transportation_Vehicle WHERE VehicleId IN ('+ @Vehicles +')'
		EXEC (@Query)
	END
ELSE IF (@Type='Restore')
	BEGIN
		SET @Query = 'UPDATE TA_Tbl_Transportation_Vehicle SET IsDeleted= ' + @RESTORE + ', Emp_ID = '+cast(@auditEmpId as nvarchar(20))+' WHERE VehicleId IN ('+ @Vehicles +')'
		EXEC (@Query)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UnUsedTerminalsinProject]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani. P>
-- Create date: <04-Jan-2020>
-- Description:	<This procedure used to bring unused termianls from project table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UnUsedTerminalsinProject]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	select isnull(Terminal_ReaderID,0), isnull(Terminal_Name,'') from ta_tbl_terminal
	where terminal_Id in (
	select isnull(Terminal_id,0) from TA_Tbl_ProjectTerminals
	where Project_Id in (
	select isnull(Project_Id,0) from TA_Tbl_Project
	where (project_status = 'Completed' or project_status = 'Rejected')
	) 
	)

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LastLogout]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_Update_LastLogout ['emp102','hfhf']
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Update_LastLogout]
	-- Add the parameters for the stored procedure here
	@UserName VARCHAR(2000)	 
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SET @Query='UPDATE  TA_Tbl_Login SET LastLogoutTime=getdate() WHERE UserName IN ('''+@UserName+''')'	
	EXEC (@Query) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveMasterDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_TA_Update_LeaveMasterDetails]    
(        
  @CompanyId INT,         
  @RegionId INT,        
  @BranchId INT,    
  @DepartmentId INT,    
  @SectionId INT,    
  @TitleId INT,  
  @LeaveType_Id INT,  
  @LOP  VARCHAR (25),    
 @id INT    
)         
As        
BEGIN        
 UPDATE TA_Tbl_LeaveMaster      
 SET        
    Company_Id =@CompanyId,        
    Region_Id = @RegionId,        
    Branch_Id = @BranchId,    
    Department_Id=@DepartmentId,    
    Section_Id=@SectionId,    
    Title_Id=@TitleId,   
    LeaveType_Id=@LeaveType_Id,  
    LOP=@LOP  
  WHERE Id=@Id    
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveTypeDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_Update_LeaveTypeDetails]        
(        
 @LeaveType NVARCHAR(50),        
 @LeaveDescription NVARCHAR(250),      
 @TypeId INT,    
 @employeeId int,  
 @CountFactor int,
 @EmpCategory int,
 @EmpType int,
 @Gender varchar(10),
 @Religion int
)        
AS        
 BEGIN        
  --declare @sql nvarchar(2000)          
  --SET @sql='
  UPDATE TA_Tbl_LeaveType SET LeaveType =@LeaveType,LeaveDescription= @LeaveDescription, 
  Emp_ID=@employeeId,CountFactor=@CountFactor,EmployeeCategory=@EmpCategory,EmployeeType=@EmpType,Gender=@Gender,Religion=@Religion WHERE LeaveType_Id=@TypeId
 -- exec(@sql)    
 END 
 --[Proc_TA_Update_LeaveTypeDetails] 'ctc','common',8,1,0,1,1,1,1
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_PayrollProcessDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_Update_PayrollProcessDetails]
(
   @HrsWork NVARCHAR(20),
   @HrsOT NVARCHAR(20),
   @NormOT NVARCHAR(20),
   @OffOT NVARCHAR(20),
   @HolOT NVARCHAR(20),
   @EarlyOut NVARCHAR(20),
   @LateIn NVARCHAR(20),
   @WorkHrs NVARCHAR(20),
   @HrsLess NVARCHAR(20),
   @HrsExtra NVARCHAR(20),
   @LeaveDays numeric(18,1),
   @AbsentDays numeric(18,1),
   @PresentDays numeric(18,1),
   @Holidays numeric(18,1),
   @LOPDays numeric(18,1),
   @UserId INt,
   @ProcessDateTime NVARCHAR(20),
   @MonthClosure_Id INT,
   @EmpId NVARCHAR(20)
)
AS
BEGIN
           UPDATE TA_Tbl_PayrollProcessDetails SET HrsWork = @HrsWork,HrsOT = @HrsOT,NormOT = @NormOT,OffOT = @OffOT,HolOT = @HolOT,EarlyOut = @EarlyOut,LateIn = @LateIn,WorkHrs = @WorkHrs,
           HrsLess = @HrsLess,HrsExtra = @HrsExtra,LeaveDays = @LeaveDays,AbsentDays = @AbsentDays,PresentDays = @PresentDays,Holidays = @Holidays,LOPDays=@LOPDays,[Emp_Id] = @UserId,[TimeStamp] = @ProcessDateTime 
           WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ReligionDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_Update_ReligionDetails]        
(        
 @Name NVARCHAR(50),        
 @Description NVARCHAR(250),  
 @ID int  
)        
AS        
 BEGIN        
  declare @sql nvarchar(2000)    
  SET @sql='UPDATE TA_Tbl_Religion SET Name =N''' +  @Name + ''',Description=N''' + @Description + ''' WHERE ID=' + cast(@ID as nvarchar(20)) + ''    
  exec(@sql)    
 END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,28-November>
-- Description:	<Description,,Delete the Shifts for given period>
-- Proc_TA_Update_ShiftAllocation 'Day21Shift=0',2009,1,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Update_ShiftAllocation]
(
@ColName varchar(3000),
@Year int,
@Month int,
@loginEmployeeId varchar(50)
)
AS
BEGIN
	DECLARE @sSql  varchar(8000)
	SET @sSql = 'UPDATE TA_Tbl_PermanentShiftAllocation SET  ' + @ColName + '' 
	SET @sSql = @sSql + ' where EmployeeId in (select EmpId from TA_Tbl_TempShiftAllocation where LoginEmployeeId = '+@loginEmployeeId+')'
	SET @sSql = @sSql + ' and [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ''
	exec(@sSql)
	DECLARE @sSql1  varchar(8000)
	SET @sSql1 = 'UPDATE TA_Tbl_TemporaryShiftAllocation SET  ' + @ColName + '' 
	SET @sSql1 = @sSql1 + ' where EmployeeId in (select EmpId from TA_Tbl_TempShiftAllocation where LoginEmployeeId = '+@loginEmployeeId+')'
	SET @sSql1 = @sSql1 + ' and [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ''
	exec(@sSql1)
	--select * from TA_Tbl_TempShiftAllocation
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateActiveLanguage]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

/*
Procedure Name	:	Proc_TA_UpdateActiveLanguage
Description	:	Set Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	16-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_UpdateActiveLanguage] 
@Language_Id int
as
Update TA_Tbl_MultiLingual set IsActive=1 where Language_Id=@Language_Id
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAPIEmployeeLogs]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAPIEmployeeLogs] 
	-- Add the parameters for the stored procedure here
	@logID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if not exists(select AutoID from ta_tbl_EmployeeAPILog)
		begin
			INSERT INTO [dbo].[ta_tbl_EmployeeAPILog]([LogID],[Log_Timestamp]) VALUES (@LogID,GETDATE())
		end
	else
		begin
			update [ta_tbl_EmployeeAPILog] set LogID=@logID,[Log_Timestamp]=GETDATE()
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateAttandanceCode]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_updateAttandanceCode]
	@AttandanceID as int,
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@EmpID as int
AS
BEGIN
	update  TA_Tbl_AttandanceCode set 
				AttandanceCode=@AttandanceCode,
				AttandanceValue=@AttandanceValue,
				CompanyID=@CompanyID,
				EmpID=@EmpID where 
		AttandanceID=@AttandanceID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAttendance]
(
  @ShiftId int,
  @WorkHrs nvarchar(10),
  @Attendance nvarchar(20),
  @Process_Rec_ID BIGINT
)
AS
BEGIN
	UPDATE TA_TBL_PROCESSEDDATA SET SHIFT_ID = @SHIFTID,WORKHRS = @WORKHRS,ATTENDANCE = @ATTENDANCE,PROCESSFLAG = 1 
	WHERE PROCESS_REC_ID = @PROCESS_REC_ID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance_Eastman]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <01-April-2019 02:44 PM>
-- Description:	<Updating the attendance as per the shift creation and allocation to employees>
-- Proc_TA_UpdateAttendance_Eastman '787','2019-03-08 00:00:00.000',4,'Present','Absent','11:31:00','',14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAttendance_Eastman]
	@EmployeeCodeID VARCHAR(50),
	@Date DATETIME,
	@EmpCategoryID INT,
	@FirstSession VARCHAR(20),
	@SecondSession VARCHAR(20),
	@Intime VARCHAR(10),
	@Outtime VARCHAR(10),
	@ShiftID INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @empCategory VARCHAR(30)
	--DECLARE @Shift_StartTime VARCHAR(10)
	--DECLARE @Shift_EndTime VARCHAR(10)
	--DECLARE @Shift_FirstHalf_StartTime VARCHAR(10)
	--DECLARE @Shift_FirstHalf_EndTime VARCHAR(10)
	--DECLARE @Shift_SecondHalf_StartTime VARCHAR(10)
	--DECLARE @Shift_SecondHalf_EndTime VARCHAR(10)
	--DECLARE @Shift_GraceInTime VARCHAR(10)
	--DECLARE @Shift_GraceOutTime VARCHAR(10)
	--select top 1 @EmpCategoryID=EC.CategoryId from TA_Tbl_EmployeeCategory EC
	--inner join TA_Tbl_Employee E on EC.EmployeeId=E.Employee_Id
	--where E.SwipeCardNo=@EmployeeCodeID
	--order by EC.EffectiveDate desc
	SELECT	@EmpCategoryID=empCategory FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	SELECT @empCategory=CategoryName FROM TA_Tbl_Category WHERE CategoryId=@EmpCategoryID
	--SELECT @empCategory
	--SELECT	@Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime,@Shift_FirstHalf_StartTime=Shift_FirstHalf_StartTime,@Shift_FirstHalf_EndTime=Shift_FirstHalf_EndTime,@Shift_SecondHalf_StartTime=Shift_SecondHalf_StartTime,
	--		@Shift_SecondHalf_EndTime=Shift_SecondHalf_EndTime,@Shift_GraceInTime=Shift_GraceInTime,@Shift_GraceOutTime=Shift_GraceOutTime 
	--FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	--STAFF AND SHIFT EXEMPTION
	BEGIN 
		IF(@empCategory='STAFF SHIFT' OR @empCategory='SHIFT EXEMPTION')
		BEGIN
			--select 'Entered'
			IF (@FirstSession not in('Present','Weekly off','Holiday','Absent','RH'))
			BEGIN
				IF(CONVERT(DATETIME,@Intime)>'14:30')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET ANAttendanceCode='Absent' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET ANAttendanceCode='Present' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
			END		
			ELSE
			BEGIN
				IF(@SHIFTID!=-1)
				BEGIN
					--Print 'Entered into first if loop'
					IF(@Intime IS NOT NULL AND @Intime<>'')
					BEGIN
						--Print 'Entered into second if loop'
						IF(CONVERT(DATETIME,@Intime)>'14:30')
						BEGIN
							--Print 'Entered ' + '14:30'
							UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Absent',ANAttendanceCode='Absent' WHERE Employee_Code_Id=@EmployeeCodeID and Date=@Date
						END
						ELSE IF(CONVERT(DATETIME,@Intime)>'11:30')
						BEGIN
							--Print 'Entered ' + '11:30'
							UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Absent' WHERE Employee_Code_Id=@EmployeeCodeID and Date=@Date
						END					
					END
				END
				ELSE
				BEGIN
					SELECT 1
				END
			END			
		END
	END
	--HOD
	BEGIN
	-- As per the client requisition, we dont need to check anything for HOD category employees
		IF(@empCategory='HOD')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Present',ANAttendanceCode='Present' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
			END		
		END
	END	
	--DRIVER SHIFT
	BEGIN
	--For driver category employees if any one punches are available in a day, that time attendance should be updated as present.
		IF(@empCategory='Driver')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				IF((@Intime IS NOT NULL AND @Intime<>'') or (@Outtime IS NOT NULL AND @Outtime<>''))
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Present',ANAttendanceCode='Present' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
			END
		END
	END
	--NIGHT SHIFT
	--select @Date+@Intime,@Date+ '05:00 PM',@Date+ '08:30 PM'
	BEGIN
		IF(@empCategory='Night Shift')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				IF(@Date+@Intime > @Date+ '08:30 PM')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Absent',ANAttendanceCode='Absent' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE IF(@Date+@Intime between @Date+ '05:00 PM' and @Date+ '08:30 PM')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode='Present',ANAttendanceCode='Present' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE
				BEGIN
					--Here need to discuss this point with client
					select 1
				END
			END
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAuditTableandFields]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Christopher S
-- Create date: 08 Jan 08
-- Description:	Update TABLES TA_Tbl_AuditTable and TA_Tbl_AuditField
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAuditTableandFields] 
	-- Add the parameters for the stored procedure here
	@tableName nvarchar(100),
    @tableStatus bit,
    @fieldName nvarchar(100),
    @insertBitStatus bit,
    @updateBitStatus bit,
    @deleteBitStatus bit,
    @fieldStatus bit,
    @opr nvarchar
AS
DECLARE @tableId decimal
DECLARE @fieldsTableId decimal
DECLARE @tn nvarchar(100)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
--    if(@opr='I')
--       begin
      	   INSERT INTO TA_Tbl_AuditTable(TableName,Status) VALUES(@tableName,@tableStatus) 
           set @tableId = (select @@identity)
--       end
--    else
--      begin
--           UPDATE TA_Tbl_AuditTable SET TableName = @tableName, Status = @tableStatus WHERE TableName = @tableName          
--      end 
    INSERT INTO TA_Tbl_AuditField(TableID,FieldName,InsertBit,UpdateBit,DeleteBit,Status) VALUES(@tableId,@fieldName,@insertBitStatus,@updateBitStatus,@deleteBitStatus,@fieldStatus) 
    set @fieldsTableId = (select @@identity) 
    SELECT @tn = TA_Tbl_AuditTable.TableName FROM TA_Tbl_AuditTable
    INNER JOIN TA_Tbl_AuditField ON TA_Tbl_AuditTable.TableID = TA_Tbl_AuditField.TableID
    WHERE TA_Tbl_AuditField.FieldID = @fieldsTableId   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBLStatusByService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateBLStatusByService]
	-- Add the parameters for the stored procedure here	
	@Process_Rec_Id bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET Attendance = 'Present',Status = 'BL',ProcessFlag = 1, fnAttendanceCode='Present', anAttendanceCode='Present' 
	WHERE Process_Rec_Id = @Process_Rec_Id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBonusLeavesForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan.
-- Create date: <28-09-2015>
-- Description:	<Updating the Bonus Leave Datas>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateBonusLeavesForService]	
AS
BEGIN	
	SET NOCOUNT ON;
	CREATE TABLE #TempBonusLeave
	(
		AutoId int identity(1,1),
		EmployeeID int,
		SwipeCardNumber varchar(40),
		BonusLeaveQuota int,
		FromDate smalldatetime,
		ToDate smalldatetime
	)
	INSERT INTO #TempBonusLeave
	SELECT	E.Employee_Id,
			E.SwipeCardNo,
			EBL.BonusLeaveQuota,
			YS.FromDate,
			YS.ToDate FROM Ta_Tbl_EmployeeBonusLeave EBL
	INNER JOIN TA_Tbl_Employee E ON  E.Employee_Id=EBL.EmployeeId
	INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id=EBL.YearSettingId
	WHERE E.IsDeleted=0 and E.Employee_Status=1 and YS.IsActive=1 and EBL.BonusLeaveQuota >0
	DECLARE @intBonusLeaveAvailable INT
	SET @intBonusLeaveAvailable= 0
	DECLARE @ApplicableBLs INT
	DECLARE @Count INT
	DECLARE @start INT
	SET @start=1
	SET @Count=(SELECT COUNT(*)FROM #TempBonusLeave)
	WHILE(@Count>=@start)
		BEGIN			
			DECLARE @SwipeCardNumber VARCHAR(40)
			DECLARE @YS_FromDate SMALLDATETIME
			DECLARE @YS_ToDate SMALLDATETIME
			DECLARE @AvailedBLCount int
			SELECT @SwipeCardNumber=SwipeCardNumber,@YS_FromDate=FromDate,@YS_ToDate=ToDate,@ApplicableBLs=BonusLeaveQuota from #TempBonusLeave where AutoId=@start
			SELECT @AvailedBLCount=Count(Process_Rec_Id) FROM  Ta_Tbl_ProcessedData
			WHERE Employee_Code_Id=@SwipeCardNumber AND (Date BETWEEN @YS_FromDate AND @YS_ToDate) AND Status='BL'
			SET @intBonusLeaveAvailable = 0
			DECLARE @DynamicQuery VARCHAR(MAX)
			set @DynamicQuery=''
			IF @ApplicableBLs >@AvailedBLCount
			BEGIN
				SET @intBonusLeaveAvailable = @ApplicableBLs-@AvailedBLCount				
				SET @DynamicQuery='UPDATE TA_Tbl_ProcessedData SET Attendance = ''Present'',Status = ''BL'',ProcessFlag = 1, 
				fnAttendanceCode=''Present'', anAttendanceCode=''Present'' 
				WHERE Process_Rec_Id in
				(
					SELECT TOP '+CONVERT(VARCHAR(20),@intBonusLeaveAvailable) +' Process_Rec_Id FROM TA_Tbl_Processeddata 
					WHERE Employee_Code_Id = '+Convert(varchar(20),@SwipeCardNumber)+' AND Attendance = ''Absent'' AND 
					(Date BETWEEN '''+CONVERT(VARCHAR(20),@YS_FromDate) +''' AND '''+ CONVERT(VARCHAR(20),@YS_ToDate)+''') ORDER BY Date ASC
				)'
				Execute(@DynamicQuery)
			End
			SET @start=@start+1
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockProcess]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_UpdateClockProcess]
@EmployeeId as int, 
@dtmStartDate as datetime,
@dtmToDate as datetime
AS
BEGIN
Declare @SwipeCardNo as nvarchar(20)
--Get swipecardno from employee table
set @SwipeCardNo=(SELECT SwipeCardNo FROM TA_Tbl_Employee Where Employee_Id = @EmployeeId and Isdeleted=0)
--update raw data table
update TA_Tbl_Clk_RawData set CLK_Flag=0 where (clk_Date between @dtmStartDate
and @dtmToDate) and CLK_CARDID=@SwipeCardNo and CLK_PROCESS=0 and CLK_Flag=1 
UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0
WHERE Employee_Code_Id = @SwipeCardNo 
AND [Date] between @dtmStartDate and @dtmToDate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours '06/14/2020',420,'Approved',4,4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]	
	@ShiftDate datetime,
	@ApprovedMinutes int,
	@status varchar(50),
	@approvedby bigint,
	@Task_EmployeeID bigint
AS
BEGIN
	SET NOCOUNT ON;
	IF(@status='Approved')
	BEGIN
		if(@ApprovedMinutes!=0)
		BEGIN
			/************************Get Shift Details for the current Date******************/
			Create table #TempShiftID(Shiftid int)				
			Insert into #TempShiftID(Shiftid)				
			select pd.Shift_Id from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Employee_Id=@Task_EmployeeID and Isdeleted=0
			/*Shift is not available get default / no shift for allocation based on the employeee level*/
			IF Not EXISTS(SELECT Shiftid FROM #TempShiftID)
			BEGIN
				Declare @EmpLevelID int
				/*********Get Employee Level details for get***********/
				create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
				insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
				(
					select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
					inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
					where emp.Isdeleted=0 
					and(emp.Employee_Id=@Task_EmployeeID)
					group by EmployeeId
				) ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
				AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
				select @EmpLevelID=LevelId from #EmpLevel
				DECLARE @CompanyId INT
				IF(ISNULL(@EmpLevelID,'')!='')
				BEGIN						
					;with getCompanyID
					as
					(
						SELECT id,parentId FROM Ta_Tbl_levelDetails where id=@EmpLevelID
						union all
						select ld.id,ld.parentId from getCompanyID gc
						inner join Ta_Tbl_levelDetails ld on ld.id=gc.parentId
					)
					select top 1 @CompanyId=id from getCompanyID where parentId=0
				end
				/************************Get Default or No shift for allocation ******************/
				if exists(select Shift_Id from TA_Tbl_Shift where DefaultShift=1)
				begin
					Insert into #TempShiftID(Shiftid)
					select Shift_Id from TA_Tbl_Shift where DefaultShift=1 and Level_Id=@CompanyId
				END
				ELSE
				BEGIN
					Insert into #TempShiftID(Shiftid)
					SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName ='Nos' AND IsDeleted = 0
				END
			END
			/*Shift is not available get default / no shift for allocation based on the employeee level*/
			IF EXISTS(SELECT Shiftid FROM #TempShiftID)
			BEGIN
				IF((SELECT top 1 Shiftid FROM #TempShiftID)!=-1)
				BEGIN
					DECLARE @currentDayShiftID int
					DECLARE @ShiftStartTime varchar(20)
					Declare @Break2StartTime varchar(20)
					Declare @Break2EndTime varchar(20)
					Declare @Break2Diff int
					SELECT @currentDayShiftID =Shiftid FROM #TempShiftID
					select @ShiftStartTime=Shift_StartTime,@Break2StartTime=Shift_BreakStartTime2,@Break2EndTime=Shift_BreakEndTime2 from TA_Tbl_Shift where Shift_Id=@currentDayShiftID and Isdeleted=0
					select @Break2Diff=isnull(DATEDIFF(minute,convert(datetime,@Break2StartTime),convert(datetime,@Break2EndTime)),0)
					if(@ShiftStartTime!='')
					begin						
						Declare @ManualEntry_EmployeeId NVARCHAR(20)
						Declare @ManualEntry_Date DATETIME
						Declare @InDate NVARCHAR(15)
						Declare @InTime NVARCHAR(20) 
						Declare @InPunchType NVARCHAR(25)
						Declare @OutDate NVARCHAR(15)
						Declare @OutTime NVARCHAR(20)
						Declare @OutPunchType NVARCHAR(25)
						Declare @InReader_Id INT
						Declare @OutReader_Id INT  
						Declare @Reason NVARCHAR(255)
						Declare @RouteId INT
						Declare @TimeStamp DATETIME
						Declare @UserId INT
						Declare @YearSettings_Id NVARCHAR(25)
						Declare @IsOnDuty INT
						Declare @IsImported int
						DECLARE @ShiftEndTime datetime
						IF EXISTS(SELECT Entrance_Id FROM TA_Tbl_Entrance where Entrance_Name='TimecheckPhase')
						BEGIN								
							Declare @CountDevice int	
							Declare @InDeviceAutoID int
							Declare @OutDeviceAutoID int
							select @CountDevice=COUNT(distinct Reader_Id)from TA_Tbl_Entrance_INOUTDetails 	EIO
							inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
							where Entrance_Name='TimecheckPhase'							
							IF(@CountDevice=1)
							BEGIN
								select distinct @InDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name='TimecheckPhase'								
								SELECT @InReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@InDeviceAutoID
								set @OutReader_Id=@InReader_Id
								set @OutDeviceAutoID=@InDeviceAutoID
							END
							ELSE
							BEGIN
								select top 1 @InDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name='TimecheckPhase' and EIO.Type='In'
								select top 1 @OutDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name='TimecheckPhase' and EIO.Type='Out'
								SELECT @InReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@InDeviceAutoID
								SELECT @OutReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@OutDeviceAutoID								
							END
							select top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InDeviceAutoID
							and PunchType in('Shift In','In')
							select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutDeviceAutoID
							and PunchType in('Shift Out','Out')
							select @ManualEntry_EmployeeId=Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@Task_EmployeeID
							select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
							set @ManualEntry_Date=CONVERT(varchar(11), GETDATE())
							set @OutDate=CONVERT(varchar(11),CONVERT(datetime,@ShiftDate))
							set @InDate=@OutDate
							set @InTime=@ShiftStartTime
							set @ShiftEndTime=DATEADD(minute,@ApprovedMinutes+@Break2Diff,@ShiftStartTime)
							set @OutTime=case when len(ltrim(right(convert(varchar, @ShiftEndTime, 22),11)))=10 then '0'+right(convert(varchar, @ShiftEndTime, 22),10) else right(convert(varchar, @ShiftEndTime, 22),11) end
							set @Reason='TimeSheet Entry - Automatic Time Updation'
							set @RouteId=0
							set @TimeStamp=GETDATE()
							set @UserId=@approvedby
							set @IsOnDuty=0
							set @IsImported=4
							--select  @ManualEntry_EmployeeId,@ManualEntry_Date,@InDate,@InTime,@InPunchType,@OutDate,
							--@OutTime,@OutPunchType,@InReader_Id,@OutReader_Id,@Reason,@RouteId,@status,@TimeStamp,@UserId,@YearSettings_Id,@IsOnDuty,@IsImported;
							if exists(select ManualTimeEntry_Id from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id=@ManualEntry_EmployeeId
							and ManualTimeEntry_InDate=@InDate and ManualTimeEntry_InPunchType=@InPunchType
							and ManualTimeEntry_OutDate=@OutDate and ManualTimeEntry_InPunchType=@OutPunchType and IsImported=@IsImported)
							BEGIN
								update TA_Tbl_ManualTimeEntry set ManualTimeEntry_InTime=@InTime,ManualTimeEntry_OutTime=@OutTime,Clk_Process='N'
								where ManualTimeEntry_Employee_Id=@ManualEntry_EmployeeId
								and ManualTimeEntry_InDate=@InDate and ManualTimeEntry_InPunchType=@InPunchType
								and ManualTimeEntry_OutDate=@OutDate and ManualTimeEntry_InPunchType=@OutPunchType and IsImported=@IsImported
							END
							ELSE
							BEGIN
								Execute [Proc_TA_InsertManualTimeEntry]	@ManualEntry_EmployeeId,@ManualEntry_Date,@InDate,@InTime,@InPunchType,@OutDate,
								@OutTime,@OutPunchType,@InReader_Id,@OutReader_Id,@Reason,@RouteId,@status,@TimeStamp,@UserId,@YearSettings_Id,@IsOnDuty,@IsImported;
							end
						END
					END
				END
			END			
		END
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Update 2nd grid info which is already exist employee info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]
@EmployeeCodeId varchar(30),
--@EmployeeName varchar(100),
--@Designation varchar(100),
--@Level	varchar(250),
@DOJ datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Declare @DesignationId int
	--Declare @LevelId int
	--Declare @ParentLevelId int
	--set @DesignationId = 0;

	IF Exists(select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id = @EmployeeCodeId)
	Begin
		update ta_tbl_employee set DateOfJoining = @DOJ where (Employee_Code_Id = @EmployeeCodeId) 
	End

	--set @DesignationId = (select isnull(TitleId,0) from TA_Tbl_Title)
	--set @LevelId = (select isnull(levelID,0) from TA_Tbl_Level)
	--set @ParentLevelId =(select dbo.Func_TA_GetParentIds(convert(varchar,@LevelId)))

	--select * from TA_Tbl_Employee
	--select * from TA_Tbl_EmployeeDesignation
	--select * from TA_Tbl_EmployeeLevel
	--select * from TA_Tbl_Level
	--select * from TA_Tbl_Title

	

END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateConcurrentUser]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_UpdateConcurrentUser] 
@UserId nvarchar(10),  
@IpAddress nvarchar(15),  
@SessionId nvarchar(25)  
as  
update ta_tbl_concurrentuser   
set status = 0 where UserId=@UserId and IpAddress=@IpAddress and SessionId=@SessionId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateDefaultRights '6,7,10,15,68,12,16,64,17,94,95,18,19,20,69,99,100,21,22,23,24,96,25,26,98,97,27,28,29,60,76,62,102,108,37,38,65,36,35,34,41,30,40,45,39,33,44,32,42,43,79,71,70,80,84,89,92,93,101,105,47,48,49,50,51,52,53,72,103,110,54,55,66,67,75,77,78,104,106,107,109','1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDefaultRights]
	-- Add the parameters for the stored procedure here
	@enterprisePageIds varchar(8000),
	@parenIds varchar(8000),
	@employeeId int 	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
declare @concat as nvarchar(100)
declare @concatPID as nvarchar(100)
declare @pos as int
declare @pos1 as int
declare @flag as int
if (@enterprisePageIds is null or @enterprisePageIds='')    
    set @flag=0
else
    set @flag=1    
while (@flag=1)
    Begin
        set @pos = charINDEX(',',@enterprisePageIds)
		set @pos1 = charINDEX(',',@parenIds)
        if (@pos=0)
            Begin
                select @concat = @enterprisePageIds
                set @enterprisePageIds=''
				select @concatPID = @parenIds
                set @parenIds=''
            End
        else
            Begin
                select @concat = substring(@enterprisePageIds,0,@pos)
				select @concatPID = substring(@parenIds,0,@pos1)
            End
		declare @exists as int
		set @exists = (select count(*) from TA_Tbl_userRights where pageId=cast(@concat as float) and groupId=1)
		if(@exists=0)
			INSERT INTO TA_Tbl_userRights (groupName,groupId,pageId,pageGroupId,addPrv,modifyPrv,deletePrv,viewPrv,isDeleted,employeeId) 
			VALUES ('SuperAdmin',1,cast(@concat as float),cast(@concatPID as int),1,1,1,1,0,@employeeId)
        set @enterprisePageIds = substring(@enterprisePageIds,@pos+1,len(@enterprisePageIds))
		set @parenIds = substring(@parenIds,@pos1+1,len(@parenIds))
        if (@enterprisePageIds is null or @enterprisePageIds='')
            set @flag=0
        else
            set @flag=1            
    End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultSE]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDefaultSE]
	-- Add the parameters for the stored procedure here
	@gradeName nvarchar(50),
    @gradeLevel int,
	@empAutoId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
declare @RecordCount as int
set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=0)    
if(@RecordCount=0)
	begin
	INSERT INTO TA_Tbl_Grade(Grade_Name,Grade_Level,Emp_ID,Time_Stamp,Isdeleted) VALUES(@gradeName,@gradeLevel,@empAutoId,getdate(),0)
	select @@identity
	UPDATE TA_Tbl_Title SET GradeID = @@identity
	UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> '18000000'
	DELETE TA_Tbl_Grade WHERE Grade_ID <> @@identity
    DELETE FROM TA_Tbl_ApprovalSettings
	end
else
begin
	UPDATE TA_Tbl_Title SET GradeID = (select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=0)
	UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> '18000000'
	DELETE TA_Tbl_Grade WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=0)
    DELETE FROM TA_Tbl_ApprovalSettings
end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By	: Prabakaran.P
Created On	: 17-Dec-09
*/
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]
@LevelId int,  
@ToMailIds varchar(4000), 
@CCMailIds varchar(4000)
AS
BEGIN
Update TA_Tbl_LevelDetails set ToMailIds=@ToMailIds,
CCMailIds=@CCMailIds where Id=@LevelId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name	:	Proc_TA_EmployeeOTStatus  
Description		:	To Update the OverTime Status in ta_tbl_processedData  table
Tables Included :	ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		:	A.K.T.MOORTHI
Created On		:	22-July-2013
Modified By		:	A.K.T.MOORTHI
Modified On		:	02-AUG-2013
Description		:	BUG FIXING FOR 0018037 NO.
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
--[Proc_TA_UpdateEmployeeCompOffOTStatus]'<NewDataSet><ColumnValues><Process_Rec_ID>3422</Process_Rec_ID><Employee_ID>12</Employee_ID><Employee_Code_ID>1007</Employee_Code_ID><Date>2015-05-01T00:00:00+05:30</Date><Employee_FirstName>VinojOTCOMPOFF</Employee_FirstName><Level_x0020_Name>Production Erode Branch</Level_x0020_Name><HrsExtra>05:20</HrsExtra><ExtraMins>320</ExtraMins><OverTimeStatus>Forwarded</OverTimeStatus><CompOffEligible>1</CompOffEligible><OTEligible>1</OTEligible><CompOffChecked>0</CompOffChecked><OTChecked>1</OTChecked><Status>Approved</Status><TopLevelID>1</TopLevelID><IsUpdated>U</IsUpdated></ColumnValues></NewDataSet>'
*/  
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]
	@Xml XML
As
BEGIN 

    
	set nocount on
	DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,[Date] varchar(20), HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT, DateToExpired DATETIME, NoOfDays NUMERIC(18,1), RemainingDays NUMERIC(18,1), CompOffSatus VARCHAR(30), TopLevelId INT, UpdatedRow VARCHAR(1))
	DECLARE @Index INT 
	set @Index= 0
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	INSERT INTO @TblRecords(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, TopLevelId)
		SELECT Process_Rec_ID, Employee_Id, convert(varchar(20),[Date]), HrsExtra, ExtraMins, (CASE WHEN CompOffEligible = 1 OR OTEligible = 1 THEN [Status] ELSE 'Pending' END),
		 CompOffEligible, OTEligible, TopLevelId FROM OPENXML(@Index, '/NewDataSet/ColumnValues')
		WITH(
			Process_Rec_ID BIGINT 'Process_Rec_ID',
			Employee_Id INT 'Employee_ID',
			[Date] varchar(50) 'Date',
			HrsExtra VARCHAR(5) 'HrsExtra',
			ExtraMins INT 'ExtraMins',
			[Status] VARCHAR(50) 'Status',
			CompOffEligible BIT 'CompOffChecked',
			OTEligible BIT 'OTChecked',
			TopLevelId INT 'TopLevelID'--,
			--UpdateRow VARCHAR(1) 'UpdateRow'
		   ) AS OT 
		ORDER BY OT.[Date]	
	EXEC sp_xml_removedocument @Index
	UPDATE @TblRecords SET 
		DateToExpired = CASE WHEN TR.OverTimeStatus != 'Pending' 
		AND TR.CompOffEligible = 1 THEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0), CONVERT(datetime,TR.[Date],103)) END,
		--DateToExpired = DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),TR.[Date]),
		--NoOfDays = CASE WHEN TR.OverTimeStatus = 'Approved' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEDIFF(MI,'00:00' ,TR.HrsExtra) / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN CAST(DATEDIFF(MI,'00:00' ,TR.HrsExtra)/ DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) AS NUMERIC(18, 1)) WHEN DATEDIFF(MI,'00:00' ,TR.HrsExtra)/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' END) END,
		--RemainingDays = CASE WHEN TR.OverTimeStatus = 'Approved' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEDIFF(MI,'00:00' ,TR.HrsExtra) / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN CAST(DATEDIFF(MI,'00:00' ,TR.HrsExtra)/ DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) AS NUMERIC(18, 1)) WHEN DATEDIFF(MI,'00:00' ,TR.HrsExtra)/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' END) END,
		NoOfDays =	CASE WHEN TR.OverTimeStatus = 'Approved' AND TR.CompOffEligible = 1 THEN	
										(	CASE	WHEN TR.ExtraMins / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN '1.0' 
														WHEN TR.ExtraMins/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' 
											END
										) 
								END,
		RemainingDays = CASE WHEN TR.OverTimeStatus = 'Approved' AND TR.CompOffEligible = 1 THEN (CASE WHEN TR.ExtraMins / DATEDIFF(MI,'00:00' ,SS.FullDayCompOff) > 0 THEN '1.0' WHEN TR.ExtraMins/ DATEDIFF(MI,'00:00' ,SS.HalfDayCompOff) > 0 THEN '0.5' END) END,
		CompOffSatus = CASE WHEN TR.OverTimeStatus = 'Approved' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),CONVERT(datetime,TR.[Date],103)) < GETDATE() THEN 'Expired' ELSE 'Not Taken' END) END
	FROM @TblRecords TR
	INNER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = TR.Process_RecID
	--LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id
	LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = TR.TopLevelId
	INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest)
		SELECT Process_RecID, Employee_Id,CONVERT(datetime,[Date],103), 
		HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, 
		DateToExpired, NoOfDays, RemainingDays, CompOffSatus,0 FROM @TblRecords 
		WHERE Process_RecID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus)
	UPDATE TA_Tbl_OverTimeStatus SET 
		Process_RecID = TR.Process_RecID,
		Employee_Id = TR.Employee_Id,
		[Date] =CONVERT(datetime,TR.[Date],103),
		HrsExtra = TR.HrsExtra,
		ExtraMins = TR.ExtraMins,
		OverTimeStatus = TR.OverTimeStatus,
		CompOffEligible = TR.CompOffEligible,
		OTEligible = TR.OTEligible,
		DateToExpired = TR.DateToExpired,
		NoOfDays = TR.NoOfDays,
		RemainingDays = TR.RemainingDays,
		CompOffSatus = TR.CompOffSatus,
		isRequest=0
	FROM TA_Tbl_OverTimeStatus OTS
	INNER JOIN @TblRecords TR ON TR.Process_RecID = OTS.Process_RecID
	WHERE ISNULL(OTS.OverTimeStatus, 'Pending') != 'Approved' AND ISNULL(OTS.CompOffSatus, 'Not Taken') != 'Taken' 
	--Added by manikandan.R
	-- On 30-july-2013
	update TA_Tbl_ProcessedData set TA_Tbl_ProcessedData.OvertimeStatus=OS.OverTimeStatus from TA_Tbl_ProcessedData P
	inner join TA_Tbl_OverTimeStatus OS on P.Process_Rec_ID=OS.Process_RecID
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi]
@EmployeeID as int,
@Flexi as int
AS
BEGIN
	update ta_tbl_employee set isFlexible=@Flexi where Employee_ID = @EmployeeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi_All]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_UpdateEmployeeFlexi 0,
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi_All]
(
@Flexi as int,
@xml xml
)
AS
BEGIN
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
  --update ta_tbl_employee set isFlexible=@Flexi where Employee_ID = @EmployeeID
  Update E set E.isFlexible = @Flexi
  from OpenXML(@Index, '/DocumentElement/Table')
  With (empAutoID Bigint 'empAutoId') As xm 
  inner join ta_tbl_employee as E on E.Employee_ID = xm.empAutoID
  Exec sp_xml_removedocument @Index
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEncashmentDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*    
Procedure Name : Proc_TA_UpdateEncashmentDetails    
Description : update Records in TA_Tbl_Encashment    
Tables Included : TA_Tbl_Encashment    
Created By : Prabakaran    
Created On : 23-Mar-09  
Modified By :    
Modified On :    
*/    
CREATE procedure [dbo].[Proc_TA_UpdateEncashmentDetails]    
@EncashmentId bigint,    
@NumberOfDays decimal(18,1),    
@Reason nvarchar(50)    
as    
declare @YearSettingId bigint    
begin    
update TA_Tbl_Encashment set NumberOfDays=@NumberOfDays,Reason=@Reason where EncashmentId=@EncashmentId  
end    
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExistingUserStatusFalse]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateExistingUserStatusFalse] 
	-- Add the parameters for the stored procedure here	
    @UserId nvarchar(10)    
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ConcurrentUser SET Status = 0 WHERE UserId = @UserId AND Status = 1 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExpInfo]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateExpInfo]
(
	@InstalledDate as nvarchar(100),
	@DemoExpiryDate as nvarchar(100)
)
AS
BEGIN
	update TA_Tbl_Demo  set  InstalledDate=@InstalledDate,DemoExpiryDate=@DemoExpiryDate
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExpiryReminderDays_Employees]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: 30-May-2022 11:49 am
-- Description:	Update Reminder days of passport and visa.
-- Proc_TA_UpdateExpiryReminderDays_Employees 2,5,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateExpiryReminderDays_Employees]
	@EmpAutoID bigint,
	@reminderDays int,
	@remindoption int
AS
BEGIN
	SET NOCOUNT ON;
    IF(@remindoption=1)
    BEGIN
		UPDATE TA_Tbl_Employee set PassportRemindDays=@reminderDays,IsPass_LastUpdatedOn=GETDATE() where Employee_Id=@EmpAutoID
	END
	ELSE IF(@remindoption=2)
	BEGIN
		UPDATE TA_Tbl_Employee set VisaRemindDays=@reminderDays,IsVisa_LastUpdatedOn=GETDATE() where Employee_Id=@EmpAutoID
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Updating flag in device database>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]
	-- Add the parameters for the stored procedure here
	@TableName varchar(max),
	@FlagName varchar(50),
	@nIndex bigint
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DynamicQuery varchar(max)=''
	set @DynamicQuery= 'UPDATE '+convert(varchar(max),@TableName) + ' SET ' + convert(varchar(50),@FlagName) + ' = 1 WHERE nIndex=' + convert(varchar(max),@nindex)
	Execute(@DynamicQuery)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateHoliday]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateHoliday](@HolidayId int,@Type char(1),@HolidayType nvarchar(2),@Holiday_FromDate nvarchar(15),@Holiday_Todate nvarchar(15),@Holiday_Description nvarchar(255) )  
AS
BEGIN
	UPDATE TA_Tbl_Holiday SET Holiday_Type=@HolidayType,Holiday_FromDate=@Holiday_FromDate,Holiday_ToDate=@Holiday_Todate,Holiday_Description=@Holiday_Description  WHERE Holiday_Id=@HolidayId
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateInAndOutPunchDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Check whether the InTime lies inbetween any InTime and OutTime in the Clock Details Table for particular Employee>
-- [Proc_TA_UpdateInAndOutPunchDetails] 15241,'07/14/2016','04:00 PM','Out','ANNUAL COMPANY TOUR','59','','M',97739,'O',1,''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateInAndOutPunchDetails]
	@inClk_DeviceId NVARCHAR(20),
	@inClk_Date NVARCHAR(20),
	@inClk_Time NVARCHAR(20),
	@inClk_Type NVARCHAR(20),
	@inClk_Remarks NVARCHAR(20),
	@inClk_User NVARCHAR(20),
	@gstrClockDate NVARCHAR(20),
	@inClk_Status NVARCHAR(20),
	@Clk_Id NVARCHAR(20),
	@Type char(1),
	@RecordFromClockdetails int,
	@strPunchTypeRemarksId NVARCHAR(max)
AS
BEGIN
	SET NOCOUNT ON;
    Declare @Dynamicsql NVARCHAR(max)
	set @Dynamicsql='UPDATE TA_Tbl_ClockDetails SET '
    if(@Type='I')
    begin
		set @Dynamicsql=@Dynamicsql+' Clk_InDeviceId = '''+@inClk_DeviceId+''',Clk_InDate = convert(datetime,'''+@inClk_Date+'''),Clk_InTime = '''+@inClk_Time+''',Clk_InPunchType =N'''+@inClk_Type+''''
		if (@inClk_Status = 'M')
		begin
			set @Dynamicsql=@Dynamicsql+',Clk_Remarks =N'''+@inClk_Remarks +''' ,Clk_User = N'''+@inClk_User + ''''
		end
		set @Dynamicsql=@Dynamicsql+',Clk_Date =convert(datetime,'''+@gstrClockDate+'''),Clk_Status ='''+@inClk_Status +''' WHERE Clk_Id = '''+@Clk_Id + ''''
	end
	else
	begin
		set @Dynamicsql=@Dynamicsql+' Clk_OutDeviceId = '''+@inClk_DeviceId+''',Clk_OutDate = convert(datetime,'''+@inClk_Date+'''),Clk_OutTime = '''+@inClk_Time+''',Clk_OutPunchType = N'''+@inClk_Type+''',Clk_Status =N'''+@inClk_Status+''''
		if (@inClk_Status = 'M') 
		begin                                
			set @Dynamicsql=@Dynamicsql+',Clk_Remarks = N'''+@inClk_Remarks+''',Clk_User = N'''+@inClk_User+''',PunchType_Remarks ='''''
		end                            
		if (@RecordFromClockdetails = 1)
		begin
			set @Dynamicsql=@Dynamicsql+',Clk_Remarks ='''',PunchType_Remarks = N'''+@strPunchTypeRemarksId + ''''
		end
		set @Dynamicsql=@Dynamicsql+' WHERE Clk_Id = ''' + @Clk_Id +''''
	end
	Execute(@Dynamicsql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLastEventofImport_Samsung]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani>
-- Create date: <10-Feb-2020>
-- Description:	<This Procedure update last updation of data for Abraj>
-- [Proc_TA_UpdateLastEventofImport_Samsung] 351,'EmployeData','D:\Manikandan\SAP DOCUMENTS\EMPLOYEE\tam_emp_18_03_2020_7.CSV',
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLastEventofImport_Samsung]
@RowsCount bigint, @DataName varchar(20),@filepath varchar(max),@modifiedDate datetime, @CreationDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	insert into Ta_Tbl_LastUpdationofFile_Samsung values (getdate(), @RowsCount, (select max(Employee_Id) from TA_Tbl_Employee), @DataName,@filepath,@modifiedDate,@CreationDate)
	if(@DataName='EmployeeData')
	begin
		select * from Ta_Tbl_Error_ImportData_Samsung where (createdDate>=dateadd(ss,-60,getdate()) and createdDate<=GETDATE()) and ErrorMsg like 'Employee master File%'
	end
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		R.Manikandan
-- Create date: <21-06-2016>
-- Description:	<Update the userrights table if client upgrade the latest version>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if not exists(select * from sys.tables where name='Ta_tbl_ExistingRightsDetails')
    begin
				create table Ta_tbl_ExistingRightsDetails(id	int,groupName	nvarchar(500),groupId	int,
				pageId	float,pageGroupId	int,addPrv	bit,modifyPrv	bit,deletePrv	bit,viewPrv	bit,isDeleted	bit,timeStamp	datetime,employeeId	decimal)
		end
		delete from Ta_tbl_ExistingRightsDetails
		insert into Ta_tbl_ExistingRightsDetails select * from TA_Tbl_userRights
    Create table #TempPage(Autoid int identity(1,1),pageid int,parentid int)
		Insert into #TempPage 
		select pageId,parentId from TA_Tbl_Page 
		Declare @Start int
		Declare @TotRecord int
		Declare @parentId int
		Declare @pageid int
		set @Start=1
		set @TotRecord=(select COUNT(*) from #TempPage)
		while @Start<=@TotRecord
		begin
			select @parentId=parentid,@pageid=pageid from #TempPage where Autoid=@Start
			if(@pageid in(177))
			begin
				set @parentId=177
			end
			if(@pageid in(179))
			begin
				set @parentId=179
			end
			if(@pageid in(312))
			begin
				set @parentId=312
			end
			if(@pageid in(246))
			begin
				set @parentId=246
			end
			update TA_Tbl_userRights set pageGroupId=@parentId where pageId=@pageid
			set @Start=@Start+1
		end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]
@Opr as varchar(1),  -- U - update , D- Delete
@ID as int,
@Notes as varchar(8000),
@EmpID as int
AS
BEGIN
	if (@Opr='U')
		Begin
			update TA_Tbl_LeaveAnalysisNotes set
					Notes = @Notes,
					EmpID = @EmpID			
			Where
					ID = @ID		
		End
	Else
		Begin
			update TA_Tbl_LeaveAnalysisNotes set
					IsDeleted = 1				
			Where			
					ID = @ID		
		End		
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplication]  
(
	--Proc_TA_UpdateLeaveApplication   45,0,'',0,'','','','','',1.0,''
	@LeaveApplication_Id int,
	@EmployeeID int,
	@Leave_ApplicationDate datetime,
	@LeaveType_id int,
	@Type nvarchar(20),
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@Leave_SessionFrom nvarchar(20),
	@Leave_SessionTo nvarchar(20),
	@NumberOfDays decimal(8,2),
	@Reason nvarchar(50) 
)  
as  
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(2000)
	set @sql=''
	set @sql= @sql + 'UPDATE TA_Tbl_LeaveApplication SET LeaveType_id=''' + cast(@LeaveType_id as nvarchar(20)) + ''',Type= N''' 
	set @sql= @sql + @Type + ''',Leave_FromDate= ''' + cast(@Leave_FromDate as nvarchar(20)) + ''',Leave_ToDate= ''' + cast(@Leave_ToDate as nvarchar(20))
	set @sql= @sql + ''',Leave_SessionFrom=N''' + @Leave_SessionFrom + ''',Leave_SessionTo=N''' + @Leave_SessionTo + ''',NumberOfDays='''set @sql= @sql + cast(@NumberOfDays as nvarchar(10)) + ''',Reason=N''' + @Reason + ''' WHERE LeaveApplication_Id = ' + cast(@LeaveApplication_Id  as nvarchar(10))
	exec(@sql)  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationConversation] 
	-- Add the parameters for the stored procedure here
	@leaveApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int
	--@TimezoneDT nvarchar(100)
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN


	SET NOCOUNT ON;
	if(@status='Resend')
		begin
			UPDATE TA_Tbl_LeaveApplication SET Status = @status,Remarks = @remarks,Emp_Id = @empAutoId WHERE LeaveApplication_Id = @leaveApplicationId
		end	
	SET @leaveConversationCount = (SELECT COUNT(*) FROM TA_Tbl_LeaveConversation WHERE LeaveApplicationId = @leaveApplicationId)
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_LeaveConversation(LeaveApplicationId,CommentsBy,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@leaveApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId,GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationMaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_UpdateLeaveApplicationMaster 323,'To go to temple with my family. (Please consider this as a CL of May-11 Month) '
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationMaster]  
(
--Proc_TA_UpdateLeaveApplicationMaster   
@LeaveApplication_Id int,
@Reason nvarchar(1000) 
)  
as  
begin
	Set NOCOUNT ON;
  UPDATE TA_Tbl_LeaveApplicationMaster SET Reason=@Reason where LeaveApplication_Id=@LeaveApplication_Id
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes] 
	-- Add the parameters for the stored procedure here
	@leaveApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int,
	@ToMailIds nvarchar(4000),
	@CcMailIds nvarchar(4000)
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	-- inert intto TA_Tbl_LeaveConversation
	SET @leaveConversationCount = (SELECT COUNT(*) FROM TA_Tbl_LeavePrivateNotes WHERE LeaveApplicationId = @leaveApplicationId)
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_LeavePrivateNotes(LeaveApplicationId,NotesBy,Notes,OrderBy,Emp_Id,ToMailIds,CcMailIds) 
	VALUES(@leaveApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId,@ToMailIds,@CcMailIds)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
Procedure Name : Proc_TA_UpdateLeaveApplicationSanction  
Description : Update Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included : TA_Tbl_LeaveApplication   
Created By : Prabakaran  
Created On : 24-Jul-07  
Modified By		:	A.K.T.MOORTHI
Modified On		:	23-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:	A.K.T.MOORTHI
Modified On		:	30-Sep-2013
Description		:	Commented For Added/Updated Leave Id For Approvel Status. Bze Already We Have Updated Leave Id(Bug No: 0019153)
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
Proc_TA_UpdateLeaveApplicationSanction 71,'Rejected','NO',1
*/							
CREATE    PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction]  
  --Proc_TA_UpdateLeaveApplicationSanction  '','',''
@LeaveApplication_Id int,  
@Status nvarchar(250),  
@commentsBy int,
@Remarks nvarchar(250),
@auEmpId int  
as  
BEGIN
	declare @sql nvarchar(4000)
	DECLARE @Type VARCHAR(20)
	declare @EmployeeId INT
	declare @NumberOfDays DECIMAL(18, 1)
set @sql=''
set @sql = @sql + 'UPDATE TA_TBL_LeaveApplication set Status=N''' + @Status + ''',Remarks= N''' + @Remarks + ''',Emp_Id='''+ cast(@auEmpId as nvarchar(20))+''' Where LeaveApplication_Id= ' + cast (@LeaveApplication_Id  as nvarchar(10))
UPDATE TA_Tbl_LeaveApplicationExists SET status=@Status WHERE LeaveApplicationId = @LeaveApplication_Id
  exec (@sql)
	SELECT 
		@Type = [Type],
		@EmployeeId = Employee_Id,
		@NumberOfDays = NumberOfDays
	FROM TA_Tbl_LeaveApplication WHERE LeaveApplication_Id = @LeaveApplication_Id
	DECLARE @CompOffId BIGINT 
	set @CompOffId=0
	DECLARE  @RemainingDays NUMERIC(18,1)
	set @RemainingDays =0.0
	DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
	IF(@Type= 'Comp Off' AND @Status = 'Rejected')
	BEGIN
		INSERT INTO @TblRecord
		SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE '%:' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + '%'
		ORDER BY [Date]
		declare @ValCount as int
		SELECT @ValCount=COUNT(*) FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE '%:' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + '%'
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@ValCount=2) THEN @RemainingDays + 0.5 else case when (@ValCount>2) THEN CASE 
				WHEN (@NumberOfDays > NoOfDays) THEN NoOfDays
				ELSE (@RemainingDays + @NumberOfDays) end else NoOfDays end END),
				CompOffSatus = (CASE
					WHEN DateToExpired < GETDATE() THEN 'Expired'
					WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN 'Not Taken' END),
				LeaveApplicationId = case	when @NumberOfDays>0.5 then REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '') 
								else	case	when (select COUNT(Value) from dbo.Split(LeaveApplicationId,':') where Value=@LeaveApplication_Id)=2 
								then ':'+CAST(@LeaveApplication_Id AS VARCHAR(20))
												else REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '') 
										end
					end
			WHERE ExtraTime_Id = @CompOffId
			SELECT @NumberOfDays = case when (@ValCount=2) then (@NumberOfDays - 0.5) else (@NumberOfDays - RemainingDays) end FROM TA_Tbl_OverTimeStatus
				WHERE ExtraTime_Id = @CompOffId
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
		--WHILE ((EXISTS(SELECT Process FROM @TblDRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		--BEGIN
		--	SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblDRecord WHERE Process = 0 ORDER BY Id)
		--	UPDATE TA_Tbl_OverTimeStatus SET
		--		@RemainingDays = RemainingDays,
		--		RemainingDays = (CASE 
		--			WHEN (@NumberOfDays > NoOfDays) THEN (@RemainingDays + @NumberOfDays) - NoOfDays
		--			ELSE (@RemainingDays + @NumberOfDays) END),
		--		CompOffSatus = (CASE
		--			WHEN DateToExpired < GETDATE() THEN 'Expired'
		--			WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN 'Not Taken' END),
		--		LeaveApplicationId = REPLACE(LeaveApplicationId, ':' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '')
		--	WHERE ExtraTime_Id = @CompOffId
		--	SELECT @NumberOfDays = (@NumberOfDays - RemainingDays) FROM TA_Tbl_OverTimeStatus
		--		WHERE ExtraTime_Id = @CompOffId
		--	UPDATE @TblDRecord SET Process = 1 WHERE CompOffId = @CompOffId
		--END
	END
	ELSE IF(@Type= 'Comp Off' AND @Status = 'Approved')
	BEGIN		
		UPDATE TA_Tbl_OverTimeStatus SET CompOffSatus = 'Expired'
		WHERE DateToExpired < GETDATE() AND
			ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
			OverTimeStatus = 'Approved' AND
			CompOffEligible = 1 AND
			Employee_Id = @EmployeeId 
		INSERT INTO @TblRecord
			SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE DateToExpired >= GETDATE() AND
				ISNULL(CompOffSatus, 'Not Taken') = 'Not Taken' AND
				OverTimeStatus = 'Approved' AND
				CompOffEligible = 1 AND
				Employee_Id = @EmployeeId
			ORDER BY [Date]
		/*WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN 0.0 END),
				CompOffSatus = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN 'Not Taken'
					WHEN (@RemainingDays <= @NumberOfDays) THEN 'Taken' END),
				LeaveApplicationId = ISNULL(LeaveApplicationId, '') + ':' + CAST(@LeaveApplication_Id AS VARCHAR(20))
			WHERE ExtraTime_Id = @CompOffId
			SET @NumberOfDays = (@NumberOfDays - @RemainingDays) (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN (@NumberOfDays - @RemainingDays) END)
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
		*/
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*  
Procedure Name : Proc_TA_UpdateLeaveApplicationSanction  
Description : Update Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included : TA_Tbl_LeaveApplication   
Created By : Prabakaran  
Created On : 24-Jul-07  
Modified By :   
Modified On :   
*/  
Create PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]  
  --Proc_TA_UpdateLeaveApplicationSanction  '','',''
@LeaveApplication_Id int,  
@Status nvarchar(250),  
@Remarks nvarchar(250),
@auEmpId int,
@IntimationType nvarchar(20)
as  
BEGIN
declare @sql nvarchar(4000)
set @sql=''
set @sql = @sql + 'UPDATE TA_TBL_LeaveApplication set Status=N''' + @Status + ''',Remarks= N''' + @Remarks + ''',InTimationType= N''' + @IntimationType + ''',Emp_Id='''+ cast(@auEmpId as nvarchar(20))+''' Where LeaveApplication_Id= ' + cast (@LeaveApplication_Id  as nvarchar(10))
exec (@sql)
set @sql=''
set @sql = @sql + 'UPDATE TA_TBL_LeaveApplicationMaster set Status=N''' + @Status + ''',InTimationType= N''' + @IntimationType + ''',Emp_Id='''+ cast(@auEmpId as nvarchar(20))+''' Where LeaveApplication_Id= ' + cast (@LeaveApplication_Id  as nvarchar(10)) 
exec (@sql)
--update the processflag
update Ta_Tbl_ProcessedData set processflag=0
from Ta_Tbl_LeaveApplication t2
inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
t1.date between t2.Leave_FromDate and t2.Leave_ToDate
where t2.LeaveApplication_Id=@LeaveApplication_Id 
declare @intEmployeeId as int
set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id) 
--and CheckedIDs in(@CheckedLeaveApplicationIDs))
--Update year closure
update ta_tbl_yearclosure set Leave_Taken=
(select isnull(sum(NumberOfDays),0.0)
from Ta_Tbl_LeaveApplication
inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status='Approved'
and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId
)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateLevels]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================  
-- Author:  senthil  
-- Create date: 08-Aug-2007  
-- Description: update level name  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_updateLevels]  
 @opr as varchar(1),  
 @lid as int,  
 @lName as nvarchar(100),
 @emp_id as nvarchar(25) 
AS  
BEGIN  
/*   
 if (@opr='C')  
  Begin  
   select count(*) as recCount from ta_tbl_level where levelId!=@lid and levelName=@lName and isDeleted=0  
  End  
 Else  
  Begin  
   update ta_tbl_level set levelname=@lName where levelId=@lid  
  End  
*/  
 declare @recCount as int  
 set @recCount = (select count(*) from ta_tbl_level where levelId!=@lid and levelName=@lName and isDeleted=0)  
 if (@recCount=0)  
  Begin  
   --update ta_tbl_level set levelname=@lName where levelId=@lid  
	declare @sql as nvarchar(1000)
	set @sql = 'update ta_tbl_level set emp_id='+ @emp_id+', levelname= N''' + @lName +''' where levelId='+ cast(@lid as nvarchar(25))
	exec(@sql)
  End  
 select @recCount as recCount  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateMailStatusForPassportVisa]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_UpdateMailStatusForPassportVisa]
	-- Add the parameters for the stored procedure here	
	@tag nvarchar(20) = null,
	@EmployeeID int = 0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here

	IF (@tag = 'Pass')
	BEGIN
		update TA_Tbl_Employee set IsMailSentForPassport = 1 where Employee_Id = @EmployeeID
	END
	ELSE IF (@tag = 'Visa')
	BEGIN
	    update TA_Tbl_Employee set IsMailSentForVisa = 1 where Employee_Id = @EmployeeID
	END
	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/*  
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction  
Description : Update Manual Time Entry Application Details of Employees Based on their ManualTimeEntry_Id  
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Kumuthini.L  
Created On : 09-Jan-09  
Modified By : Sashma   
Modified On : 04-May-2011  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]  
(
@ManualTimeEntry_Id INT,  
@Status NVARCHAR(250),  
@Remarks NVARCHAR(250),
@auEmpId INT  
)
AS 
BEGIN
	SET NOCOUNT ON;
	if not exists(SELECT * FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Id = @ManualTimeEntry_Id AND Clk_Process = 'Y')  
	BEGIN
			UPDATE TA_Tbl_ManualTimeEntry SET ManualTimeEntry_Status= @Status ,ManualTimeEntry_Remarks= @Remarks ,Emp_Id=cast(@auEmpId as nvarchar(20)) WHERE ManualTimeEntry_Id= cast (@ManualTimeEntry_Id  as nvarchar(10))
		return 0
	END
	else
	BEGIN
	   return 1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/* 
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction_Group 
Description : Update Manual Time Entry Application Details for a group of Employees 
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Sashma.S 
Created On : 04-May-2011 
[Proc_TA_UpdateManualEntryApplicationSanction_Group] 'Approved','',1,'<DocumentElement>
  <Table>
    <ManualTimeEntry_Id>453</ManualTimeEntry_Id>
  </Table>
</DocumentElement>'
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group] 
( 
	@Status NVARCHAR(250), 
	@Remarks NVARCHAR(250),
	@auEmpId INT,
	@xml xml 
)
AS 
BEGIN
SET NOCOUNT ON;
	DECLARE @Index int
	set @Index = 0 
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	declare @UpdateCount int
	-- updates the status of the manual entry if is not processed
	UPDATE TA_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@auEmpId as nvarchar(20))
	from OpenXML(@Index, '/DocumentElement/Table')
	with (ManualTimeEntry_Id bigint 'ManualTimeEntry_Id') as xm
	inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
	--Added this new line after gettting scuf client requisition
	where Clk_Process = 'N'
	-- and @auEmpId!=1
	set @UpdateCount = @@ROWCOUNT
	Exec sp_xml_removedocument @Index
	set @Index = 0 
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	declare @ProcessedDataCount int 
	--select the manual entry which is already processed.
	set @ProcessedDataCount = (select count(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
	from OpenXML(@Index, '/DocumentElement/Table')
	with (ManualTimeEntry_Id bigint 'ManualTimeEntry_Id') as xm
	inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
	where Clk_Process = 'Y')
	select @UpdateCount as UpdateCount,@ProcessedDataCount ProcessedDataCount
	Exec sp_xml_removedocument @Index 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateManualNotation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Modified by:R.Manikandan
-- Create DATE:22-10-2015 12.50 PM
-- Description:This function will work above 2005 version only 
-- I am passing intime\outtime also into clkdate. This is major change. it wont support for previous versions
-- if sql server is above 2005 means, we can change the existing procedure like this, but we can't use this procedure directly.
-- Proc_Ta_UPDATEManualNotation N'105','2015-10-20 02:11:00 AM','O','M'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateManualNotation]
	@inSwipeCardNo VARCHAR(50),
	@Clk_DATE VARCHAR(30),	
	@StrType CHAR(1),
	@strClk_Status CHAR(1)
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		DECLARE @ShIFtId INT
		DECLARE @ShIFtStartDATE DATETIME
		DECLARE @ShIFtEndDATE DATETIME
		DECLARE @isNightShIFt INT
		SET @isNightShIFt =0
		SELECT @ShIFtId=ShIFt_Id FROM TA_Tbl_ProcessedData WHERE CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE) AND Employee_Code_Id=@inSwipeCardNo
		SELECT @ShIFtStartDATE=CAST(ShIFt_StartTime as DATETIME),@ShIFtEndDATE=CAST(ShIFt_EndTime as DATETIME)FROM TA_Tbl_ShIFt WHERE ShIFt_Id=@ShIFtId AND Isdeleted=0
		IF( (DATEPART(HOUR,@ShIFtStartDATE) between 12 AND 23) AND DATEPART(HOUR,@ShIFtEndDATE) between 0 AND 11 )
		BEGIN
			SET @isNightShIFt=1
		END
		IF(@strType='I')
			BEGIN
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_InDATE+ManualTimeEntry_InTime) = CONVERT(DATETIME,@Clk_DATE,0) AND Isdeleted=0 AND ManualTimeEntry_Status='Approved')>0)
					BEGIN					
						UPDATE TA_Tbl_ProcessedData SET InNotation=@strClk_Status 
						WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
					END			
			END
		ELSE
			BEGIN
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_OutDATE+ManualTimeEntry_OutTime)=CONVERT(DATETIME,@Clk_DATE,0) AND Isdeleted=0 
				AND ManualTimeEntry_Status='Approved')>0)
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET OutNotation=@strClk_Status 
					WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
				end
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_OutDATE+ManualTimeEntry_OutTime)=DATEADD(d,1,CONVERT(DATETIME,@Clk_DATE,0)) AND Isdeleted=0 AND ManualTimeEntry_Status='Approved')>0)
					BEGIN
						UPDATE TA_Tbl_ProcessedData SET OutNotation=@strClk_Status 
						WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
					END
			END
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
	END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualTimeEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_UpdateManualTimeEntry 329,'10101','09/01/2008','08/29/2008','08:11 AM','In','','','',28,0,'df','09/01/2008 10:41 AM','6'
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualTimeEntry] 
(
	@MID int,
	@ManualEntry_EmployeeId nvarchar(20),
	@ManualEntry_Date nvarchar(15),
	@InDate nvarchar(15),
	@InTime nvarchar(20),
	@InPunchType nvarchar(100),
	@OutDate nvarchar(15),
	@OutTime nvarchar(20),
	@OutPunchType nvarchar(100),
	@InReader_Id int,
	@OutReader_Id int,
	@Reason nvarchar(255),
	@TimeStamp DateTime,
	@UserId int
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @sql NVARCHAR(4000)
	SET @sql = '' 
	IF(@InDate = '')
	 BEGIN  
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId,
											ManualTimeEntry_Date= @ManualEntry_Date,
											ManualTimeEntry_InDate=NULL,
											ManualTimeEntry_InTime=NULL,
											ManualTimeEntry_InPunchType=NULL,
											ManualTimeEntry_OutDate= @OutDate ,
											ManualTimeEntry_OutTime= @OutTime ,
											ManualTimeEntry_OutPunchType=@OutPunchType,
											ManualTimeEntry_InReaderId=NULL,
											ManualTimeEntry_OutReaderId= cast(@OutReader_Id as nvarchar(20)),
											ManualTimeEntry_Reason=@Reason ,
											modify_date= cast(@TimeStamp as nvarchar(20)), 
											modify_By= cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id= cast(@MID as nvarchar(20))
	 END  
	ELSE IF(@OutDate = '')  
	 BEGIN  
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId, 
											ManualTimeEntry_Date= @ManualEntry_Date ,
											ManualTimeEntry_InDate=@InDate ,
											ManualTimeEntry_InTime= @InTime,
											ManualTimeEntry_InPunchType= @InPunchType ,
											ManualTimeEntry_OutDate=NULL,
											ManualTimeEntry_OutTime=NULL,
											ManualTimeEntry_OutPunchType=NULL,
											ManualTimeEntry_InReaderId= cast(@InReader_Id as nvarchar(20)),
											ManualTimeEntry_OutReaderId=NULL,
											ManualTimeEntry_Reason=@Reason,
											modify_date= cast(@TimeStamp as nvarchar(20)),
											modify_By= cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id= cast(@MID as nvarchar(20))
	 END
	ELSE
	  BEGIN
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId , 
											ManualTimeEntry_Date= @ManualEntry_Date ,
											ManualTimeEntry_InDate=@InDate,
											ManualTimeEntry_InTime=@InTime,
											ManualTimeEntry_InPunchType=@InPunchType,
											ManualTimeEntry_OutDate=@OutDate,
											ManualTimeEntry_OutTime=@OutTime,
											ManualTimeEntry_OutPunchType=@OutPunchType,
											ManualTimeEntry_InReaderId=cast(@InReader_Id as nvarchar(20)),
											ManualTimeEntry_OutReaderId=cast(@OutReader_Id as nvarchar(20)),
											ManualTimeEntry_Reason=@Reason,
											modify_date=cast(@TimeStamp as nvarchar(20)), 
											modify_By=cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id=cast(@MID as nvarchar(20))
	  END
	EXEC(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateMasterDataLevelsParent]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateMasterDataLevelsParent]
AS
BEGIN
update Ta_Tbl_ImportMasterData 
set Level1_Id= t2.id
from TA_Tbl_LevelDetails t2
inner join Ta_Tbl_ImportMasterData t1
on t2.name=t1.Level1
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

/* 
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction_Group 
Description : Update Manual Time Entry Application Details for a group of Employees 
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Sashma.S 
Created On : 04-May-2011 
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA] 
( 
@Status NVARCHAR(250), 
@Remarks NVARCHAR(250),
@auEmpId INT,
@xml xml 
)
AS 
BEGIN
DECLARE @Index int
set @Index = 0 
EXEC sp_xml_preparedocument @Index OUTPUT, @xml
SET NOCOUNT ON;
declare @UpdateCount int
-- updates the status of the manual entry if is not processed
UPDATE TA_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@auEmpId as nvarchar(20))
from OpenXML(@Index, '/DocumentElement/Table')
with (ManualTimeEntry_Id bigint 'ManualTimeEntry_Id') as xm
inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
set @UpdateCount = @@ROWCOUNT
Exec sp_xml_removedocument @Index
set @Index = 0 
EXEC sp_xml_preparedocument @Index OUTPUT, @xml
declare @ProcessedDataCount int 
--select the manual entry which is already processed.
set @ProcessedDataCount = (select count(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
from OpenXML(@Index, '/DocumentElement/Table')
with (ManualTimeEntry_Id bigint 'ManualTimeEntry_Id') as xm
inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
select @UpdateCount as UpdateCount,@ProcessedDataCount ProcessedDataCount
Exec sp_xml_removedocument @Index 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOnDutyApplicationConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Gopinath.k
-- Create date:16Jun2014
-- Description:	used for adding the OD conversation.
-- Proc_TA_UpdateOnDutyApplicationConversation 5,'Pending','Test Remarks',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateOnDutyApplicationConversation] 
	-- Add the parameters for the stored procedure here
	@ondutyApplicationId bigint,
	@status nvarchar(50),
	@remarks nvarchar(1050),
	@empAutoId int
AS
DECLARE @OnDutyConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	SET NOCOUNT ON;
	SELECT @OnDutyConversationCount=COUNT(*) FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @ondutyApplicationId
	SET @orderBy = @OnDutyConversationCount + 1
	INSERT INTO TA_Tbl_OnDutyConversation(OnDutyApplicationId,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@ondutyApplicationId, @remarks, @orderBy, @empAutoId,GETDATE())
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOTRoundoffSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateOTRoundoffSettings]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int, 
	@startTime nvarchar(5),
	@endTime nvarchar(5),
	@startMins float,
    @endMins float,
	@roundedAs nvarchar(5)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	INSERT INTO TA_Tbl_OTRoundoffSettings(ShiftSettingId,StartTime,EndTime,StartMins,EndMins,RoundedAs)  VALUES(@shiftSettingId,@startTime,@endTime,@startMins,@endMins,@roundedAs) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOtType]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UpdateOtType] 
	@OtTypeID as int,
	@OtType as varchar(25),
	@OtValue as varchar(25),
	@CompanyID as int,
	@EmpId as int
AS
BEGIN	
	update  TA_Tbl_OtType set 
			OtType=@OtType,
			OtValue=@OtValue,
			CompanyID=@CompanyID,
			EmpID=@EmpID
		where OtTypeID=@OtTypeID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOvertimeHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Proc_TA_UpdateOvertimeHours  '240',0,0,'04:00','00:00','00:00',180,0,0,'03:00','00:00','00:00',2496,'787','15/04/2022',0,0,0,0,0,0,'00:00','00:00','00:00','00:00','00:00','00:00',1,'15/06/2022'
CREATE PROCEDURE [dbo].[Proc_TA_UpdateOvertimeHours]
(
    @intOTHrs		int,
    @intWOFOTHrs	int,
    @intHDOTFrs		int,
    @OTHours		varchar(5),
    @WOFOTHours		varchar(5),
    @HDOTHours		varchar(5),
    @intUpOTHrs		int,
    @intUpWOFOTHrs	int,
    @intUpHDOTFrs	int,
    @UpOTHours		varchar(5),
    @UpWOFOTHours	varchar(5),
    @UpHDOTHours	varchar(5),
    @Pro_RecordID	bigint,
    @Employee_code_id varchar(50),
    @Date varchar(20),
    @Modified_Spec_NormOTMins1 int,
	@Modified_Spec_NormOTMins2 int,
	@Modified_Spec_OffOTMins1 int,
	@Modified_Spec_OffOTMins2 int,
	@Modified_Spec_HolOTMins1 int,
	@Modified_Spec_HolOTMins2 int,
	@Modified_Spec_NormOTHrs1 varchar(10),
	@Modified_Spec_NormOTHrs2 varchar(10),
	@Modified_Spec_OffOTHrs1 varchar(10),
	@Modified_Spec_OffOTHrs2 varchar(10),
	@Modified_Spec_HolOTHrs1 varchar(10),
	@Modified_Spec_HolOTHrs2 varchar(10),
	@uploadedEmpid bigInt,
	@ExpiryDate varchar(20)
)
 AS
BEGIN
	set nocount on
	UPDATE TA_Tbl_ProcessedData SET ActNormOTMins=@intOTHrs,ActOffOTMins=@intWOFOTHrs,
	ActHolOTMins=@intHDOTFrs,ActOTMins=(@intOTHrs + @intWOFOTHrs + @intHDOTFrs),ActHrsOT='00:00',
	ActNormOT=@OTHours,ActOffOT=@WOFOTHours,ActHolOT=@HDOTHours,
	NormOTMins=@intUpOTHrs,OffOTMins=@intUpWOFOTHrs,HolOTMins=@intUpHDOTFrs,
	OTMins=(@intUpOTHrs + @intUpWOFOTHrs + @intUpHDOTFrs),NormOT=@UpOTHours,OffOT=@UpWOFOTHours,
	HolOT=@UpHDOTHours WHERE Process_Rec_ID=@Pro_RecordID;
	
	if(@ExpiryDate is not null)
	BEGIN
		--select CONVERT(datetime,@ExpiryDate)
		UPDATE TA_Tbl_OverTimeStatus set Modified_On=GETDATE(),Modified_By=@uploadedEmpid, DateToExpired=CONVERT(datetime,@ExpiryDate) where Process_RecID=@Pro_RecordID
	END
    --EXEC (@Query)
    IF NOT EXISTS(SELECT Modified_Spec_NormOTMins1 FROM Ta_tbl_specialOvertimeDetails where Employee_code_id=@Employee_code_id and DATE=@Date)
    BEGIN
		INSERT INTO Ta_tbl_specialOvertimeDetails 
		(Employee_code_id,Date,Modified_Spec_NormOTMins1,Modified_Spec_NormOTMins2,Modified_Spec_OffOTMins1,Modified_Spec_OffOTMins2,
		Modified_Spec_HolOTMins1,Modified_Spec_HolOTMins2,Modified_Spec_NormOTHrs1,
		Modified_Spec_NormOTHrs2,Modified_Spec_OffOTHrs1,Modified_Spec_OffOTHrs2,Modified_Spec_HolOTHrs1,Modified_Spec_HolOTHrs2,
		Inserted_By,Inserted_Date)
		VALUES
		(
			@Employee_code_id,
			@Date,
			@Modified_Spec_NormOTMins1,
			@Modified_Spec_NormOTMins2,
			@Modified_Spec_OffOTMins1,
			@Modified_Spec_OffOTMins2,
			@Modified_Spec_HolOTMins1,
			@Modified_Spec_HolOTMins2,
			@Modified_Spec_NormOTHrs1,
			@Modified_Spec_NormOTHrs2,
			@Modified_Spec_OffOTHrs1,
			@Modified_Spec_OffOTHrs2,
			@Modified_Spec_HolOTHrs1,
			@Modified_Spec_HolOTHrs2,
			@uploadedEmpid,
			GETDATE()			
		)
    END
    ELSE
    BEGIN
		UPDATE Ta_tbl_specialOvertimeDetails SET
			Modified_Spec_NormOTMins1	=@Modified_Spec_NormOTMins1,
			Modified_Spec_NormOTMins2	=@Modified_Spec_NormOTMins2,
			Modified_Spec_OffOTMins1	=@Modified_Spec_OffOTMins1,
			Modified_Spec_OffOTMins2	=@Modified_Spec_OffOTMins2,
			Modified_Spec_HolOTMins1	=@Modified_Spec_HolOTMins1,
			Modified_Spec_HolOTMins2	=@Modified_Spec_HolOTMins2,
			Modified_Spec_NormOTHrs1	=@Modified_Spec_NormOTHrs1,
			Modified_Spec_NormOTHrs2	=@Modified_Spec_NormOTHrs2,
			Modified_Spec_OffOTHrs1		=@Modified_Spec_OffOTHrs1,
			Modified_Spec_OffOTHrs2		=@Modified_Spec_OffOTHrs2,
			Modified_Spec_HolOTHrs1		=@Modified_Spec_HolOTHrs1,
			Modified_Spec_HolOTHrs2		=@Modified_Spec_HolOTHrs2,
			Modified_By=@uploadedEmpid,
			Modified_Date=GETDATE()
			WHERE Employee_code_id=@Employee_code_id and DATE=@Date
    END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePassword]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_UpdatePassword]
(
@username NVARCHAR(10),
@password NVARCHAR(50)
)
AS
BEGIN
	UPDATE TA_Tbl_Employee SET Emp_password=@password  WHERE Employee_Id=@username 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplication]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_UpdatePermissionApplication
Description	:	Update Permisssion Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission
Created By	:	Prabakaran
Created On	:	20-Jul-07
Modified By	:	Prabakaran.P
Modified On	:	17-Mar-08
--Proc_TA_UpdatePermissionApplication
*/
CREATE procedure [dbo].[Proc_TA_UpdatePermissionApplication]
	@Permission_Id bigint,
	@PermissionType nvarchar(30),
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime,
	@Reason nvarchar(1000),
	@auEmpId nvarchar(50),
	@status nvarchar(25),
	@CCMail varchar(3000),
	@Permission_Hours varchar(5),
	@YearSettingId varchar(5)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(4000)
	declare @IsDeleted int
	set @Isdeleted=0
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@PermissionDate as nvarchar(50)), 102) and EL.LevelId is not null
	--set @sql=''
	--set @sql='update TA_Tbl_Permission set Permission_Date=''' + convert(nvarchar(20),@PermissionDate,101) +''',
	--Permission_Type=N''' + @PermissionType + ''',Permission_FromTime=''' + cast(@Permission_FromTime as nvarchar(100)) + ''',Permission_ToTime=''' + cast(@Permission_EndTime as nvarchar(100)) + ''','
	--if(@status='Pending' or @status='Forwarded')
	--begin
	--set @sql=@sql + 'Permission_Reason=''' + @Reason + ''','
	--end
	--set @sql=@sql + 'Permission_Status=''' + @status + ''',CCMail=''' + @CCMail + ''',No_Of_Hours=''' + @Permission_Hours + ''',Permission_Hours=''' + @Permission_Hours + ''',IsDeleted=''' + cast(@Isdeleted as nvarchar(10)) + ''',Emp_Id=N'''+ @auEmpId+''',YearSettings_Id=''' +@YearSettingId+''' 
	--where Permission_Id=''' + cast(@Permission_Id as nvarchar(25)) + ''' '
	----where Permission_Id=''' + cast(@Permission_Id as nvarchar(25)) + ''' and Permission_Status=''' + 'Pending'+ ''' '
	--exec(@sql)
	
	update TA_Tbl_Permission set Permission_Date=convert(nvarchar(20),@PermissionDate,101),
	Permission_Type=@PermissionType,
	Permission_FromTime=cast(@Permission_FromTime as nvarchar(100)),
	Permission_ToTime=cast(@Permission_EndTime as nvarchar(100)),
	Permission_Reason=@Reason,	
	Permission_Status=@status,
	CCMail=@CCMail,
	No_Of_Hours=@Permission_Hours,
	Permission_Hours=@Permission_Hours,
	IsDeleted=cast(@Isdeleted as nvarchar(10)),
	Emp_Id=@auEmpId,
	YearSettings_Id=@YearSettingId
	where Permission_Id=cast(@Permission_Id as nvarchar(25))
	
	SELECT P.Permission_Id, LD.Id AS LevelId,P.Permission_Reason as Reason,P.Unplanned FROM TA_Tbl_Permission P
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = P.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
	INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
	WHERE P.Permission_Id = @Permission_Id
	--Remove the temporary tables here  
	drop table #EmpLevel
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplicationConversation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdatePermissionApplicationConversation]
	-- Add the parameters for the stored procedure here
	@PermissionApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	SET NOCOUNT ON;

	declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@empAutoId)

	SELECT @leaveConversationCount=COUNT(*) FROM TA_Tbl_PermissionConversation WHERE PermissionId = @PermissionApplicationId
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_PermissionConversation(PermissionId,CommentsBy,Comments,OrderBy,Emp_Id,TimeStamp) 
	VALUES(@PermissionApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId,@GetUTCTime)
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name	:	Proc_TA_UpdatePermissionSanction
Description		:	Update Permission Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_UpdatePermissionSanction]
	@Permission_Id int,
	@Permission_Status nvarchar(20),
	@Remarks nvarchar(300),
	@auEmpId int  
as
BEGIN
	declare @sql nvarchar(2000)
	set nocount on;

	declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@auEmpId)

		UPDATE TA_Tbl_Permission set Permission_Status=@Permission_Status ,
		Remarks= @Remarks ,Emp_Id= cast(@auEmpId as nvarchar(20)), TimeStamp = @GetUTCTime 
		Where Permission_Id= cast(@Permission_Id as nvarchar(25))
END

--Select * from TA_Tbl_Permission

--SP_Help TA_Tbl_Permission
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePerShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_UpdatePerShiftAllocation] 
(@EmpId int,@year int,@month int,@Day1Shift int,@Day2Shift int,@Day3Shift int,@Day4Shift int,@Day5Shift int,@Day6Shift int,@Day7Shift int,@Day8Shift int,@Day9Shift int,@Day10Shift int,@Day11Shift int,@Day12Shift int,@Day13Shift int,@Day14Shift int,@Day15Shift int,@Day16Shift int,@Day17Shift int,@Day18Shift int,@Day19Shift int,@Day20Shift int,@Day21Shift int,@Day22Shift int,@Day23Shift int,@Day24Shift int,@Day25Shift int,@Day26Shift int,@Day27Shift int,@Day28Shift int,@Day29Shift int,@Day30Shift int,@Day31Shift int)
AS
	BEGIN 
		UPDATE TA_Tbl_TemporaryShiftAllocation SET Day1Shift=@Day1Shift,Day2Shift=@Day2Shift,Day3Shift=@Day3Shift,Day4Shift=@Day4Shift,Day5Shift=@Day5Shift,Day6Shift=@Day6Shift,Day7Shift=@Day7Shift,Day8Shift=@Day8Shift,Day9Shift=@Day9Shift,Day10Shift=@Day10Shift,Day11Shift=@Day11Shift,Day12Shift=@Day12Shift,Day13Shift=@Day13Shift,Day14Shift=@Day14Shift,Day15Shift=@Day15Shift,Day16Shift=@Day16Shift,Day17Shift=@Day17Shift,Day18Shift=@Day18Shift,Day19Shift=@Day19Shift,Day20Shift=@Day20Shift,Day21Shift=@Day21Shift,Day22Shift=@Day22Shift,Day23Shift=@Day23Shift,Day24Shift=@Day24Shift,Day25Shift=@Day25Shift,Day26Shift=@Day26Shift,Day27Shift=@Day27Shift,Day28Shift=@Day28Shift,Day29Shift=@Day29Shift,Day30Shift=@Day30Shift,Day31Shift=@Day31Shift WHERE [Year]=@year and [Month]=@month and  EmployeeId=@EmpId
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedData]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessedData] 
(
  @FirstIn nvarchar(25),
  @LastOut nvarchar(25),
  @ShiftId int,
  @TotalWorkHours nvarchar(10),
  @HrsOT nvarchar(10),
  @NorOT nvarchar(10),
  @WeekOffOT nvarchar(10),
  @HoliOT nvarchar(10),
  @EarlyExit nvarchar(10),
  @LateInTime nvarchar(10),
  @WorkHrs nvarchar(10),
  @LessHours nvarchar(10),
  @ExtraHours nvarchar(10),
  @LateInMins float,
  @EarlyOutMins float,
  @OTmins float,
  @Process_Rec_ID BIGINT
)
AS
     UPDATE TA_Tbl_ProcessedData SET InTime = @FirstIn,OutTime = @LastOut,Shift_Id = @ShiftId,HrsWork = @TotalWorkHours,HrsOT = @HrsOT, NormOT = @NorOT, OffOT = @WeekOffOT, HolOT = @HoliOT,
     EarlyOut = @EarlyExit, LateIn = @LateInTime, Attendance = 'Present', WorkHrs = @WorkHrs, HrsLess = @LessHours,HrsExtra = @ExtraHours,LateInMins = @LateInMins,EarlyOutMins = @EarlyOutMins,OtMins = @OTmins,ProcessFlag = 1                                 
     WHERE Process_Rec_ID = @Process_Rec_ID
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlag]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Proc_TA_UpdateProcessedDataFlag 0,'07/20/2011','07/20/2011',0
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlag]
(
  @EmployeeId nvarchar(20),
  @FromDate DateTime,
  @ToDate DateTime,
  @ProcessFlag int
)
AS
begin
	if(@EmployeeId <> '0')
		BEGIN
			declare @SwipeCardNo as nvarchar(20)
			set @SwipeCardNo=(select SwipeCardNo from TA_TBL_Employee where Employee_Id =@EmployeeId)
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = @ProcessFlag
			WHERE Employee_Code_Id = @SwipeCardNo 
			AND [Date] between @FromDate and @ToDate
		END
	else
		BEGIN
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = @ProcessFlag
			WHERE [Date] between @FromDate and @ToDate
		END
end
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]
	-- Add the parameters for the stored procedure here	
	@EmployeeId nvarchar(20),
	@FromDate DateTime,
	@ToDate DateTime,
	@ProcessFlag int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @IsDeleted BIT
	SET @IsDeleted=0
	DECLARE @Employee_Code_Id VARCHAR(20)
	DECLARE @SwipeCardNo AS NVARCHAR(20)
	DECLARE @dtFROMDate AS DATETIME
	Declare @count int
	Declare @Start int
	set @Start=1
	set @count=(select count(EmployeeId) from TA_Tbl_TempShiftAllocation)
	CREATE TABLE #TA_Tbl_TempShiftAllocation
	(
		AutoId int identity(1,1),
		[EmpID] [int] NOT NULL,
		[EmployeeId] [nvarchar](50) NOT NULL,
		[EmployeeName] [nvarchar](50) NOT NULL,
		[LoginEmployeeId] [int] NOT NULL
	)
	insert into #TA_Tbl_TempShiftAllocation
	select * from TA_Tbl_TempShiftAllocation
	while @count>=@Start
		begin
			set @Employee_Code_Id=(select EmployeeId from #TA_Tbl_TempShiftAllocation where AutoId=@Start)
			--SET @Employee_Code_Id = (SELECT Employee_code_id  FROM Ta_tbl_Employee where Ta_tbl_Employee.Employee_id=@EmployeeID)
			SET @SwipeCardNo = (SELECT SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id and (InActiveDate is null or
			 InActiveDate='' or InActiveDate>=GETDATE()) and isDeleted=0)   
			DELETE FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id = @SwipeCardNo AND Date BETWEEN @FROMDate AND @ToDate  
			DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_Date BETWEEN @FROMDate AND @ToDate 
			SET @dtFROMDate=@FROMDate
			WHILE(@dtFROMDate<=@ToDate)
				BEGIN
					DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_InDate=@dtFROMDate		
					DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_OutDate=@dtFROMDate and Clk_InDate is null			
					UPDATE TA_Tbl_ManualTimeEntry set Clk_Process='N' 
					where (ManualTimeEntry_InDate = @dtFROMDate or ManualTimeEntry_OutDate = @dtFROMDate)		
					SET @dtFROMDate=DateAdd(d,1,@dtFROMDate)
				END				
			UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 WHERE Clk_CardId = @SwipeCardNo AND Clk_Date BETWEEN DateAdd(d,-1,@FROMDate) AND DateAdd(d,1,@ToDate)  
			set @Start=@Start+1			
		end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateProcessedDataForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateProcessedDataForService]
	-- Add the parameters for the stored procedure here
	@UpdateQuery nvarchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--RETRY: -- Label RETRY
	--BEGIN TRY
	--	BEGIN TRANSACTION		
	Execute(@updateQuery)
	--	COMMIT TRANSACTION
	--END TRY
	--BEGIN CATCH	
	--	ROLLBACK TRANSACTION
	--	IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
	--	BEGIN
	--		WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
	--		GOTO RETRY -- Go to Label RETRY
	--	END
	--END CATCH
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessflag]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 12.06 PM>
-- Description:	<Update process flag from previous to next date>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessflag]
	@inClk_EmpId varchar(50),
	@inClockDate varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0 where Employee_Code_Id = @inClk_EmpId 
	and Date BETWEEN DATEADD(d,-1,convert(datetime,@inClockDate)) AND DATEADD(d,1,convert(datetime,@inClockDate))
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateProcessFlagForBonusLeave '12121','1/1/2009 12:00:00 AM'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave] 
	-- Add the parameters for the stored procedure here
	@employeeCodeId nvarchar(25), 
	@processFromDate nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	update ta_tbl_processeddata set processflag = 0 where employee_code_id = @employeeCodeId and date >= CONVERT(DATETIME,'' + cast(@processFromDate as nvarchar(25))  + '', 102)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRawDataFlag]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Update Raw data flag>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRawDataFlag]
	-- Add the parameters for the stored procedure here
	@CLK_ID bigint,
	@ReasonId int,
	@Clk_Flag int,
	@Clk_Process int,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type='C')
	begin
		update TA_Tbl_Clk_RawData set Clk_Flag =@Clk_Flag,Clk_Process = @Clk_Process,ReasonId=@ReasonId where Clk_Id = @CLK_ID
	end
	if(@Type='M')
	begin
		UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'Y' WHERE ManualTimeEntry_Id = @CLK_ID
	end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCount]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRowsCount] 
AS
BEGIN
	DECLARE cur CURSOR STATIC LOCAL FOR
	SELECT TableName,active,Module FROM ta_tbl_pageredirect
	declare @TableNameTemp as varchar(200)
	declare @ActiveTemp as varchar(200)
	declare @ModuleTemp as varchar(500)
	declare @sql as varchar(1000)
	declare @Flag as int
	OPEN cur
	WHILE 1 = 1
	BEGIN
		FETCH cur INTO @TableNameTemp,@ActiveTemp,@ModuleTemp
		IF @@fetch_status <> 0
			BREAK
		if (@ActiveTemp=1)
		Begin
			set @sql =  'update ta_tbl_pageredirect set rows=temp.RecCount from (select * from ('
			set @sql = @sql + ' select count(*) as RecCount   from    ' + @TableNameTemp
			set @sql = @sql +  ' )A)Temp where Active=1 and Tablename= ''' + @TableNameTemp + ''' '		
			exec (@sql)
		End
	END
	update ta_tbl_pageredirect set rows=temp.RecCount from (
	select * from ( 
				select count(*) as RecCount   from    TA_Tbl_Employee where employee_firstname <> 'Administrator'
	 )A)Temp where Active=1 and Tablename= 'TA_Tbl_Employee' 
	declare @RecCount as int
	set @RecCount = (select count(*) from ta_tbl_pageredirect where (Rows =0 or Rows is null) and Active=1)
	Declare @RecTotal as int 
	set @RecTotal = (select count(*) from TA_Tbl_PageMandatoryFlag)
	if @RecCount=0
		Begin	
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlag set MandatoryChecking =0
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlag (MandatoryChecking) values (0)
				End
		End
	Else
		Begin
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlag set MandatoryChecking =1
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlag (MandatoryChecking) values (1)
				End
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCountStandard]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name> Ta_Tbl_PageRedirectStandard
-- Create date: <Create Date,,> TA_Tbl_PageMandatoryFlagStandard
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRowsCountStandard] 
AS
BEGIN
	DECLARE cur CURSOR STATIC LOCAL FOR
	SELECT TableName,active,Module FROM Ta_Tbl_PageRedirectStandard
	declare @TableNameTemp as varchar(200)
	declare @ActiveTemp as varchar(200)
	declare @ModuleTemp as varchar(500)
	declare @sql as varchar(1000)
	declare @Flag as int
	OPEN cur
	WHILE 1 = 1
	BEGIN
		FETCH cur INTO @TableNameTemp,@ActiveTemp,@ModuleTemp
		IF @@fetch_status <> 0
			BREAK
		if (@ActiveTemp=1)
		Begin
			set @sql =  'update Ta_Tbl_PageRedirectStandard set rows=temp.RecCount from (select * from ('
			set @sql = @sql + ' select count(*) as RecCount   from    ' + @TableNameTemp
			set @sql = @sql +  ' )A)Temp where Active=1 and Tablename= ''' + @TableNameTemp + ''' '		
			exec (@sql)
		End
	END
	update Ta_Tbl_PageRedirectStandard set rows=temp.RecCount from (
	select * from ( 
				select count(*) as RecCount   from    TA_Tbl_Employee where employee_firstname <> 'Administrator'
	 )A)Temp where Active=1 and Tablename= 'TA_Tbl_Employee' 
	declare @RecCount as int
	set @RecCount = (select count(*) from Ta_Tbl_PageRedirectStandard where (Rows =0 or Rows is null) and Active=1)
	Declare @RecTotal as int 
	set @RecTotal = (select count(*) from TA_Tbl_PageMandatoryFlagStandard)
	if @RecCount=0
		Begin	
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlagStandard set MandatoryChecking =0
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlagStandard (MandatoryChecking) values (0)
				End
		End
	Else
		Begin
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlagStandard set MandatoryChecking =1
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlagStandard (MandatoryChecking) values (1)
				End
		End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateScheduleStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateScheduleStatus]
(
	@ScheduleIds NVARCHAR(1000),
	@Type varchar(10)
)
AS	
BEGIN
	DECLARE @Query NVARCHAR(3000)
	SET @Query=''
    if(@Type = 'Delete')
		BEGIN
			--SET @Query = 'UPDATE TA_Tbl_EmailSchedule set IsDeleted = 1 WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
			SET @Query = 'DELETE FROM TA_Tbl_EmailScheduleFilters WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
			SET @Query = @Query+';delete from ta_tbl_emailtemplate WHERE ScheduleId IN  (' + @ScheduleIds + ')'
			SET @Query = @Query+';delete from TA_tbl_MailIdsForTriggeringEmail WHERE ScheduleId IN  (' + @ScheduleIds + ')'
			SET @Query = @Query+';DELETE FROM TA_TBL_EMAILSCHEDULE WHERE ScheduleId IN  (' + @ScheduleIds + ')'	
			SET @Query = @Query+';DELETE FROM TA_Tbl_EmailScheduled_Employees WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
		END
	else if(@Type = 'Enable')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_EmailSchedule set Enabled = 1 WHERE ScheduleId IN  (' + @ScheduleIds + ')'
		END
	else if(@Type = 'Disable')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_EmailSchedule set Enabled = 0 WHERE ScheduleId IN  (' + @ScheduleIds + ')'
		END
	EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShift]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,28-November>
-- Description:	<Description,,Delete the Shifts for given period>
-- Proc_TA_UpdateShift 'Day21Shift',185,2009,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShift](@ColName varchar(20),@EmpId int,@Year int,@Month int)
AS
BEGIN
	CREATE TABLE #TemShift( ShiftCount int )	
	DECLARE @count int
	DECLARE @sSql  nvarchar(200)
	DECLARE @notDeleted  nvarchar(2000)
	set @sSql='SELECT COUNT(*) FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and EmployeeId=' + cast(@Empid as varchar(10)) + ''
	INSERT INTO #TemShift EXEC(@sSql)	
	set @count=(SELECT ShiftCount from #TemShift)
	if(@count=0)
		BEGIN	
		SET @sSql='UPDATE TA_Tbl_PermanentShiftAllocation SET  ' + @ColName + ' = 0 WHERE [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and EmployeeId=' + cast(@Empid as varchar(10)) + ''
		SET @notDeleted = 'select ' + @ColName +',  [Year], [Month], EmployeeId  from TA_Tbl_PermanentShiftAllocation where ' + @ColName + ' = 0 and EmployeeId=' + cast(@Empid as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and [Year]= ' + cast(@Year as varchar(10)) + '' 
		EXEC(@sSql)
		EXEC(@notDeleted)
		END
	else
		BEGIN
--		SET @sSql='UPDATE TA_Tbl_TemporaryShiftAllocation SET  ' + @ColName + ' = 0 WHERE [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and EmployeeId=' + cast(@Empid as varchar(10)) + ''
--	
--		
--		EXEC(@sSql)
		SET @sSql='UPDATE TA_Tbl_PermanentShiftAllocation SET  ' + @ColName + ' = 0 WHERE [Year]= ' + cast(@Year as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and EmployeeId=' + cast(@Empid as varchar(10)) + ''
		SET @notDeleted = 'select ' + @ColName +',  [Year], [Month], EmployeeId  from TA_Tbl_PermanentShiftAllocation where ' + @ColName + ' = 0 and EmployeeId=' + cast(@Empid as varchar(10)) + ' and [Month]=' + cast(@Month as varchar(10)) + ' and [Year]= ' + cast(@Year as varchar(10)) + '' 
		EXEC(@sSql)
		EXEC(@notDeleted)
		END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftAllocation]
(
    @Query nVarchar(Max)
)
 AS
BEGIN
      EXEC (@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Proc_TA_UpdateShiftDetails 1,3,'Testing Default Shift','TDS','','09:00 AM','05:30 PM','09:00 AM','12:30 PM','01:00 PM','05:30 PM','','','12:30 PM','01:00 PM',
--'','','','','00:00','00:00',0,'08:00','03:30','04:30',1,0,0
CREATE  PROCEDURE [dbo].[Proc_TA_UpdateShiftDetails]     
(    
	@levelId int,    
	@ShiftId int,    
	@ShiftName nvarchar(50),     
	@ShiftShortName nvarchar(50),     
	@ShiftDescription nvarchar(255),    
	@ShiftStartTime nvarchar(10),    
	@ShiftEndTime nvarchar(10),    
	@Shift_FirstHalf_StartTime nvarchar(10),    
	@Shift_FirstHalf_EndTime nvarchar(10),    
	@Shift_SecondHalf_StartTime nvarchar(10),    
	@Shift_SecondHalf_EndTime nvarchar(10),    
	@ShiftGraceInTime nvarchar(10),    
	@ShiftGraceOutTime nvarchar(10),    
	@ShiftBreakStartTime1 nvarchar(10),    
	@ShiftBreakEndTime1 nvarchar(10),    
	@ShiftBreakStartTime2 nvarchar(10),    
	@ShiftBreakEndTime2 nvarchar(10),    
	@ShiftBreakStartTime3 nvarchar(10),    
	@ShiftBreakEndTime3 nvarchar(10),    
	@ShiftMinTimeOT nvarchar(10),    
	@ShiftMaxTimeOT nvarchar(10),    
	@ShiftWorkingDayOverTime float,    
	@ShiftTotalWorkingHours nvarchar(10),  
	@Shift_FirstHalfWorkingHours nvarchar(10),    
	@Shift_SecondHalfWorkingHours nvarchar(10),    
	@Emp_ID nvarchar(50),
	@DefaultShift int,
@ShiftType bit
	)    
AS    
BEGIN
declare @sql as nvarchar(3000)    
   --UPDATE TA_Tbl_Shift  SET Shift_Name=@ShiftName, Shift_ShortName = @ShiftShortName, Shift_Description=@ShiftDescription,Shift_StartTime=@ShiftStartTime,Shift_EndTime=@ShiftEndTime,Shift_GraceInTime=@ShiftGraceInTime,Shift_GraceOutTime=@ShiftGraceOutTi
   --me,Shift_BreakStartTime1=@ShiftBreakStartTime1,Shift_BreakEndTime1=@ShiftBreakEndTime1,Shift_BreakStartTime2=@ShiftBreakStartTime2,Shift_BreakEndTime2=@ShiftBreakEndTime2,Shift_BreakStartTime3 =@ShiftBreakStartTime3,Shift_BreakEndTime3=@ShiftBreakEndTime3
   -- ,Shift_MinTimeOT= @ShiftMinTimeOT, Shift_MaxTimeOT=@ShiftMaxTimeOT,Shift_WorkingDay_OverTime=@ShiftWorkingDayOverTime,Shift_Holiday_OverTime=@ShiftHolidayOverTime,Shift_Weekoff_OverTime= @ShiftWeekoffOverTime,Shift_TotalWorkingHours=@ShiftTotalWorkingHou
   --rs WHERE Shift_Id=@ShiftId 
	Declare @OldGraceShiftIn nvarchar(6)
	Declare @OldGraceShiftOut nvarchar(6)
	Declare @Shift_BreakStartTime1	nvarchar(10)
	Declare @Shift_BreakEndTime1	nvarchar(10)
	Declare @Shift_BreakStartTime2	nvarchar(10)
	Declare @Shift_BreakEndTime2	nvarchar(10)
	Declare @Shift_BreakStartTime3	nvarchar(10)
	Declare @Shift_BreakEndTime3	nvarchar(10)
	select @OldGraceShiftIn=Shift_GraceInTime,@OldGraceShiftOut=Shift_GraceOutTime,
	@Shift_BreakStartTime1=Shift_BreakStartTime1,
	@Shift_BreakEndTime1=Shift_BreakEndTime1,
	@Shift_BreakStartTime2=Shift_BreakStartTime2,
	@Shift_BreakEndTime2=Shift_BreakEndTime2,
	@Shift_BreakStartTime3=Shift_BreakStartTime3,
	@Shift_BreakEndTime3=Shift_BreakEndTime3		
    from TA_Tbl_Shift where Shift_Id=@ShiftId
   insert into ta_tbl_GraceDetails values(@ShiftId,@OldGraceShiftIn,@OldGraceShiftOut,  @Shift_BreakStartTime1,
   @Shift_BreakEndTime1,	@Shift_BreakStartTime2,	@Shift_BreakEndTime2,	@Shift_BreakStartTime3,	@Shift_BreakEndTime3,   GETDATE())
   Declare @DefShift int
	if exists(select DefaultShift from TA_Tbl_Shift where Level_Id=@levelId and DefaultShift=1)
		begin	
			if(@DefaultShift=1)
				begin
					update ta_tbl_shift set DefaultShift=0 where Level_Id =@levelId 
				end
		end
   set @sql = 'UPDATE TA_Tbl_Shift  SET Level_Id='+cast(@levelId as nvarchar(25))+', Shift_Name=N'''+@ShiftName+''', Shift_ShortName = N'''+@ShiftShortName+''', Shift_Description=N'''+@ShiftDescription+''',Shift_StartTime=N'''+@ShiftStartTime+''',
   Shift_EndTime=N'''+@ShiftEndTime+''',Shift_FirstHalf_StartTime=N'''+@Shift_FirstHalf_StartTime+''',Shift_FirstHalf_EndTime=N'''+@Shift_FirstHalf_EndTime+''',Shift_SecondHalf_StartTime=N'''+@Shift_SecondHalf_StartTime+''',Shift_SecondHalf_EndTime=N'''+
   @Shift_SecondHalf_EndTime+''',Shift_GraceInTime=N'''+@ShiftGraceInTime+''',Shift_GraceOutTime=N'''+@ShiftGraceOutTime+''',Shift_BreakStartTime1=N'''+@ShiftBreakStartTime1+''',Shift_BreakEndTime1=N'''+@ShiftBreakEndTime1+''',Shift_BreakStartTime2=N'''+
   @ShiftBreakStartTime2+''',Shift_BreakEndTime2=N'''+@ShiftBreakEndTime2+''',Shift_BreakStartTime3 =N'''+@ShiftBreakStartTime3+''',Shift_BreakEndTime3=N'''+@ShiftBreakEndTime3+''' ,Shift_MinTimeOT= N'''+ @ShiftMinTimeOT +''', Shift_MaxTimeOT=N'''+ @ShiftMaxTimeOT +''',
   Shift_WorkingDay_OverTime='+cast(@ShiftWorkingDayOverTime as nvarchar(25))+',Shift_TotalWorkingHours=N'''+@ShiftTotalWorkingHours+''',Shift_FirstHalfWorkingHours=N'''+@Shift_FirstHalfWorkingHours+''',Shift_SecondHalfWorkingHours=N'''+
   @Shift_SecondHalfWorkingHours+''',Emp_ID=N''' + @Emp_ID + ''',DefaultShift='+cast(@DefaultShift as nvarchar(25))+ ',ShiftType=' + cast(@ShiftType as nvarchar(1)) + ',ModifiedDate=''' + cast(GETDATE() as nvarchar(25)) + ''' WHERE Shift_Id='+cast(@ShiftId as nvarchar(25))+''  
   exec(@sql)  
    --if(cast(@DefaultShift as nvarchar(1))='1')
    --BEGIN
    --  update TA_Tbl_Shift set DefaultShift=0 where Shift_Id<>@ShiftId and Level_Id=@levelId
    --END 
END
  
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Velumani P>
-- Create date: <19/07/2019>
-- Description:	<Update Shift Id in permenent table for Vaigai - Reg Auto Shift Configuration>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]
@Shift_Id int, @EmployeeCodeId varchar(40), @ShiftDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @year INT
	DECLARE @month INT
	DECLARE @day INT
	DECLARE @DynamicQuery VARCHAR(MAX)
	declare @EmployeeId int
	SELECT @year=DATEPART(YEAR,@ShiftDate),@month=DATEPART(MONTH,@ShiftDate),@day=DATEPART(DAY,@ShiftDate) 
	select @EmployeeId = isnull(Employee_Id,0) from TA_Tbl_Employee where Employee_Code_Id = @EmployeeCodeId
	SET @DynamicQuery =''
	--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
	IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EmployeeId)
	Begin
		if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EmployeeId)
		begin
			SET @DynamicQuery =@DynamicQuery +'update TA_Tbl_PermanentShiftAllocation set day'+CONVERT(VARCHAR(2),@day)+'shift='+CONVERT(VARCHAR(2),@Shift_Id)+ ' where
			month='+CONVERT(VARCHAR(2),@month)+' and year='+CONVERT(VARCHAR(4),@year)+' and employeeid='+CONVERT(VARCHAR(40),@EmployeeId)
		end
		else
		begin
			SET @DynamicQuery =@DynamicQuery +'insert into TA_Tbl_PermanentShiftAllocation (day'+CONVERT(VARCHAR(2),@day)+'shift,month,year,employeeid,Emp_id,dateshift)
			values('+CONVERT(VARCHAR(2),@Shift_Id)+ ','+CONVERT(VARCHAR(2),@month)+','+CONVERT(VARCHAR(4),@year)+','+CONVERT(VARCHAR(40),@EmployeeId)+',1,'''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+''')'
		end
		exec (@DynamicQuery)
	End
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftReport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Karthikeyan.R
-- Create date: 10-Aug-2016
-- Description:   Update Shift Setting week month start and end day update in default company
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftReport]
      -- Add the parameters for the stored procedure here
      @WeekStartDay nvarchar(3),
      @WeekEndDay nvarchar(3),
      @MonthStartDay nvarchar(3),
      @MonthEndDay nvarchar(3),
      @MapKey nvarchar(max)
AS
BEGIN
      SET NOCOUNT ON;
      update ta_tbl_shiftsettings set CumulativeWeekStartDay=@WeekStartDay,CumulativeWeekEndDay=@WeekEndDay,MonthStartDay=@MonthStartDay,MonthEndDay=@MonthEndDay,MapKey=@mapkey
      select -1 as 'ShiftSettingId'
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftRoaster]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftRoaster]
(@levelId int,@RoasterId int,@RoasterName nvarchar(25),@NoOfPatterns int,@Pattern1 int,@Pattern2 int,@Pattern3 int,@Pattern4 int,
 @Pattern5 int,@Pattern6 int,@Pattern7 int,@Pattern8 int,@Pattern9 int,@Pattern10 int,@Employee_Id int)
 AS
declare @sql as nvarchar(3000)
	BEGIN
--		UPDATE TA_Tbl_ShiftRoaster SET ShiftRoaster_Name=@RoasterName,NumberOfPatterns=@NoOfPatterns,Pattern1=@Pattern1,Pattern2=@Pattern2,Pattern3=@Pattern3,Pattern4=@Pattern4,			
--			   Pattern5=@Pattern5,Pattern6=@Pattern6,Pattern7=@Pattern7,Pattern8=@Pattern8,Pattern9=@Pattern9,Pattern10=@Pattern10,Emp_Id=@Employee_Id WHERE ShiftRoaster_Id=@RoasterId
       set @sql ='UPDATE TA_Tbl_ShiftRoaster SET Level_Id='+cast(@levelId as nvarchar(25))+',ShiftRoaster_Name=N'''+@RoasterName+''',NumberOfPatterns='+cast(@NoOfPatterns as nvarchar(25))+',Pattern1='+cast(@Pattern1 as nvarchar(25))+',Pattern2='+cast(@Pattern2 as nvarchar(25))+',Pattern3='+cast(@Pattern3 as nvarchar(25))+',Pattern4='+cast(@Pattern4 as nvarchar(25))+',
                                                 Pattern5='+cast(@Pattern5 as nvarchar(25))+',Pattern6='+cast(@Pattern6 as nvarchar(25))+',Pattern7='+cast(@Pattern7 as nvarchar(25))+',Pattern8='+cast(@Pattern8 as nvarchar(25))+',Pattern9='+cast(@Pattern9 as nvarchar(25))+',Pattern10='+cast(@Pattern10 as nvarchar(25))+',Emp_Id='+cast(@Employee_Id as nvarchar(25))+' WHERE ShiftRoaster_Id='+cast(@RoasterId as nvarchar(25))+''
       exec(@sql)
	END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftSettings]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	01-Apl-2013
-- Description		:	Adding the New Column(Default Lunch hrs)
-- Modified by Gopinath on 18Jun14 for Angler Migration added new column named as 'ExceptionHours'
-- [Proc_TA_UpdateShiftSettings]'OT',27,'','',''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftSettings] 
(
	@tag nvarchar(10),
	@CompanyId as int,
	@maxHoursBeforeShift as varchar(10),
	@maxHoursAfterShift as varchar(10),
	@shiftBreak as varchar(10),
	@shiftMaxBreakHours as varchar(10),
	@monthlyWorkingHours as varchar(10),
	@weeklyWorkingHours as varchar(10),
	@AuditEmp as nvarchar(20),
	@HolidayOT as float,
	@WeekOffOT as float,
	@otOption as varchar(10),
	@strMonthClosureDate as varchar(20),
	@flexibleStatus int,
	@flexibleValue int,
	@otStatus int,		
	@fullAttendance int,
	@halfAttendance int,
	@DefaultLunchHours VARCHAR(10),
	@MaxLunchHrs NVARCHAR(5),
	@WeekOffStartHours as varchar(5),
	@IgnorePunch tinyint,
	@IgnorePunchInterval varchar(5),
	@AfterShiftTime bit,
	@BeforeShiftTime bit,
	@DefinedWorkhrs bit,
	@NoOfSuccessiveDaysInYear int,
	@CompensationValidityDays int,
	@HalfDayCompOff VARCHAR(5),
	@FullDayCompOff VARCHAR(5),
	@VaildityCompOffDays INT,
	@LateEntry bit,
	@EarlyEntry bit,
	@EarlyExit bit,
	@LateExit bit,
	@IsLunchDeduction bit,
	@LunchDeductionHours nvarchar(10)='00:00',
	@ExceptionHours as varchar(10),
	@24maxHoursBeforeShift as varchar(10),
	@24weeklyWorkingHours as varchar(10),
	@Flexi_AfterShiftTime	bit,
	@Flexi_BeforeShiftTime	bit,
	@Flexi_DefinedWorkhrs	bit,
	@CumulativeWeekStartDay as varchar(10),
	@CumulativeWeekEndDay as varchar(10),	
	@isCarryForwardCOff int,
	@isRequestingforCompOff int,
	@FirstAndLast bit,
	@SpecialOverTime1 int,
	@SpecialOverTime2 int
	
	--the 2 bewlow fields for vaigai --
	,@LateMinsPerDay int
	,@LateDaysPerMonth int

		--the 2 bewlow fields for sohit--
    ,@EarlyExitperDay int
	,@EarlyExitDaysPerMonth int

	--1 field for vaiagai late point--
	,@EnableAbsent bit
	,@isLOPRequired int
	,@isRemindRrd_Pas_Vis bit,
	@reminderDays int,
	@mon int,
	@tues int,
	@wed int,
	@thurs int,
	@fri int,
	@satur int,
	@sun int
)	
AS
BEGIN
		declare @cou as int
		Select @cou = count(*) from TA_Tbl_shiftSettings where CompanyId=@CompanyId
		if(@tag='OT')
		begin
			update TA_Tbl_shiftSettings set 
				HolidayOT=@HolidayOT,
				WeekOffOT=@WeekOffOT, 
				otOption=@otOption , 
				OTRoundoffEnable=@otStatus,
				AfterShiftTime=@AfterShiftTime,
				BeforeShiftTime=@BeforeShiftTime,
				DefinedWorkhrs=@DefinedWorkhrs,
				HalfDayCompOff = @HalfDayCompOff,
				FullDayCompOff = @FullDayCompOff,
				VaildityCompOffDays = @VaildityCompOffDays,
				Flexi_AfterShiftTime=@Flexi_AfterShiftTime,
				Flexi_BeforeShiftTime=@Flexi_BeforeShiftTime,
				Flexi_DefinedWorkhrs=@Flexi_DefinedWorkhrs,
				Carry_Forward_COff_Year=@isCarryForwardCOff,
				isRequestingforCompOff=@isRequestingforCompOff,
				SpecialOverTime1=@SpecialOverTime1,
				SpecialOverTime2=@SpecialOverTime2
				where CompanyId=@CompanyId
			  select ShiftSettingId from TA_Tbl_shiftSettings where CompanyId=@CompanyId
		end
		else
		begin
			if (@cou>0)
			Begin
				update TA_Tbl_shiftSettings set 
				maxHoursBeforeShift=@maxHoursBeforeShift, 
				maxHoursAfterShift=@maxHoursAfterShift,
				shiftBreak=@shiftBreak,
				shiftMaxBreakHours=@shiftMaxBreakHours,
				monthlyWorkingHours=@monthlyWorkingHours,
				weeklyWorkingHours=@weeklyWorkingHours, 
				EmpID=@AuditEmp,
				DefaultMonthClosureDate=@strMonthClosureDate,
				IsFlexible = @flexibleStatus,
				FlexibleFlag=@flexibleValue,
				FullDayAttendance=@fullAttendance,
				halfdayAttendance=@halfAttendance,
				WeeklyOffStartHours=@WeekOffStartHours,
				IgnoreDuplicatePunch=@IgnorePunch,
				PunchInterval=@IgnorePunchInterval,
				NoOfSuccessiveDaysInYear=CONVERT(int, @NoOfSuccessiveDaysInYear),
				lateEntry=@LateEntry,
				EarlyEntry=@EarlyEntry,
				EarlyExit=@EarlyExit,
				LateExit=@LateExit,
				timestamp1=getdate(),
				IsLunchDeduction=@IsLunchDeduction,
				LunchDeductionHours=@LunchDeductionHours,
				MaxHoursBeforeShift_24HrsShift=@24maxHoursBeforeShift,
				WeeklyOffStartHours_24HrsShift=@24weeklyWorkingHours,
				CumulativeWeekStartDay=@CumulativeWeekStartDay,
				CumulativeWeekEndDay=@CumulativeWeekEndDay,
				DefaultLunchHours = @DefaultLunchHours,
				MaxLunchHours = @MaxLunchHrs,
				MaxWorkPlaceInHours=@ExceptionHours,
				FirstAndLast=@FirstAndLast
				,LateMinsPerDay=@LateMinsPerDay
				,LateDaysPerMonth=@LateDaysPerMonth
				,EarlyExitMinsPerDay=@EarlyExitperDay
				,EarlyExitDaysPerMonth=@EarlyExitDaysPerMonth
				,EnableAbsent=@EnableAbsent
				,isLOPDisplayed=@isLOPRequired,
				reminderDays=@reminderDays,
				isRemindRrd_Pas_Vis=@isRemindRrd_Pas_Vis,
				mon=@mon,
				tues=@tues,
				wed =@wed,
				thurs =@thurs ,
				fri =@fri,
				satur=@satur ,
				sun =@sun
				where CompanyId=@CompanyId
			  select ShiftSettingId from TA_Tbl_shiftSettings where CompanyId=@CompanyId
			End
			Else
				Begin
					insert into Ta_Tbl_ShiftSettings (CompanyId,HolidayOT,WeekOffOT, otOption,maxHoursBeforeShift,maxHoursAfterShift,shiftBreak,shiftMaxBreakHours,monthlyWorkingHours,weeklyWorkingHours,EmpID,DefaultMonthClosureDate,IsFlexible,FlexibleFlag,OTRoundoffEnable,FullDayAttendance,halfdayAttendance,WeeklyOffStartHours,IgnoreDuplicatePunch,PunchInterval,AfterShiftTime,BeforeShiftTime,DefinedWorkhrs,NoOfSuccessiveDaysInYear,CompensationValitityDays, HalfDayCompOff, FullDayCompOff, VaildityCompOffDays
					,lateEntry,EarlyEntry,EarlyExit,LateExit
					,timestamp,timestamp1,IsLunchDeduction,LunchDeductionHours,Flexi_AfterShiftTime,Flexi_BeforeShiftTime,Flexi_DefinedWorkhrs,MaxHoursBeforeShift_24HrsShift,WeeklyOffStartHours_24HrsShift
					,CumulativeWeekStartDay,CumulativeWeekEndDay, DefaultLunchHours, MaxLunchHours,MaxWorkPlaceInHours,Carry_Forward_COff_Year,isRequestingforCompOff,FirstAndLast
					,LateMinsPerDay
					,LateDaysPerMonth
					,EarlyExitMinsPerDay
					,EarlyExitDaysPerMonth
					,EnableAbsent
					,isLOPDisplayed,
					reminderDays,
					isRemindRrd_Pas_Vis,
					mon ,tues,wed,thurs,fri,satur,sun
					) 
					values (@CompanyId,null,null, null,@maxHoursBeforeShift,@maxHoursAfterShift,@shiftBreak,@shiftMaxBreakHours,@monthlyWorkingHours,@weeklyWorkingHours,@AuditEmp,@strMonthClosureDate,@flexibleStatus,@flexibleValue,null,@fullAttendance,@halfAttendance,@WeekOffStartHours,@IgnorePunch,@IgnorePunchInterval,null,null,null,CONVERT(int,@NoOfSuccessiveDaysInYear),@CompensationValidityDays, null, null, null
				,@LateEntry,@EarlyEntry,@EarlyExit,@LateExit
					,getdate(),GETDATE(),@IsLunchDeduction,@LunchDeductionHours,null,null,null,@24maxHoursBeforeShift,@24weeklyWorkingHours,@CumulativeWeekStartDay,@CumulativeWeekEndDay,@DefaultLunchHours,
					 @MaxLunchHrs,@ExceptionHours,@isCarryForwardCOff,@isRequestingforCompOff,@FirstAndLast
					 ,@LateMinsPerDay
					 ,@LateDaysPerMonth
					 ,@EarlyExitperDay
					 ,@EarlyExitDaysPerMonth
					 ,@EnableAbsent
					 ,@isLOPRequired
					 ,@reminderDays,
					 @isRemindRrd_Pas_Vis,
					 @mon ,	@tues ,	@wed ,@thurs ,@fri ,@satur ,@sun
					 )
					select @@identity
				End
			end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateSMSTemplateDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <06-09-2016>
-- Description:	<Updating Receivers Details for single Templates>
-- select Value from dbo.Split('Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights',';')
-- Proc_TA_UpdateSMSTemplateDetails 2,'Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights','01:00','01:00','Dear {User Name}, The following employees are late comers today,{Employee ID}-{Employee Name}-{Late By Hrs}.',1
-- Proc_TA_UpdateSMSTemplateDetails 2,'Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights','01:00','01:00','Dear {User Name}, The following employees are late comers today,{Employee ID}-{Employee Name}-{Late By Hrs}.',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateSMSTemplateDetails]
	-- Add the parameters for the stored procedure here
	@TemplateID int,
	@Receivers varchar(max),
	@firstNotification varchar(5),
	@secondNotification varchar(5),
	@Message varchar(max),
	@ModifiedBy varchar(50),
	@ToEmployee int,
	@LessHrsLimitation varchar(5),
	@Continue_AbsentDays int,
	@RepoFilters varchar(max),
	@ReportType varchar(50),
	@Tags varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	if exists(select COUNT(*) from Ta_Tbl_SMSTemplates where id=@TemplateID)
	begin
		update Ta_Tbl_SMSTemplates set Message=@Message,LastModified=GETDATE(),ModifiedBy=@ModifiedBy,First_TriggeringTime=@firstNotification,
		Second_TriggeringTime=@secondNotification,ToEmployee=@ToEmployee,LessHrsLimitation=@LessHrsLimitation,Continue_AbsentDays=@Continue_AbsentDays
		,Tags=@Tags
		where id=@TemplateID
		if exists(select * from Ta_tbl_SMSTemplateFilters where TemplateId=@TemplateID)
		begin
			update Ta_tbl_SMSTemplateFilters set Filters= @RepoFilters,ReportType=@ReportType where TemplateId=@TemplateID
		end
		else
		begin
			if(@RepoFilters!='')
			begin
				insert into Ta_tbl_SMSTemplateFilters values(@TemplateID,@RepoFilters,@ReportType)
			end
		end
		Create table #SplittedgrpIDs(id int identity(1,1),ids varchar(max))
		insert into #SplittedgrpIDs select Value from dbo.Split(@Receivers,';')
		delete from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID		
		Declare @Count int
		Declare @Start int
		Declare @Ids varchar(100)
		SET @Start=1
		SET @Count=(select COUNT(*) from #SplittedgrpIDs)		
		while @Count>=@Start
		begin			
			select @ids=ids from #SplittedgrpIDs where id=@Start
			if exists(select groupId from TA_Tbl_Usergroup where groupName=@Ids)
			begin
				insert into Ta_Tbl_SMSReceivers values((select top 1 groupId from TA_Tbl_Usergroup where groupName=@Ids),@TemplateID,GETDATE(),@ModifiedBy)
			end
			set @Start=@Start+1
		end		
	end  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateSyncFlagDetails_Oracle]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateSyncFlagDetails_Oracle]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	Insert into ta_tbl_oracleSync values(getdate(),GETDATE(),1)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTempShiftAlloc]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_UpdateTempShiftAlloc]
(
@EmployeeID int,
@ShiftID int,
@date int,
@month int,
@year int,
@EmpID int,
@Timestamp nvarchar,
@DateShift nvarchar
)
as
Begin
declare @query nvarchar(2000)
set @query='Update TA_Tbl_TemporaryShiftAllocation set Day' + cast(@date as nvarchar) +'Shift= ' + cast(@ShiftID as nvarchar) + ',[Emp_Id]=' + cast(@EmpID as nvarchar) + 'Where EmployeeId=' + cast(@EmployeeID as nvarchar)+ ' And [Year]=' + cast(@year as nvarchar) + ' And [Month]=' + cast(@month  as nvarchar)
exec (@query)
End
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTimesheetEntry]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateTimesheetEntry]
	@TaskDetailID BIGINT,	
	@ApprovedHours varchar(10),
	@status varchar(50),
	@approvedby bigint,
	@Task_EmployeeID bigint,
	@Comments varchar(500)
AS
BEGIN	
	SET NOCOUNT ON;
	if(@TaskDetailID!='' and @status!='')
	begin
		update ta_tbl_taskprogressdetails set Status=@status where TaskDetailID=@TaskDetailID	
		Insert into ta_tbl_taskprogressStatus values(@TaskDetailID,@ApprovedHours,@approvedby,GETDATE(),@Comments,@status)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserProfile]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Manikandan.R
-- Create date: 16-08-2017
-- Description:	Updating User profile details by users from mobile app
-- updateUserProfile/json?EmpAutoID=48&fatherName=Rajendran&motherName=Mother%20Name&officialmail=manikandan.rr@angleritech.com&address=4/75,koniappa%20pillai%20street,%20kurichi,%20sundarapuram(post),%20Coimbatore-641024&bloodgrp=B%20ive&image=
-- Proc_TA_UpdateUserProfile 48,'Rajendran.r','usharani','manikandan.rr@angleritech.com','4/75,koniappa%20pillai%20street,%20kurichi,%20sundarapuram(post),%20Coimbatore-641024','B%20ive',''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateUserProfile] 
	-- Add the parameters for the stored procedure here
	@EmpAutoID int, 
	@fatherName varchar(100),
	@motherName varchar(100),
	@officialmail varchar(200),
	@address varchar(500),
	@bloodgrp varchar(20),
	@image image=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Update TA_Tbl_Employee set Father_name=@fatherName,Mother_name=@motherName,EmailId=@officialmail,Permanent_Address=@address,
	Blood_Group=@bloodgrp,Photo=@image where Employee_Id=@EmpAutoID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateUserStatus] 
	-- Add the parameters for the stored procedure here
	@UserId nvarchar(15),
    @IpAddress nvarchar(15),
    @LoginTime datetime,
    @Status bit,
    @SessionId nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	 INSERT INTO TA_Tbl_ConcurrentUser(UserId, IpAddress, LoginTime, Status, SessionId) VALUES(@UserId, @IpAddress, @LoginTime, @Status, @SessionId) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author			:	Prabakaran.P
-- Create date		: 
-- Modified date	:	02-May-11
-- Description		:	Procedure used to Ignore and Include punches
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid] 
@ClkID as int,
@opr as varchar(8)
AS
BEGIN
	Declare @VoidFlag as int
	
	update TA_Tbl_Clk_RawData set	ReasonId=case when (@opr='Void') then 6 else 0 end,
									CLK_FLAG=case when (@opr='Void') then 1 else 0 end,
									CLK_PROCESS=0
	Where Clk_ID = @ClkID
	
	declare @InTime as datetime
	declare @InDate as datetime
	declare @OutDate as datetime
	declare @OutTime as datetime
	declare @CardID as varchar(100)
	declare @EmpID as varchar(100)			
	declare @dtClockDate as datetime
	
	select  @InDate  = Clk_Date,
			@InTime  = cast(convert(varchar(10),CLK_TIME,108) as datetime ),
			@CardID = CLK_CARDID
	from TA_Tbl_Clk_RawData   where  Clk_ID = @ClkID
	
	update TA_Tbl_Clk_RawData set CLK_FLAG=0,CLK_PROCESS=0 
	where CLK_CARDID=@CardID and CLK_DATE=@InDate and ReasonId=0
	
	select @EmpID=employee_code_id from ta_tbl_employee where 
	isdeleted=0 and employee_status=1 and swipecardno=@CardID
	
	delete from ta_tbl_clockdetails where Clk_Date=@InDate and Clk_EmpId=@CardID
	
	delete from TA_Tbl_ProcessedData from TA_Tbl_ProcessedData where Date=@InDate and Employee_Code_Id=@CardID
	
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' 
	WHERE ManualTimeEntry_Employee_Id = @EmpID AND 
	((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@InDate) AND DateAdd(d,1,@InDate)) 
	OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@InDate) AND DateAdd(d,1,@InDate))) 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid_Group]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Sashma
-- Create date: 04-May-2011
-- Description:	<Description,,>
/*
 [Proc_TA_UpdateVoidUnVoid_Group]
'Void',
'<DocumentElement>
  <Table>
    <Clk_ID>1812</Clk_ID>
    <EmployeeCode>6599</EmployeeCode>
    <EmpName>Rajendran S</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1811</Clk_ID>
    <EmployeeCode>7588</EmployeeCode>
    <EmpName>Sathishkumar S</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1810</Clk_ID>
    <EmployeeCode>7877</EmployeeCode>
    <EmpName>Manikandan R</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1813</Clk_ID>
    <EmployeeCode>1234</EmployeeCode>
    <EmpName>Manikandan </EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1814</Clk_ID>
    <EmployeeCode>1235</EmployeeCode>
    <EmpName>Anitha </EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
</DocumentElement>'
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid_Group] 
	@opr as varchar(8),
	@xml xml
AS
BEGIN
	set nocount on
	create table #TempClockDetails 
	(
		[CLK_ID] [bigint],		
		employee_code_id varchar(50),
		[CLK_DATE] [datetime] NULL,
		[CLK_TIME] [nvarchar](25) NULL
	)
	DECLARE @Index int
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		insert into #TempClockDetails
		select xm.* from OPENXML(@Index, '/DocumentElement/Table',2)
		with (Clk_ID bigint,EmployeeCode varchar(50),InDate varchar(15),InTime varchar(10)) as xm
	Exec sp_xml_removedocument @Index
	
	--Updates the void flag in the ta_tbl_clockdetails table
	update TA_Tbl_Clk_RawData set	ReasonId=case when (@opr='Void') then 6 else 0 end,
									Clk_Process=0,
									CLK_FLAG=case when (@opr='Void') then 1 else 0 end
	from TA_Tbl_Clk_RawData c 
	inner join TA_Tbl_Employee e on e.SwipeCardNo=c.CLK_CARDID
	inner join #TempClockDetails TCD on TCD.CLK_ID=c.CLK_ID
	
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'N' from TA_Tbl_ManualTimeEntry m
	inner join TA_Tbl_Employee e on e.SwipeCardNo=m.ManualTimeEntry_Employee_Id
	inner join  #TempClockDetails TCD on TCD.Employee_Code_Id= e.Employee_Code_Id
	WHERE ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,TCD.Clk_Date) AND DateAdd(d,1,TCD.Clk_Date)) 
	OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,TCD.Clk_Date) AND DateAdd(d,1,TCD.Clk_Date)))
	
	delete from TA_Tbl_ClockDetails from TA_Tbl_ClockDetails C
	inner join TA_Tbl_Employee e on e.SwipeCardNo=C.Clk_EmpId
	inner join #TempClockDetails TCD on (TCD.Employee_Code_Id=e.Employee_Code_Id and C.Clk_Date=TCD.Clk_Date)	
	
	delete from TA_Tbl_ProcessedData from TA_Tbl_ProcessedData P 
	inner join TA_Tbl_Employee e on e.SwipeCardNo=P.Employee_Code_Id
	inner join #TempClockDetails TCD on (TCD.Employee_Code_Id=e.Employee_Code_Id and P.Date=TCD.Clk_Date)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateWhatsAppScheduleStatus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Proc_TA_UpdateWhatsAppScheduleStatus]
(
	@ScheduleIds NVARCHAR(1000),
	@Type varchar(10)
)
AS	
BEGIN
	DECLARE @Query NVARCHAR(3000)
	SET @Query=''
    if(@Type = 'Delete')
		BEGIN
			--SET @Query = 'UPDATE TA_Tbl_EmailSchedule set IsDeleted = 1 WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
			SET @Query = 'DELETE FROM TA_Tbl_WhatsAppScheduleFilters WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
			--SET @Query = @Query+';delete from ta_tbl_emailtemplate WHERE ScheduleId IN  (' + @ScheduleIds + ')'
			SET @Query = @Query+';delete from TA_tbl_WhatsAppIdsForTriggering WHERE ScheduleId IN  (' + @ScheduleIds + ')'
			SET @Query = @Query+';DELETE FROM TA_Tbl_WhatsAppSchedule WHERE ScheduleId IN  (' + @ScheduleIds + ')'	
			SET @Query = @Query+';DELETE FROM TA_tbl_WhatsAppScheduled_Employees WHERE ScheduleId IN  (' + @ScheduleIds + ')'			
		END
	else if(@Type = 'Enable')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_WhatsAppSchedule set Enabled = 1 WHERE ScheduleId IN  (' + @ScheduleIds + ')'
		END
	else if(@Type = 'Disable')
		BEGIN
			SET @Query = 'UPDATE TA_Tbl_WhatsAppSchedule set Enabled = 0 WHERE ScheduleId IN  (' + @ScheduleIds + ')'
		END
	EXEC (@Query)
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosure]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  procedure [dbo].[Proc_TA_UpdateYearClosure]
(
@OrgLevelId INT,
@Employee_Id INT,
@Year_SettingID INT,
@LeaveTypeID INT,
@Available_Leaves FLOAT,
@YearClosed NVARCHAR(50),
@DateClosed NVARCHAR(15),
@Emp_ID INT,
@encashment float
)
AS
begin
	
	/*** Hariharan J *** 16-02-2024** UTC Datetime TimeZone****/
	Declare @UTCTime datetime 
	Set @UTCTime=[dbo].[GetUTCTimeZoneDateTime](@Emp_ID) --Print @UTCTime
	
	UPDATE TA_Tbl_YearClosure
	SET Available_Leaves=@Available_Leaves,YearClosed=@YearClosed,DateClosed=@DateClosed,Emp_ID=@Emp_ID,Time_Stamp=@UTCTime,
	Encashment=@encashment
	WHERE Year_SettingID=@Year_SettingID AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID 

end	
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByEncashment]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Procedure Name	:	Proc_TA_UpdateYearClosureByEncashment
Description		:	Update year closure Encaschment field while Encash sanctioned
Tables Included	:	TA_Tbl_YearClosure and Ta_tbl_yearsetting
Created By		:	Prabakaran
Created On		:	21-Aug-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByEncashment]
@Employee_Id int,
@NumberOfDays decimal(18,1),
@LeaveTypeId int
as
update TA_Tbl_YearClosure set Encashment=isnull(Encashment,0) + @NumberOfDays
where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id
and Year_SettingId=(select YearSettings_Id from Ta_tbl_yearsetting where IsActive=1)
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Procedure Name  : Proc_TA_UpdateYearClosureByLeaveSanction    
Description  : Update year closure leave taken field while Leave sanctioned    
Tables Included  : TA_Tbl_YearClosure     
Created By  : Prabakaran    
Created On  : 21-Aug-07    
Modified By  :     
Modified On  :   
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]  
( 
	@NumberOfDays decimal(18,1),    
	@LeaveTypeId int,  
	@Employee_Id int,  
	@ModeType nvarchar(10),  
	@auEmpId int,
	@YearSetting_ID int  
)  
as  
BEGIN
	
	declare @GetUTCTime Datetime
	Select @GetUTCTime=dbo.GetUTCTimeZoneDateTime(@auEmpId)


	-- A indicates Leave Approved  
	if(@ModeType='A')    
	begin    
		update TA_Tbl_YearClosure set Leave_Taken=isnull(Leave_Taken,0)+@NumberOfDays,Emp_Id=@auEmpId,Time_Stamp=@GetUTCTime
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID   
	end  
	-- R indicates Leave Rejected  
	else if(@ModeType='R')    
	begin  
		update TA_Tbl_YearClosure set Leave_Taken=isnull(Leave_Taken,0)-@NumberOfDays,Emp_Id=@auEmpId,Time_Stamp=@GetUTCTime
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID    
	end  
	-- AB indicates Borrow Leave Approved   
	else if(@ModeType='AB')  
	begin  
		update TA_Tbl_YearClosure set Borrow_NextYear=isnull(Borrow_NextYear,0)+(-@NumberOfDays),Emp_Id=@auEmpId,Time_Stamp=@GetUTCTime  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID
	end  
	-- RB indicates Borrow Leave Rejected    
	else if(@ModeType='RB')  
	begin 
		update TA_Tbl_YearClosure set Borrow_NextYear=isnull(Borrow_NextYear,0)-(-@NumberOfDays),Emp_Id=@auEmpId,Time_Stamp=@GetUTCTime  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID 
	end
END


GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureModify]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_UpdateYearClosureModify]
(
@YearClosureId int,
@Carry_PrevYear float,
@Current_Quota float,
@Borrow_NextYear float,
@Leave_Taken float,
@Available_Leaves float,
@Encashment float
)
AS
UPDATE TA_Tbl_YearClosure
SET Carry_PrevYear=@Carry_PrevYear,
Current_Quota=@Current_Quota,
Borrow_NextYear=@Borrow_NextYear,
Leave_Taken=@Leave_Taken,
Available_Leaves=@Available_Leaves,
Encashment=@Encashment
WHERE YearClosureId=@YearClosureId
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearsetting]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[Proc_TA_UpdateYearsetting](@NewId int)
AS
BEGIN TRANSACTION 
UPDATE Ta_Tbl_Yearsetting SET IsActive=0
UPDATE Ta_Tbl_Yearsetting SET IsActive=1 WHERE YearSettings_Id=@NewId
COMMIT TRANSACTION 
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_UpdatingData_PunchesNotAvailed 2,1,'','Absent','Absent','Absent','07:30','09:30 AM','06:00 PM','',1,0,'','240835'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]
	-- Add the parameters for the stored procedure here		
	@intShiftId int,
	@dblTotalDays bigint,
	@strLeaveCode varchar(20),
	@gstrAttendance varchar(20),
	@strFNAttendanceCode varchar(20),
	@strANAttendanceCode varchar(20),
	@strWorkHrs varchar(10),
	@ActualShfInTime varchar(20),
	@ActualShfOutTime varchar(20),
	@HolidayDescription varchar(max),
	@intYearSettingId int,
	@Variation bigint,
	@No_Of_Hours varchar(20),
	@inProcess_Rec_ID bigint
AS
BEGIN		
	SET NOCOUNT ON;
	Declare @strSQLProcessUpdate varchar(max)
	set @strSQLProcessUpdate=''
	set @strSQLProcessUpdate=@strSQLProcessUpdate+'
	UPDATE TA_Tbl_ProcessedData SET
				--Employee_Code_Id
				--Date
				Shift_Id = ' + convert(varchar(10),@intShiftId) + ',
				Shift_StartTime = ''' + CONVERT(varchar(10),@ActualShfInTime) + ''',
				Shift_EndTime = ''' + convert(varchar(10),@ActualShfOutTime) + ''',
				WorkHrs = '''+ convert(varchar(10),@strWorkHrs) + ''',
				InTime = ''00:00'',
				OutTime = ''00:00'',
				BreakHrs = ''00:00'',
				LunchHrs = ''00:00'',
				PermissionHrs = ''' + Convert(varchar(20),@No_Of_Hours) + ''',
				HrsWork = ''00:00'',
				Attendance =''' + CONVERT(varchar(10),@gstrAttendance) +''',
				HrsOT=''00:00'',
				NormOT=''00:00'',
				OffOT=''00:00'',
				HolOT=''00:00'',
				OvertimeStatus=NULL,
				HrsLess = ''00:00'',
				HrsExtra=''00:00'',
				LateIn=''00:00'',
				EarlyOut=''00:00'',
				BreakHrsInMins = ''0'',
				LunchHrsInMins = ''0'',
				PermissionHrsInMins= ''' + CONVERT(varchar(10),@Variation) + ''',
				HoursWorkInMins = 0,
				----WorkHoursInMins
				----LessHoursInMins
				LateInMins=0,
				EarlyOutMins=0,
				ExtraMins=0,
				OtMins=0,
				LateExit = 0,
				EarlyEntry = 0,
				----InNotation
				----OutNotation
				TotalDays = ' + convert(varchar(10),@dblTotalDays) + ',
				LeaveCode = ''' + convert(varchar(10),@strLeaveCode) + ''',
				----LateEntryReason
				----EarlyOutReason
				Status = NULL,
				IsOnduty=0,
				FNAttendanceCode='''+ CONVERT(varchar(10),@strFNAttendanceCode) +''',
				ANAttendanceCode='''+ CONVERT(varchar(10),@strANAttendanceCode) +''',
				ProcessFlag = 1,				
				--LeaveStatus
				--PermissionStatus
				NormOtmins=0,
				OffOtmins=0,
				HolOtMins=0,
				----CLAvailed
				YearSettingId = ''' + convert(varchar(10),@intYearSettingId) + ''',
				----LeaveType_Id
				Holiday_Description=''' + CONVERT(varchar(10),@HolidayDescription) + ''',
				EarlyInmins=0,
				EarlyInHrs=''00:00'',
				lateExitMins=0,
				LateExitHours=''00:00'',
				ActNormOTMins=0,
				ActOffOTMins=0,
				ActHolOTMins=0,
				ActOTMins=0,
				ActHrsOT=''00:00'',
				ActNormOT=''00:00'',
				ActOffOT=''00:00'',
				ActHolOT=''00:00'',
				Inpunch=NULL,
				Outpunch=NULL,
				Indate=NULL,
				Outdate=NULL				
				WHERE Process_Rec_ID = ' + convert(varchar(10), @inProcess_Rec_ID )
	RETRY:
	BEGIN TRANSACTION
	BEGIN TRY	
		execute(@strSQLProcessUpdate)
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH	
		ROLLBACK TRANSACTION
		IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
		BEGIN
			WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
			GOTO RETRY -- Go to Label RETRY
		END
	END CATCH	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--[Proc_Ta_UpdatingProcessedDataValuesForService]
--@Process_Rec_ID = 239914,@Shift_Id = 2,@Shift_StartTime = N'09:30:00 AM',@Shift_EndTime = N'06:00:00 PM',
--@WorkHrs = N'',@InTime = N'01:51 PM',@OutTime = N'05:51 PM',
--@BreakHrs = N'00:00',@LunchHrs = N'00:00',@PermissionHrs = N'00:00',@HrsWork = N'04:00',@Attendance = N'Attendance',
--@HrsOT = N'00:00',@NormOT = N'00:00',@OffOT = N'00:00',@HolOT = N'00:00',@OvertimeStatus = N'OvertimeStatus',
--@HrsLess = N'03:30',@HrsExtra = N'00:00',@LateIn = N'04:21',@EarlyOut = N'00:00',@BreakHrsInMins = 1,@LunchHrsInMins = 1,@PermissionHrsInMins = 1,
--@HoursWorkInMins = 1,@WorkHoursInMins = 1,@LessHoursInMins = 1,@LateInMins = 1,@EarlyOutMins = 1,@ExtraMins = 1,@OtMins = 1,@LateExit = 1,
--@EarlyEntry = 1,@TotalDays = 1,@Status = null,@IsOnduty = 1,@FNAttendanceCode = N'Absent',@ANAttendanceCode = N'Present',@LeaveStatus = N'1',
--@PermissionStatus = N'1',@NormOtmins = 1,@OffOtmins = 1,@HolOtMins = 1,@CLAvailed = 1,@YearSettingId = 1,@LeaveType_Id = 1,@Holiday_Description = N'',
--@EarlyInmins = 1,@EarlyInHrs = N'00:00',@lateExitMins = 1,@LateExitHours = N'00:00',@Inpunch = N'Shift In',@Outpunch = N'In Duty',@Indate = N'09/18/2015',@Outdate = N'09/18/2015'
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]
(
	@Process_Rec_ID bigint,		
	@Shift_Id	int,
	@Shift_StartTime	nvarchar(40),
	@Shift_EndTime	nvarchar(40),
	@WorkHrs	nvarchar(20),
	@InTime	nvarchar(50),
	@OutTime	nvarchar(50),
	@BreakHrs	nvarchar(20),
	@LunchHrs	nvarchar(20),
	@PermissionHrs	nvarchar(20),
	@HrsWork	nvarchar(20),
	@Attendance	nvarchar(40),
	@HrsOT	nvarchar(20),
	@NormOT	nvarchar(20),
	@OffOT	nvarchar(20),
	@HolOT	nvarchar(20),
	@OvertimeStatus	nvarchar(100),
	@HrsLess	nvarchar(20),
	@HrsExtra	nvarchar(20),
	@LateIn	nvarchar(20),
	@EarlyOut	nvarchar(20),
	@BreakHrsInMins	float,
	@LunchHrsInMins	float,
	@PermissionHrsInMins	float,
	@HoursWorkInMins float,
	@WorkHoursInMins float,
	@LessHoursInMins float,
	@LateInMins	float,
	@EarlyOutMins float,
	@ExtraMins	float,
	@OtMins	float,
	@LateExit	bit,
	@EarlyEntry	bit,	
	@TotalDays	numeric(9),
	--@LeaveCode	nvarchar(40),	
	@Status	nvarchar(100),
	@IsOnduty	bit,
	@FNAttendanceCode nvarchar(30),
	@ANAttendanceCode nvarchar(30),	
	@LeaveStatus nvarchar(100),
	@PermissionStatus nvarchar(100),
	@NormOtmins float,
	@OffOtmins float,
	@HolOtMins float,
	@CLAvailed numeric(5),
	@YearSettingId int,
	@LeaveType_Id int,
	@Holiday_Description nvarchar(500),
	@EarlyInmins int,
	@EarlyInHrs	varchar(20),
	@lateExitMins int,
	@LateExitHours varchar(20),
	@Inpunch varchar(20),
	@Outpunch varchar(20),
	@Indate	datetime,
	@Outdate datetime
)
AS
BEGIN	
	SET NOCOUNT ON;	
	RETRY: -- Label RETRY
	BEGIN TRANSACTION
	BEGIN TRY
		UPDATE TA_Tbl_ProcessedData SET InTime = @InTime,
									OutTime = @OutTime,
									Shift_Id = @Shift_Id,
									HrsWork = @HrsWork,
									LateIn = @LateIn,
									LateInMins = @LateInMins,
									EarlyOut = @EarlyOut,
									EarlyOutMins = @EarlyOutMins,
									HrsOT = @HrsOT ,
									NormOT = @NormOT,
									Status = NULL,
									OffOT = @OffOT,
									HolOT = @HolOT,
									Attendance = @Attendance,
									FNAttendanceCode=@FNAttendanceCode,
									ANAttendanceCode=@ANAttendanceCode,
									BreakHrs = @BreakHrs,
									LunchHrs = @LunchHrs,
									HoursWorkInMins = @HoursWorkInMins,
									BreakHrsInMins = @BreakHrsInMins,
									LunchHrsInMins = @LunchHrsInMins,
									YearSettingId = @YearSettingId,
									Indate=@Indate,
									Outdate=@Outdate,
									Inpunch=@Inpunch,
									Outpunch=@Outpunch,
									Holiday_Description=@Holiday_Description,
									PermissionHrsInMins=@PermissionHrsInMins,
									PermissionHrs = @PermissionHrs,
									WorkHoursInMins=@WorkHoursInMins,
									Shift_StartTime=@Shift_StartTime,
									Shift_EndTime =@Shift_EndTime, 
									WorkHrs= @WorkHrs,   
									OvertimeStatus=@OvertimeStatus,					
									EarlyEntry = @EarlyEntry,
									EarlyInmins =@EarlyInmins,
									EarlyInHrs = @EarlyInHrs,        
									LateExit= @LateExit,
									lateExitMins=@lateExitMins,
									lateExitHours=@lateExitHours,
									HrsLess = @HrsLess,
									HrsExtra = @HrsExtra,
									ExtraMins = @ExtraMins,
									OtMins = @OtMins,
									TotalDays = @TotalDays,
									--LeaveCode = @LeaveCode,
									ProcessFlag = 1,
									LessHoursInMins =@LessHoursInMins
									WHERE Process_Rec_ID = @Process_Rec_ID
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH		
		ROLLBACK TRANSACTION
		IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
		BEGIN
			WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
			GOTO RETRY -- Go to Label RETRY
		END
	END CATCH   
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatingSMSGatewayDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016 16:54>
-- Description:	<Updating SMS gateway details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdatingSMSGatewayDetails]
	-- Add the parameters for the stored procedure here
	@serviceURL varchar(max), 
	@destinationKey varchar(100), 
	@messageKey varchar(100), 
	@phNo varchar(20),
	@EmpID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	delete from ta_tbl_SMSGateway
	Insert into ta_tbl_SMSGateway values(@serviceURL,@destinationKey,@messageKey,getdate(),@phNo,@EmpID)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <27-08-2016>
-- Description:	<Activate and deactivate Templates>
-- [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]'2,3,4,5,6,7,8,9,10,11','Disable',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]
	-- Add the parameters for the stored procedure here
	@TemplateIds varchar(max),
	@Status varchar(10),
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Declare @DynamicSQL varchar(max)
	set @DynamicSQL =''
	set @DynamicSQL =@DynamicSQL+'update Ta_Tbl_SMSTemplates set Status=case when '''+CONVERT(varchar(10), @status)+'''=''Enable'' then 1 else 0 end, 
	ModifiedBy='+CONVERT(varchar(10),@EmployeeID)+' where id in('+CONVERT(varchar(max),@TemplateIds)+')'
	Execute(@DynamicSQL)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserAccessRights_MobileApp]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UserAccessRights_MobileApp]
	@userName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Declare @Defined_Users varchar(max)
	--set @Defined_Users='581','2','7','12','787','758'
    -- Insert statements for procedure here
    if(@userName in('581','2','7','12','787','758'))
    begin
		select 1 as eligible
    end
    else
    begin
		select 0 as eligible
    end	
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserLogin]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Proc_TA_UserLogin]
(
	@username NVARCHAR(10),
	@password NVARCHAR(50)
)
AS
BEGIN	
	---Implemented this BLOCK newly for handling my profile into user login.
	BEGIN
		CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
		IF(@username!='Superadmin')
		BEGIN
			DECLARE @local_EMPLOYEEID varchar(50)
			DECLARE @local_TODAT DATETIME
			DECLARE @local_EMPLOYEETYPE INT
			SET @local_EMPLOYEETYPE =0
			SET @local_TODAT =GETDATE()
			SELECT @local_EMPLOYEEID=Employee_Code_Id from TA_Tbl_Employee WHERE UserName=@username AND Emp_password=@password AND IsDeleted=0 and Employee_status=1
			INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
			-------------
		END		
		DECLARE @isMyprofile_disply INT	
		SET @isMyprofile_disply=0
		SELECT TOP 1 @isMyprofile_disply=T.Isdisply_MyProf FROM #EMPTYPE ET  inner join TA_Tbl_Type T on ET.TYPEID=T.TypeId
		IF(@isMyprofile_disply IS NULL)
		BEGIN
			SET @isMyprofile_disply=0
		END
	END
	
	SELECT	
	Employee_Id,Employee_FirstName + ' ' + Employee_LastName AS 'Employee Name',
	Employee_Code_Id,EmailId,Photo,
	UserGroup_Id,Designation_Id,ShiftPattern_Id,Bus_Id,
			Employee_MiddleName,Employee_LastName,Father_name,Mother_name,DateofBirth,DateofBirth_Record,Blood_Group,Contact_Address, 
			Permanent_Address, Phone_Number, Mobile_Number, Gender, Marital_status, Nationality, Religion,Personal_mailid, Passport_No, 
			Passport_expirydate, Visa_No, Visa_expirydate, Vehicle_Type, Vehicle_No, Anniversary_Date, Native_Place, District, State, Country, 
			Spouse_No, Children_No, DateOfJoining, Reporting_To, Leave_Sanc_Authority, Prev_Experience, Basic_Salary, Allowances, 
			UserName, Emp_password, Qual_JoiningTime, Qual_Employment, OutDoorJob, CompOff_Eligible, OT_Eligible, ESI_Eligible, PF_Eligible, 
			Report_Exclude, Employee_Status, SwipeCardNo, Time_Stamp, Emp_ID, Isdeleted, Hostel, IsFlexible, InActiveDate, CustomField1, CustomField2, 
			CustomField3, CustomField4, CustomField5, IsComplete, Isdeleted_Status, InActive_Status, IsImported,MobileClockInOUt,IsMyProfileRqrd=ISNULL(@isMyprofile_disply,0) FROM TA_Tbl_Employee 
	WHERE UserName=@username AND Emp_password=@password AND IsDeleted=0 and Employee_status=1
	DROP TABLE #EMPTYPE
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_userRightsInsert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		senthil
-- Create date: 11 Aug 2007
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_userRightsInsert] 
(
--[Proc_TA_userRightsInsert] '12','1','','1','','1',''
	@groupId nvarchar(45),
	@pageId int,
	@pageGroupId int,
	@addPrv bit,
	@modifyPrv bit,
	@deletePrv bit,
	@viewPrv bit,
    @employeeId decimal
)
AS
declare @sql nvarchar(2000)    
set @sql=''   
BEGIN
		declare @recordCount as int
declare @query nvarchar(1000)
set @query = ('select count(*) as recordCount from TA_Tbl_userRights where groupId= N''' + @groupId + ''' and pageId=''' + cast(@pageId as nvarchar) + '''')
create table #temp (reccount int)
insert into #temp exec(@query)
set @recordCount =  (select * from #temp)
		if (@recordCount=0)
			begin
				set @sql = @sql + 'insert into TA_Tbl_userRights (groupId,pageId,pageGroupId,addPrv,modifyPrv,deletePrv,viewPrv,employeeId) values ( N''' + @groupId + ''', ''' + cast(@pageId as nvarchar) + ''',''' + cast(@pageGroupId as nvarchar) + ''', ''' + cast(@addPrv as nvarchar) + ''',''' + cast(@modifyPrv as nvarchar) + ''' , ''' + cast(@deletePrv as nvarchar) + ''',''' + cast(@viewPrv as nvarchar) + ''','''+cast(@employeeId as nvarchar)+''')'
exec(@sql)
			end
		else
			begin
				set @sql = @sql + 'update ta_tbl_userRights set addPrv=''' + cast(@addPrv as nvarchar) + ''',modifyPrv=''' + cast(@modifyPrv as nvarchar) + ''',deletePrv= ''' + cast(@deletePrv as nvarchar) + ''',viewPrv= ''' + cast(@viewPrv as nvarchar) + ''',employeeId='''+cast(@employeeId as nvarchar)+''' where groupId= N''' + @groupId + ''' and pageId=  ''' + cast(@pageId as nvarchar) + ''''
exec(@sql)				
			end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UTCEmployeeDetailsInsert]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UTCEmployeeDetailsInsert] 

@EmployeeID int ,
@UTC_TimeZone_ID int,
@LogInDate Datetime,
@Flag int


AS
BEGIN

	Insert Into TA_Tbl_UTCEmployeeLoginDetails Values 
	(@EmployeeID,@UTC_TimeZone_ID,@LogInDate,@Flag)

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UTCEmployeeDetailsUpdate]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UTCEmployeeDetailsUpdate]
@UTC_Auto_ID int,
@UTC_TimeZone_ID int


AS
BEGIN
	
	Update TA_Tbl_UTCEmployeeLoginDetails set 
      UTC_TimeZone_ID= @UTC_TimeZone_ID where UTC_Auto_ID =@UTC_Auto_ID

	  -- 	EmployeeCode	UTC_TimeZone_ID	LogInDate	Flag

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UTCExcisitCheck]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- exec Proc_TA_UTCExcisitCheck @EmployeeCode=N'1001'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UTCExcisitCheck]
@EmployeeCode NVARCHAR(50) ='1001'
AS
BEGIN
	

	--	if(@EmployeeCode='1')
	--	begin 

	--	Select TA_Tbl_EmployeeLevel.LevelId,Ta_Tbl_levelDetails.TimezoneId,TimeZoneName,TimeZoneDesc,TimeZoneValue,HoursToBeAdded,MinToBeAdded from TA_Tbl_EmployeeLevel
	--Inner Join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id =TA_Tbl_EmployeeLevel.LevelId
	--Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
	--Inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id =  TA_Tbl_EmployeeLevel.EmployeeId
	--Where TA_Tbl_Employee.Employee_ID =@EmployeeCode

	--	end 
	--	else
	--	begin
		Select TA_Tbl_EmployeeLevel.LevelId,Ta_Tbl_levelDetails.TimezoneId,TimeZoneName,TimeZoneDesc,TimeZoneValue,HoursToBeAdded,MinToBeAdded from TA_Tbl_EmployeeLevel
	Inner Join Ta_Tbl_levelDetails on Ta_Tbl_levelDetails.id =TA_Tbl_EmployeeLevel.LevelId
	Inner Join TA_Tbl_UTCTimeZonesCountryDetails on TA_Tbl_UTCTimeZonesCountryDetails.TimeZoneID = Ta_Tbl_levelDetails.TimezoneId
	Inner Join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	Where TA_Tbl_Employee.Employee_Code_Id =@EmployeeCode

		--end

	
	
	--Select * from TA_Tbl_UTCTimeZonesCountryDetails
	
	--Where 	EmployeeCode = @EmployeeCode
END

--Select * from TA_Tbl_Employee

--Select * from Ta_Tbl_levelDetails
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UTCTimeZoneSelectEmployeePeference]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UTCTimeZoneSelectEmployeePeference]

@TimeZoneID int

AS
BEGIN

--TimeZoneID	TimeZoneName	TimeZoneDesc	HoursToBeAdded	MinToBeAdded

Select * from TA_Tbl_UTCTimeZonesCountryDetails where TimeZoneID = @TimeZoneID

END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateLeavePolicyByFilters]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <29-Oct-2011>
-- Description:	<To Validate the selected Leave Policy is related to selected Items>
-- =============================================
--Proc_TA_ValidateLeavePolicyByFilters 1,1,'Female',43,97
CREATE PROCEDURE [dbo].[Proc_TA_ValidateLeavePolicyByFilters] 
	@EmployeeCategory int,
	@EmployeeType int,
	@Gender varchar(20),
	@Religion int,
	@LeavePolicyId int
AS
BEGIN
	SET NOCOUNT ON;
	declare @Query nvarchar(4000)
    set @Query=''
    set @Query= @Query + ' select count(*) from TA_Tbl_LeavePolicy LP'
    set @Query= @Query + ' where Policy_Id='+ cast(@LeavePolicyId  as varchar(20)) +' '
	if(@EmployeeCategory <> 0)
	begin
	 set @Query= @Query + ' and (LP.EmployeeCategory = ' + cast(@EmployeeCategory as varchar(20)) + ' or LP.EmployeeCategory =0)'
	end
	if(@EmployeeType <>0)
		begin
			set @Query= @Query + ' and (LP.EmployeeType = '+ cast(@EmployeeType as varchar(20)) +' or LP.EmployeeType =0)'
		end
	if(@Gender = 'Male' or @Gender ='Female')
		begin
			set @Query= @Query + ' and (LP.Gender = ''' + @Gender + ''' or LP.Gender =''Both'') '
		end	
	if(@Religion <> 0)
		begin
			set @Query= @Query + ' and (LP.Religion = ' + cast(@Religion as varchar(20)) + ' or LP.Religion =0)'
		end	
	exec(@Query)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateOndutyForImport]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-Apr-2019 07:16PM>
-- Description:	<Checking whether onduty entry already available or not>
-- Proc_TA_ValidateOndutyForImport '787',3,'2019-04-01'
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ValidateOndutyForImport]
	@EmpCode varchar(50),
	@ShiftID int,
	@Date varchar(12)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Shift_StartTime varchar(6)
	Declare @Shift_EndTime varchar(6)
	SELECT @Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID
	DECLARE	@return_value int
	EXEC	[dbo].[Proc_TA_CheckManualODEntry]
	@EmpCode = @EmpCode,@ManualInDate = @Date,@ManualInTime = @Shift_StartTime,@ManualOutDate = @Date,@ManualOutTime = @Shift_EndTime
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateSelectedLeavePolicy]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <15-July-2019>
-- Description:	<Validating the selected leave policy for insertion>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ValidateSelectedLeavePolicy]
	@PolicyName varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT companyid=isnull(companyid,'') from TA_Tbl_LeavePolicy where PolicyName=@PolicyName
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ViewLeavePolicyDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: 29 June 2007  
-- Description: Leave policy - select  
-- Modified By : Kumuthini.L
-- Modified On : 06-Feb-2008
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Modified by	:	Manikandan.R
Modified on	:	15-Oct-11
Description	:	Year closure changes
-- =============================================  
*/
CREATE PROCEDURE [dbo].[Proc_TA_ViewLeavePolicyDetails]
 -- Add the parameters for the stored procedure here  
 @Type CHAR(1)='',  
-- @Policy_Id INT=0,  
 @UserGroupName nVarchar(250),
 @EmployeeCategory NVARCHAR(50)=NULL,
 @EmployeeType NVARCHAR(50)=NULL,
 @Gender NVARCHAR(10)=NULL,
 @Religion NVARCHAR(50)=NULL  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
  DECLARE @SQL NVARCHAR(MAX)
IF (@Type='A')  
   BEGIN  
    IF(@UserGroupName = 'SuperAdmin')  
       BEGIN     
		SET @SQL='SELECT *,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
              (select Name from TA_Tbl_Religion where ID=Religion)as Religions FROM TA_Tbl_LeavePolicy 
	          WHERE IsDeleted=0 '   
       END
    ELSE       
       BEGIN
			SET @SQL='=SELECT *,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
              (select Name from TA_Tbl_Religion where ID=Religion)as Religions FROM TA_Tbl_LeavePolicy WHERE IsDeleted=0 '
       END    
   END
ELSE IF (@Type='P')     
     BEGIN  
			IF(@UserGroupName = 'SuperAdmin')
                BEGIN
					-- New Code on 16-Feb-08, Based on Policy Year field removed from TA_Tbl_LeavePolicy
						SET @SQL='SELECT *, getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions  
  					FROM TA_Tbl_LeavePolicy  
        			WHERE IsDeleted=0 '
                END
           ELSE
               BEGIN
				-- New Code 16-Feb-08,Based on Policy Year field removed from TA_Tbl_LeavePolicy
					SET @SQL='SELECT *,getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions  
					FROM TA_Tbl_LeavePolicy  
					WHERE IsDeleted=0 '
               END
			IF @EmployeeCategory<>'' AND @EmployeeCategory IS NOT NULL
				BEGIN
					SET @SQL=@SQL + ' AND EmployeeCategory='+@EmployeeCategory 
				END
			IF @EmployeeType<>'' AND @EmployeeType IS NOT NULL 
				BEGIN
					SET @SQL=@SQL + ' AND EmployeeType='+@EmployeeType
				END
			IF @Gender <>'' AND @Gender IS NOT NULL
				BEGIN
					SET @SQL=@SQL + ' AND Gender='''+@Gender+'''' 
				END
			if @Religion<>'' AND @Religion IS NOT NULL
				BEGIN
					SET @SQL=@SQL + ' AND Religion='+@Religion 
				END
			SET @SQL=@SQL + ' ORDER BY Policy_Id'
			EXEC(@SQL)
    END  
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_WriteErrorDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 15.09>
-- Description:	<Write Error details into Errorlog Table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_WriteErrorDetails]
	-- Add the parameters for the stored procedure here
	@Clk_Id varchar(50),
	@strErrorMessage varchar(max),
	@Type char(2)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	insert into TA_Tbl_ErrorLog_ClockRawData(Clock_Id,ErrorMessage) values(@Type+'-'+ @Clk_Id,@strErrorMessage)
	if(@Type='C')
	begin		
		UPDATE TA_Tbl_Clk_RawData SET clk_flag = 0,clk_process=1,ReasonId=5 WHERE clk_Id=@Clk_Id
	end
	if(@Type='MU')
	begin
		UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = 'Y' WHERE ManualTimeEntry_Id =@Clk_Id
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_InsertResponseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
=============================================
Procedure Name = Proc_TC_InsertResponseDetails
Created By = K.Gopinath
Created Date = 17 March 2014
Description = Procedure for insert the license requested response details in TA_Tbl_LicenseRequestDetail table
Proc_OL_GenerateLicense 1,1
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_InsertResponseDetails]
@RequestID bigint,
@MacAddress nvarchar(50),
@Status bit
AS
BEGIN
IF NOT EXISTS (select RequestID from TA_Tbl_LicenseRequestDetail where RequestID=@RequestID)
insert into TA_Tbl_LicenseRequestDetail(RequestID,MacAddress,Status,CreatedDate) values 
(@RequestID,@MacAddress,@Status,GETDATE())
else
update TA_Tbl_LicenseRequestDetail
SET
--RequestID=@RequestID,
MacAddress=@MacAddress,
Status=@Status,
ModifiedDate=GETDATE() where RequestID=@RequestID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_SelectLicenseReqDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
=============================================
Procedure Name = Proc_TC_SelectLicenseReqDetails
Created By = K.Gopinath
Created Date = 18 March 2014
Description = Procedure for select the license requested details in TA_Tbl_LicenseRequestDetail table
Proc_TC_SelectLicenseReqDetails
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_SelectLicenseReqDetails]
AS
BEGIN
select RequestID, Status from TA_Tbl_LicenseRequestDetail where Status=1 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_UpdateResponseDetails]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
=============================================
Procedure Name = [Proc_TC_UpdateResponseDetails]
Created By = K.Gopinath
Created Date = 24 March 2014
Description = Procedure for Update the license requested response details in TA_Tbl_LicenseRequestDetail table
Proc_TC_UpdateResponseDetails 1,1
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_UpdateResponseDetails]
@RequestID bigint,
--@MacAddress nvarchar(50),
@Status bit
AS
BEGIN
update TA_Tbl_LicenseRequestDetail
SET
RequestID=@RequestID,
--MacAddress=@MacAddress,
Status=@Status,
ModifiedDate=GETDATE()
where RequestID=@RequestID
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleFirst]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/
CREATE Procedure [dbo].[Proc_Update_TA_TBL_TitleFirst]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(250),
	@LevelID INT,
	@PolicyID INT,
	@GradeID INT,
	@EmpID INT,
	@TitleId INT
) 
As
declare @sql as nvarchar(3000)
BEGIN
	set @sql = 'UPDATE TA_Tbl_Title SET TitleName=N'''+@TitleName+''',TitleDescription=N'''+@TitleDescription+''',LevelID='+cast(@LevelID as nvarchar(25))+',LeavePolicyID='+cast(@PolicyID as nvarchar(25))+',GradeID='+cast(@GradeID as nvarchar(25))+',Emp_Id='+cast(@EmpID as nvarchar(25))+',Time_Stamp=getdate() WHERE TitleId='+cast(@TitleId as nvarchar(25))+''
	--set @sql = 'UPDATE TA_Tbl_Title SET TitleName=N'''+@TitleName+''',TitleDescription=N'''+@TitleDescription+''',LeavePolicyID='+cast(@PolicyID as nvarchar(25))+',GradeID='+cast(@GradeID as nvarchar(25))+',Emp_Id='+cast(@EmpID as nvarchar(25))+',Time_Stamp=getdate() WHERE TitleId='+cast(@TitleId as nvarchar(25))+''
   exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleMapping]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_Update_TA_TBL_TitleMapping]
(    
	 @CompanyId INT,     
	 @RegionId INT,    
	 @BranchId INT,
	 @DepartmentId INT,
	 @SectionId INT,
	 @TitleId INT,
	@id INT
)     
As    
BEGIN    
	UPDATE TA_Tbl_TitleMapping  
	SET    
	   Company_Id =@CompanyId,    
	   Region_Id = @RegionId,    
	   Branch_Id = @BranchId,
	   Department_Id=@DepartmentId,
	   Section_Id=@SectionId,
	   TitleId=@TitleId	    
  WHERE Id=@Id
END  
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Procedure [dbo].[Proc_Update_TA_TBL_Transportation] 
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT,
	@id int
) 
As
BEGIN
	UPDATE TA_Tbl_Transportation
SET
			VehicleNo = @VehicleNo, 
			RouteName = @RouteName,
			Company_Id =@CompanyId,
			Region_Id = @RegionId,
			Branch_Id = @BranchId
  		WHERE VehicleNo=@VehicleNo and Id=@id
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation_Route]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_Update_TA_TBL_Transportation_Route]    
(  
  @LevelId INT,  
  @VehicleID INT,	
  @RouteName NVARCHAR(50),    
  @RouteDescription NVARCHAR(250),
  @EmpID  INT,  
  @RouteId INT    
)     
As    
declare @sql as nvarchar(3000)
BEGIN    
 --UPDATE TA_Tbl_RouteMaster SET Level_Id=@LevelId, VehicleID=@VehicleID, Route_Name = @RouteName, Route_Description =@RouteDescription, Emp_ID=@EmpID, Time_stamp=getdate() WHERE [Id]=@RouteId 
 set @sql = 'UPDATE TA_Tbl_RouteMaster SET Level_Id='+cast(@LevelId as nvarchar(25))+', VehicleID='+cast(@VehicleID as nvarchar(25))+', Route_Name = N'''+@RouteName+''', Route_Description =N'''+@RouteDescription+''', Emp_ID='+cast(@EmpID as nvarchar(25))+', Time_stamp='''+cast(getdate() as nvarchar(25))+''' WHERE [Id]='+cast(@RouteId as nvarchar(25))+''
 exec(@sql)
END    
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationMapping]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_Update_TA_TBL_TransportationMapping]    
(    
 @VehicleId INT,    
 @RouteId INT,    
 @CompanyId INT,     
 @RegionId INT,    
 @BranchId INT,    
 @id int    
)     
As    
BEGIN    
 UPDATE TA_Tbl_Transportation_Mapping    
SET    
   VehicleId = @VehicleId,     
   RouteId = @RouteId,    
   Company_Id =@CompanyId,    
   Region_Id = @RegionId,    
   Branch_Id = @BranchId    
  WHERE VehicleId=@id --and Id=@id    
END 
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationVehicle]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified By	:	P.Prabakaran
Modified on	:	7-Feb-08
*/
CREATE  Procedure [dbo].[Proc_Update_TA_TBL_TransportationVehicle]
(
	@VehicleNo NVARCHAR(50),
	@VehicleDescription NVARCHAR(250),
	@VehicleId int,
	@EmpID INT
) 
As
declare @sql as nvarchar(3000)
BEGIN
	--UPDATE TA_Tbl_Transportation_Vehicle SET VehicleNo = @VehicleNo,VehicleDescription =@VehicleDescription,Time_Stamp=getdate(),Emp_ID=@EmpID WHERE VehicleId=@VehicleId
    set @sql = 'UPDATE TA_Tbl_Transportation_Vehicle SET VehicleNo = N'''+@VehicleNo+''',VehicleDescription =N'''+@VehicleDescription+''',Time_Stamp='''+cast(getdate() as nvarchar(25))+''',Emp_ID='+cast(@EmpID as nvarchar(25))+' WHERE VehicleId='+cast(@VehicleId as nvarchar(25))+''
    exec(@sql)
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_UpdateOTHours]    Script Date: 10-30-2024 09:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_UpdateOTHours]
	-- Add the parameters for the stored procedure here
	@Type nvarchar(50),
	@OTMins int,
	@UpOTHours nvarchar(50),
	@OTHours nvarchar(50),
	@UpOTHrs nvarchar(50),
	@Process_Rec_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@Type='NormOTHrs')
	begin
		Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,NormOT=@UpOTHours,ActHrsOT='00:00',ActNormOT=@OTHours,NormOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
	end	
	else if(@Type='WeekOffOT')
		begin
			Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,OffOT=@UpOTHours,ActHrsOT='00:00',ActOffOT=@OTHours,OffOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
		end
	else if(@Type='HolOT')
		begin	
			Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,HolOT=@UpOTHours,ActHrsOT='00:00',ActOffOT=@OTHours,HolOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
		end
END
-----------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[ReducePermissionHoursFromTotalHours]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ReducePermissionHoursFromTotalHours]
	@dtmPermissionFromDateTime datetime,
	@dtmPermissionToDateTime datetime,
	@dtmShiftEndTime datetime,
	@dtmFirstInDateTime datetime,
	@dtmLastOutDateTime datetime,
	@No_Of_Hours varchar(10)
AS
BEGIN
	SET NOCOUNT ON;
	if (@dtmShiftEndTime >= @dtmPermissionFromDateTime and @dtmShiftEndTime <= @dtmPermissionToDateTime)
	Begin
		if (@dtmLastOutDateTime > @dtmPermissionFromDateTime)
		Begin
			select DATEDIFF(minute,@dtmFirstInDateTime,@dtmPermissionFromDateTime)as dTotalMinsWorked
		End
		else if (@dtmLastOutDateTime >= @dtmFirstInDateTime)
		begin
			select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
		End
	End
	else if (@dtmFirstInDateTime >= @dtmPermissionFromDateTime and @dtmFirstInDateTime <= @dtmPermissionToDateTime)
	begin
		set @dtmFirstInDateTime = @dtmPermissionToDateTime
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
	end
	else if (@dtmPermissionFromDateTime >= @dtmFirstInDateTime and @dtmPermissionToDateTime <= @dtmLastOutDateTime)
	begin
		Declare @permissionMinutes int
		set @permissionMinutes=SUBSTRING(@No_Of_Hours,0,CHARINDEX(':',@No_Of_Hours))*60+SUBSTRING(@No_Of_Hours,CHARINDEX(':',@No_Of_Hours)+1,LEN(@No_Of_Hours))
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)-@permissionMinutes as dTotalMinsWorked
	end
    else if (@dtmLastOutDateTime >= @dtmFirstInDateTime)
    begin
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
	end	
END
GO
/****** Object:  StoredProcedure [dbo].[ReminderMailForLeavePolicyUpdationToHR]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-07-2019>
-- Description:	<Send reminder mail to HR for Leave policy updation>
-- =============================================
CREATE PROCEDURE [dbo].[ReminderMailForLeavePolicyUpdationToHR]
AS
BEGIN
	SET NOCOUNT ON;
	Declare @TriggerDate datetime
	Declare @StartDate datetime
	Declare @EndDate datetime
	set @TriggerDate=DATEADD(d,24,DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0))
	--select @TriggerDate
	if(@TriggerDate=CONVERT(varchar(11),GETDATE()))
	begin
		if not exists(select id from ta_tbl_remainder where convert(varchar(11),TimeStamp)=CONVERT(varchar(11),GETDATE()) and Type='LPR')
		begin
			set @StartDate=DATEADD(d,-14,@TriggerDate)
			set @EndDate=DATEADD(d,-15,DATEADD(m,1,@TriggerDate))
			Declare @yearsettingID int
			select @yearsettingID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
			Create table #TempLeavePolicy
			(
				Employee_Code_Id	varchar(20),
				Employee_FirstName	varchar(20),
				DateOfJoining		datetime,
				[Current Policy]	varchar(20),
				[Total Year Experience]	varchar(20),
				[Total Days] int,
				ExperienceAdded		datetime,
				Row					varchar(20),
				LeavePolicy_Id		varchar(20),
				IsAlreadyUpdated	bit default(0)
			)
			Create table #TempLeavePolicy1
			(
				Employee_Code_Id	varchar(20),
				Employee_FirstName	varchar(20),
				DateOfJoining		datetime,
				[Current Policy]	varchar(20),
				[Total Year Experience]	varchar(20),
				[Total Days] int,
				ExperienceAdded		datetime,
				Row					varchar(20),
				LeavePolicy_Id		varchar(20),
				IsAlreadyUpdated	bit default(0)
			)
			--select @StartDate,@EndDate
			Insert into #TempLeavePolicy
			select 
					--@StartDate,
					--@EndDate,
					Employee_Code_Id,Employee_FirstName,DateOfJoining,PolicyName as [Current Policy],
					[Total Year Experience]=DATEDIFF(d,DateOfJoining,GETDATE())/365,[Total Days]=DATEDIFF(D,DateOfJoining,GETDATE()),
					ExperienceAdded=DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining),  
					Row=ROW_NUMBER()over(partition by employee_code_id order by Employee_Code_Id),
					ELP.LeavePolicy_Id,0
					from TA_Tbl_Employee E
			inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
			inner join TA_Tbl_LeavePolicy LP on ELP.LeavePolicy_Id=LP.Policy_Id
			where Employee_Status=1 and isnull(InActiveDate,'')=''
			and (DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining)>=@StartDate
			and DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining)<=@EndDate)
			and ELP.YearSettingId=@yearsettingID and ELP.LeavePolicy_Id not in(76,72)
			and DATEDIFF(d,DateOfJoining,GETDATE())>180
			update #TempLeavePolicy set IsAlreadyUpdated=1 where Employee_Code_Id in(select Employee_Code_Id from #TempLeavePolicy TLP where Row>1)
			
			--Below 1.5 yrs category
			Insert into #TempLeavePolicy1
			select 
				--@StartDate,
				--@EndDate,
				Employee_Code_Id,Employee_FirstName,DateOfJoining,PolicyName as [Current Policy],
				[Total Year Experience]=DATEDIFF(d,DateOfJoining,GETDATE())/365,[Total Days]=DATEDIFF(D,DateOfJoining,GETDATE()),
				ExperienceAdded=DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining),  
				ROW_NUMBER()over(partition by employee_code_id order by Employee_Code_Id),
				ELP.LeavePolicy_Id,0
				from TA_Tbl_Employee E
				inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
				inner join TA_Tbl_LeavePolicy LP on ELP.LeavePolicy_Id=LP.Policy_Id
				where Employee_Status=1 and isnull(InActiveDate,'')=''
				and ELP.YearSettingId=@yearsettingID and ELP.LeavePolicy_Id in(72)
				and DATEDIFF(d,DateOfJoining,GETDATE())>180
				
			update #TempLeavePolicy1 set IsAlreadyUpdated=1 where Employee_Code_Id in(select Employee_Code_Id from #TempLeavePolicy TLP where Row>1)
			
			select	Employee_Code_Id,
					Employee_FirstName,
					DateOfJoining=replace(CONVERT(varchar(11),DateOfJoining,113),' ','-'),
					[Current Policy],			
					TotalYearExperience=convert(varchar(20),[Total Days]/365)+ ' Yrs ' + convert(varchar(20),([Total Days]%365)/12) +' months '+convert(varchar(20),([Total Days]%365)%12) +' day(s)'
			from #TempLeavePolicy where IsAlreadyUpdated=0
			--union all
			--select	787,
			--		'Manikandan',
			--		DateOfJoining=replace(CONVERT(varchar(11),'2011-03-21',113),' ','-'),
			--		'5 year above',			
			--		TotalYearExperience='8 Yrs '
			
			
			--below 1.5 category always fetch
			select Employee_Code_Id,
					Employee_FirstName,
					DateOfJoining=replace(CONVERT(varchar(11),DateOfJoining,113),' ','-'),
					[Current Policy],			
					TotalYearExperience=convert(varchar(20),[Total Days]/365)+ ' Yrs ' + convert(varchar(20),([Total Days]%365)/12) +' months '+convert(varchar(20),([Total Days]%365)%12) +' day(s)'
			from #TempLeavePolicy1 where IsAlreadyUpdated=0
			
			select EmailId as EmailId from TA_Tbl_Employee where Employee_Code_Id='6003'
			
			drop table #TempLeavePolicy
			drop table #TempLeavePolicy1
		end
	end
	--else
	--begin
	--	select 'Not Triggering date'
	--end
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyData]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RemoveDiscrepancyData] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '4%'
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '3%'
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate='2009-10-15 00:00:00.000' or Clk_outDate='2009-10-15 00:00:00.000')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark='Script IN on' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day='Day'+LTrim(str(day(@CLK_inDATE)))+'Shift'
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark='1'
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script in 1 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name='166' or rtrim(@shift_name)='0'
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #shiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_inDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_inDATE))) +''' and year='''+ltrim(str(year(@CLK_inDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID='-1' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+'no data with out in. so create an out based on the shift'
			set @remark='Script in 3 on' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark='Script in 51 on' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script in 52 on' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark='Script in 56 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
else
begin
set @remark='Script in 57 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark='Script in 5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark='Script in 4Match case on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark='Script in 3 on' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script in 7  on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark='Script in 3Matchcase on' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script in 21 on' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark='20'
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark='Script Out11 on' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day='Day'+LTrim(str(day(@CLK_outDATE)))+'Shift'
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script Out2 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name='0' or @shift_name='166' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_outDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_outDATE))) +''' and year='''+ltrim(str(year(@CLK_outDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID='-1'
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark='no data with out in. so create an out based on the shift'
		set @remark='Script Out 33 on' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,'00:00'),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark='Script out Void51 on' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script out Void52 on' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark='Script out Void5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark='Script out Void4 m on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script out Void6 on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark='Script out Void61 on' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script Out 10 on' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataIFFCO]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RemoveDiscrepancyDataIFFCO] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '4%'
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '3%'
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
--where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate='2009-10-15 00:00:00.000' or Clk_outDate='2009-10-15 00:00:00.000')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark='Script IN on' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day='Day'+LTrim(str(day(@CLK_inDATE)))+'Shift'
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark='1'
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script in 1 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name='166' or rtrim(@shift_name)='0'
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #shiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_inDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_inDATE))) +''' and year='''+ltrim(str(year(@CLK_inDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID='-1' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+'no data with out in. so create an out based on the shift'
			set @remark='Script in 3 on' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark='Script in 51 on' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script in 52 on' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark='Script in 56 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
else
begin
set @remark='Script in 57 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark='Script in 5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark='Script in 4Match case on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark='Script in 3 on' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script in 7  on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark='Script in 3Matchcase on' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script in 21 on' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark='20'
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark='Script Out11 on' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day='Day'+LTrim(str(day(@CLK_outDATE)))+'Shift'
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script Out2 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name='0' or @shift_name='166' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_outDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_outDATE))) +''' and year='''+ltrim(str(year(@CLK_outDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID='-1'
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark='no data with out in. so create an out based on the shift'
		set @remark='Script Out 33 on' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,'00:00'),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark='Script out Void51 on' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script out Void52 on' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark='Script out Void5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark='Script out Void4 m on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script out Void6 on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark='Script out Void61 on' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script Out 10 on' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataOMAN]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RemoveDiscrepancyDataOMAN] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '4%'
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '3%'
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in('20039')or Clk_outDeviceId in('20039')) order by Clk_OutDate
--and (Clk_inDate='2009-10-15 00:00:00.000' or Clk_outDate='2009-10-15 00:00:00.000')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark='Script IN on' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day='Day'+LTrim(str(day(@CLK_inDATE)))+'Shift'
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark='1'
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script in 1 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name='166' or rtrim(@shift_name)='0'
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #shiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_inDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_inDATE))) +''' and year='''+ltrim(str(year(@CLK_inDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID='-1' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+'no data with out in. so create an out based on the shift'
			set @remark='Script in 3 on' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark='Script in 51 on' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script in 52 on' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark='Script in 56 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
else
begin
set @remark='Script in 57 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark='Script in 5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark='Script in 4Match case on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark='Script in 3 on' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script in 7  on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark='Script in 3Matchcase on' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script in 21 on' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark='20'
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark='Script Out11 on' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day='Day'+LTrim(str(day(@CLK_outDATE)))+'Shift'
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script Out2 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name='0' or @shift_name='166' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_outDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_outDATE))) +''' and year='''+ltrim(str(year(@CLK_outDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID='-1'
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark='no data with out in. so create an out based on the shift'
		set @remark='Script Out 33 on' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,'00:00'),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark='Script out Void51 on' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script out Void52 on' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark='Script out Void5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark='Script out Void4 m on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script out Void6 on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark='Script out Void61 on' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script Out 10 on' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataTiffany]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[RemoveDiscrepancyDataTiffany] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '4%'
--update TA_Tbl_ProcessedData set hrswork='10:00',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like '3%'
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate='2009-10-15 00:00:00.000' or Clk_outDate='2009-10-15 00:00:00.000')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark='Script IN on' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day='Day'+LTrim(str(day(@CLK_inDATE)))+'Shift'
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark='1'
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script in 1 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name='166' or rtrim(@shift_name)='0'
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #shiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_inDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_inDATE))) +''' and year='''+ltrim(str(year(@CLK_inDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID='-1' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+'no data with out in. so create an out based on the shift'
			set @remark='Script in 3 on' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark='Script in 51 on' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script in 52 on' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark='Script in 56 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
else
begin
set @remark='Script in 57 on' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark='Script in 5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark='Script in 4Match case on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark='Script in 3 on' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script in 7  on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , 'Out'),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark='Script in 3Matchcase on' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script in 21 on' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark='20'
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark='Script Out11 on' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day='Day'+LTrim(str(day(@CLK_outDATE)))+'Shift'
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark='Script Out2 on' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,'Absent',0)
			end
		set @shift_name=( select isnull(Shift_Id,'166') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name='0' or @shift_name='166' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql ='insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,'+@M_day+' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId='''+@EMP_ID+''' and Year='''+@cyear+''' and Month='''+@cmonth+''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql ='update dbo.TA_Tbl_TemporaryShiftAllocation set Day' +ltrim(str(day(@CLK_outDATE)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @EMP_ID +''' and month='''+ ltrim(str(month(@CLK_outDATE))) +''' and year='''+ltrim(str(year(@CLK_outDATE))) +''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID='-1'
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark='no data with out in. so create an out based on the shift'
		set @remark='Script Out 33 on' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,'00:00'),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,'00:00',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark='Script out Void51 on' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark='Script out Void52 on' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process='Y' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark='Script out Void5 on' + Convert(varchar,getdate())
						if @CLK_CARDID=''
						begin
									set @remark='Script NO Card ' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark='Script out Void4 m on' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, '00:00',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark='Script out Void6 on' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , 'IN'),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process='Y'	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance='Present' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark='Script out Void61 on' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark='Script Out 10 on' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason ='Script Entry'
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData
GO
/****** Object:  StoredProcedure [dbo].[RemoveDuplicateData]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RemoveDuplicateData] 
as
declare @CLK_ID int
declare @clk_empID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_outDate datetime
update dbo.TA_Tbl_ProcessedData set processflag=0  where left(HrsWork,2) >23
declare RemoveDuplicate cursor for 
select CLK_ID,clk_empID,clk_indate,clk_outdate from View_Duplicatedata
open RemoveDuplicate
fetch RemoveDuplicate into @CLK_ID,@clk_empID,@clk_indate,@clk_outdate
while (@@fetch_status = 0 )
begin
	delete from  dbo.TA_Tbl_ClockDetails  where  CLK_ID=@CLK_ID
--if len(@clk_indate)>2
--begin
	 	update  dbo.TA_Tbl_ProcessedData set ProcessFlag =0 where  Date=@CLK_inDATE and Employee_Code_Id =@clk_empID
--end
--else
--begin
--		update  dbo.TA_Tbl_ProcessedData set ProcessFlag =0 where  Date=@CLK_outDATE and Employee_Code_Id =@CLK_CARDID
--
--end
  fetch RemoveDuplicate into  @CLK_ID,@clk_empID,@clk_indate,@clk_outdate
end   
deallocate RemoveDuplicate
GO
/****** Object:  StoredProcedure [dbo].[RemoveTemporaryShiftAllocation]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[RemoveTemporaryShiftAllocation] 
	-- Add the parameters for the stored procedure here
AS
declare @EmployeeId varchar(5)
declare @day1shift varchar(3)
declare @day30shift varchar(3)
declare @emonth varchar(3)
declare @eCount int
declare emp_TempShift cursor for 
select  EmployeeId,day1shift,month,day30shift  from TA_Tbl_TemporaryShiftAllocation
open emp_TempShift
fetch emp_TempShift into @EmployeeId,@day1shift,@emonth,@day30shift
while (@@fetch_status = 0 )
begin
set @eCount=(select  count(shift_ID) from dbo.TA_Tbl_Shift WHERE
       shift_ID = @day1shift )
if @eCount=0
begin
delete   from TA_Tbl_TemporaryShiftAllocation where EmployeeId= @EmployeeId and day1shift=@day1shift and month=@emonth and day1shift <>0 and day1shift<>-1
 end
set @eCount=(select  count(shift_ID) from dbo.TA_Tbl_Shift WHERE
       shift_ID = @day30shift )
if @eCount=0
begin
delete   from TA_Tbl_TemporaryShiftAllocation where EmployeeId= @EmployeeId and day30shift=@day30shift and month=@emonth and day30shift <>0 and day30shift<>-1
 end
  fetch emp_TempShift into @EmployeeId,@day1shift,@emonth,@day30shift
end   
deallocate emp_TempShift
GO
/****** Object:  StoredProcedure [dbo].[ReProcess_EmpLogs]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--3 processing data last
CREATE procedure [dbo].[ReProcess_EmpLogs] @Process_Rec_ID varchar(20), @Employee_Code varchar(20),@Emp_Date Datetime,@Shift_Id varchar(10),@OTtype varchar(1)
as
declare @mOT char(1)--if you want Morning OT then Y else N
declare @RoundEnable char(1)-- if Enable  Roundoff tehn Y else N
declare @Clk_EmpId char(8)
declare @Clk_inDatetime datetime
declare @Clk_inTime char(8)
declare @Clk_outDatetime datetime
declare @Clk_outTime char(8)
declare @Clk_Remarks varchar(50)
declare @WMinutes numeric(18)
declare @TotalSWMin numeric(18)
declare @TotalShiftbreak numeric(18)
declare @check_In_time  datetime
declare @check_End_time  datetime
declare @check_In_date char(20)
declare @Shiftbreak varchar(10)
select @RoundEnable='Y' -- if Enable  Roundoff tehn Y else N
create table #loglist (emp_code char(8),emp_inDate datetime,emp_outdate datetime,emp_remark varchar(50) NULL,Work_minute numeric(8) null,ShiftWork_minute numeric(8) null)
declare emp_list cursor for 
select  Clk_EmpId,Clk_inDate+Clk_inTime as INTime,Clk_outDate + Clk_outTime as OutTime,Clk_Remarks,DateDiff("N", Clk_inDate+Clk_inTime, Clk_outDate + Clk_outTime) as WMinutes from TA_Tbl_ClockDetails WHERE
       Clk_EmpId = @Employee_Code AND Clk_InTime IS NOT NULL AND Clk_OutTime IS NOT NULL  AND Clk_InDate =@Emp_Date order by  Clk_inDate, Clk_inTime
open emp_list
fetch emp_list into  @Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks,@WMinutes
while (@@fetch_status = 0 )
begin
	select @Shiftbreak =(select Shift_BreakStartTime1 from dbo.TA_Tbl_Shift where shift_ID=@Shift_Id )
if len(@Shiftbreak)>0 
begin
--***************Calculate Working hours based on in and out on the log
	select @TotalShiftbreak =(select Datediff("n", Shift_BreakStartTime1,Shift_BreakEndTime1) from dbo.TA_Tbl_Shift where shift_ID=@Shift_Id )
end
else
begin
	set @TotalShiftbreak=0
end
	select @TotalSWMin =(select DateDiff("N", '00:00',Shift_TotalWorkingHours) from TA_Tbl_Shift where Shift_Id=@Shift_Id )
      if (@WMinutes<0 )
		begin 	
			set @WMinutes=0 -- if its negitive working time assign it zero
		end
		if (@TotalShiftbreak>0 )
		begin 	
			set @WMinutes=@WMinutes-@TotalShiftbreak -- if its negitive working time assign it zero
		end
--convert(int,@iTotalMin) <=convert(int,@TotalSWMin)+300 and
if ( convert(int, @WMinutes) >0 and  convert(int, @WMinutes) <1440 ) 
begin
	insert into #loglist(emp_code ,emp_inDate, emp_outdate,EMP_REMARK,Work_minute,ShiftWork_minute)
   values(@Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks, @WMinutes,@TotalSWMin)
end 
   fetch emp_list into @Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks,@WMinutes
end   
deallocate emp_list
declare @fin  char(20) -- first in 
declare @lout  char(20) -- last out
declare @wTHour   numeric(4) -- Total working Minutes
declare @ShortageHour   numeric(4) -- shortage minutes
declare @wmin  char(2) -- shift break
declare @wH   char(2) -- shift break
declare @workingHour  char(20) -- shift break
declare @LmworkingHour  char(20) -- shift break
declare @REMARK  VARCHAR(50) -- shift break
declare @S_wTHour   numeric(4) -- shift work hours
declare @S_wmin  char(2) -- shift break
declare @S_wH   char(2) -- shift break
declare @S_workingHour  char(20) -- shift break
declare @phrswork char(5)
declare @Short_wH char(2)
declare	@Short_wmin char(2)
declare	@Short_workingHour char(5)
declare @pOT char(10)
declare @pHrsOT char(10)
declare @pHrsOT_hh char(2)
declare @pHrsOT_mm char(2)
declare @pNormOT char(5)
declare @pOffOT char(5)
declare @pHolOT char(5)
declare @pEarlyOut char(5)
declare @pLateIn char(5)
--pLeaveType
declare @pWorkHrs char(5)
declare @pHrsLess char(5)
declare @Pday char(5)
declare @Exot char(5)
declare  @pEarlyIn char(5)
declare @OTstatusDay char(15)
declare @OT_AMT numeric(2,2)
declare @MinOT char(5)
declare @MaxOT char(5)
select @fin=(select min(emp_inDate )as Firstin from #loglist )
select @lout=(select max(emp_outdate )as lastout from #loglist )
select @REMARK =(select   distinct (EMP_REMARK) from #loglist )
if @fin is null 
begin
	select @fin=(select distinct (emp_inDate)  from #loglist ) 
end
if @lout is null 
begin
	select @lout=(select distinct (emp_outDate) from #loglist)
end
select @wTHour= convert(int,(select sum(Work_minute)as totWH from #loglist ),5)
select @s_wTHour= convert(int,(select distinct  (ShiftWork_minute) from #loglist ),5)
	if  (@wTHour>1440)  -- not more thatn 24 hours
	begin
		select @wTHour=1440
	end
	if  (@wTHour<=1)  -- IN SECONDS
	begin
		select @wTHour=0
	end
-- convert the working minutes to hours and minutesselect @wH=convert(char,convert(int,(@wTHour/60),2),2)
select @wH=convert(char,convert(int,(@wTHour/60),2),2)
select @wmin= convert(int,@wTHour)%60
if (len(rtrim(@wH))=1) select @wH= '0'+@wH
if (len(rtrim(@wmin))=1) select @wmin= '0'+@wmin
select @workingHour=  rtrim(@wH) +':'+   rtrim(@wmin)
-- convert the Shift working minutes to hours and minutes
select @S_wH=convert(char,convert(int,(@S_wTHour/60),2),2)
select @S_wmin= convert(int,@S_wTHour)%60
if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
select @S_workingHour= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
/*
-- convert the working minutes to hours and minutesselect @wH=convert(char,convert(int,(@wTHour/60),2),2)
set @ShortageHour=0
set @Short_workingHour='00:00'
if @S_wTHour>@wTHour
begin
		select @ShortageHour=@S_wTHour-@wTHour
		-- convert the Shift working minutes to hours and minutes
		select @Short_wH=convert(char,convert(int,(@ShortageHour/60),2),2)
		select @Short_wmin= convert(int,@ShortageHour)%60
		if (len(rtrim(@Short_wH))=1) select @Short_wH= '0'+@Short_wH
		if (len(rtrim(@Short_wmin))=1) select @Short_wmin= '0'+@Short_wmin
		select @Short_workingHour= rtrim(@Short_wH) +':'+   rtrim(@Short_wmin)
end
select @LmworkingHour=@workingHour
-- calculation of OT
if @pHrsOT is null 
begin
select @pHrsOT='00:00' 
end
if( DateDiff(mi,  @S_workingHour,@workingHour)> 0 )
--select DateDiff(mi,'09:00','10:30')
begin
select @pOT=DateDiff(mi,  @S_workingHour,@workingHour)
	if ( @pOT>abs(@pEarlyIn))
		begin 
			select @LmworkingHour =convert(int,@wTHour) - convert(int,abs(@pEarlyIn))
		select @wH=convert(char,convert(int,(@LmworkingHour/60),2),2)
		select @wmin= convert(int,@LmworkingHour)%60
		if (len(rtrim(@wH))=1) select @wH= '0'+@wH
		if (len(rtrim(@wmin))=1) select @wmin= '0'+@wmin
		select  @LmworkingHour=  rtrim(@wH) +':'+   rtrim(@wmin)
		end
if @mOT='Y'
begin
--if you want the morning OT Comment this below line
select  @LmworkingHour=@workingHour
end
--end of morning OT
select @pOT=DateDiff(MI,  @S_workingHour,@LmworkingHour)/60
select @pHrsOT_hh=convert(char,@pOT,2)
select @pOT=DateDiff(mi,  @S_workingHour,@LmworkingHour)
	select @pHrsOT_mm=convert(char,@pOT%60,2)
*/
select @pHrsOT_hh=convert(char,DateDiff(hh,  @S_workingHour,@workingHour),2)
select @pHrsOT_mm=convert(char,DateDiff(mi, @S_workingHour,@workingHour)%60,2)
if convert(int,@pHrsOT_hh)<0 
begin
	set @pHrsOT_hh=0
end
	--convert(int,@S_wTHour)%60
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= '0'+@pHrsOT_hh
	if (len(rtrim(@pHrsOT_mm))=1) select @pHrsOT_mm= '0'+@pHrsOT_mm
select @Exot =rtrim(@pHrsOT_hh)+':'+rtrim(@pHrsOT_mm)
-- Rounding the OT Calculation if <29 means 00  and >30 <59 menas 30
if @RoundEnable='Y'
begin
if (convert(int,@pHrsOT_mm)<=15 )
	begin
	select @pHrsOT_mm='00'
	end
if (convert(int,@pHrsOT_mm)>15) and (convert(int,@pHrsOT_mm)<=30 )
	begin
	select @pHrsOT_mm='30'
	end
if (convert(int,@pHrsOT_mm)>30 and  convert(int,@pHrsOT_mm)<=45 )
	begin
	select @pHrsOT_mm='30'
	end
if  convert(int,@pHrsOT_mm)>45  
	begin
	select @pHrsOT_mm='00'
	select @pHrsOT_hh=convert(int,@pHrsOT_hh)+1
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= '0'+@pHrsOT_hh
	end
-- end of  Rounding off
end
 	select @pHrsOT =rtrim(@pHrsOT_hh)+':'+rtrim(@pHrsOT_mm)
select @MinOT =(select Shift_MinTimeOT from TA_Tbl_Shift where Shift_Id=@Shift_Id )
  select @MaxOT =(select Shift_MaxTimeOT from TA_Tbl_Shift where Shift_Id=@Shift_Id )
	if DateDiff(mi,'00:00',@MinOT)> DateDiff(mi,'00:00',@pHrsOT)
	begin
		select @pHrsOT='00:00'
	end
	if DateDiff(mi,'00:00',@MaxOT)>0
	begin
		if DateDiff(mi,'00:00',@MaxOT)< DateDiff(mi,'00:00',@pHrsOT)
		begin
			select  @pHrsOT=@MaxOT
		end
	end
	--end
if( DateDiff(mi,  @S_workingHour,@workingHour)<= 0 )
begin
select @pHrsOT='00:00'
select @Exot='00:00'
end
if @pHrsOT is null 
begin
select @pHrsOT='00:00' 
end
if @fin is null 
begin
select @fin='00:00:00' 
end
if @lout is null 
begin
select @lout='00:00:00' 
end
if @workingHour is null 
begin
select @workingHour='00:00' 
end
if @S_workingHour is null 
begin
select @S_workingHour='00:00' 
end
-- calculate late in and early out
if @OTtype='N'
begin
	set @pNormOT =@pHrsOT
	set @pOffOT='00:00'
	set @pHolOT ='00:00'
end
if @OTtype='O'
begin
	set @pNormOT ='00:00'
	set @pOffOT=@workingHour
	set @pHolOT ='00:00'
end
if @OTtype='H'
begin
	set @pNormOT ='00:00'
	set @pOffOT='00:00'
	set @pHolOT =@workingHour
end
--ExtraMins              OtMins 
Update 	dbo.TA_Tbl_ProcessedData 
set HrsWork=@workingHour,HrsOT=@pHrsOT,NormOT=@pNormOT,OffOT=@pOffOT,HolOT=@pHolOT,WorkHrs=@workingHour,HrsExtra=@pHrsOT
where Process_Rec_ID=@Process_Rec_ID
/*
if @pHrsOT	is null
begin 
select @pHrsOT='00:00'
end
	select @pHrsOT_hh=convert(char,convert(int,(@wTHour/60),2),2)
	select @pHrsOT_mm=convert(char,convert(int,(@wTHour),2)%60,2)
	--convert(int,@S_wTHour)%60
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= '0'+@pHrsOT_hh
	if (len(rtrim(@pHrsOT_mm))=1) select @pHrsOT_mm= '0'+@pHrsOT_mm
		select @Exot =rtrim(@pHrsOT_hh)+':'+rtrim(@pHrsOT_mm)
		if @RoundEnable='Y'
		begin
			-- Rounding the OT Calculation if <29 means 00  and >30 <59 menas 30
			if (convert(int,@pHrsOT_mm)<30 )
				begin
					select @pHrsOT_mm='00'
				end
			if  convert(int,@pHrsOT_mm)>30  
			begin
				select @pHrsOT_mm='30'
			end
		end
	select @pHrsOT =rtrim(@pHrsOT_hh)+':'+rtrim(@pHrsOT_mm)
if @Exot	is null
begin 
select @Exot='00:00'
end
delete from tblprocesseddata where pEmpId=@EMP_ID and  pDate=@EMP_date
*/
GO
/****** Object:  StoredProcedure [dbo].[ReProcessEmpData]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[ReProcessEmpData] @CompID VARCHAR(2),@frmdate datetime,@todate datetime
as
declare @Process_Rec_ID varchar(20)
declare @EmpID varchar(20)
declare @employeeid varchar(20)
declare @Company varchar(30)
declare @mSql varchar(200)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @MonthClosure_Id int
declare @totpresent int
declare @totAbsent int
declare @totHoliday int
declare @S_wH varchar(10) 
declare @S_wmin varchar(10) 
declare @S_workingHour varchar(10) 
declare @Shift_TotalWHours varchar(6) 
declare @WHours int
declare @shiftID int
declare @NewshiftID int
declare @totHrsWorks int
declare @totHrsOT int
declare @totNormOT int
declare @totOffOT int
declare @totHolOT int
declare @totEarlyOut int
declare @totLateIn int
declare @totWorkHrs int
declare @totHrsLess int
declare @totHrsExtra int
declare @employee_status int
declare @fromdate datetime
set @fromdate=@frmdate
select @eCount=(select count(*) from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID)
if (@eCount=0)
begin
		insert into dbo.TA_Tbl_MonthClosure(OrgLevel_Id,MonthClosure_Month,MonthClosure_Year,MonthClosure_StartDate,MonthClosure_EndDate,MonthClosure_ClosingDate,Emp_Id,Process,TimeStamp,IsDeleted,YearSettings_Id)
		values (@CompID,DateName(mm,@todate),year(@todate),@frmdate,@todate,getdate(),2,'N',getdate(),'False',1)
		set @MonthClosure_Id=(select MonthClosure_Id from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID )
end
else
begin
		set @MonthClosure_Id=(select MonthClosure_Id from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID )
end
declare emp_ReProcess cursor for 
--select EmpID,Company from  dbo.View_companyEmployees where id=@CompID order by empid
select EmpID,Company from  dbo.View_companyEmployees where id=@CompID and EmpID in(
SELECT     Employee_Code_Id
FROM         View_UnProcessEMPdata
GROUP BY Employee_Code_Id)
open emp_ReProcess
fetch emp_ReProcess into  @EmpID,@Company
while (@@fetch_status = 0 )
begin
select @fromdate=@frmdate
set @employee_status= (select employee_status from dbo.TA_Tbl_Employee where swipecardno=@EmpID)
While @fromdate <= @todate
begin
     set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
if (@eCount=0)
begin
			insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
			values(@EmpID,@fromdate,0,'Absent',0)
end
if (@employee_status=0)
begin
	update dbo.TA_Tbl_ProcessedData set processflag=1 where Employee_Code_Id=@EmpID and  Date= @fromdate
end
set @employeeid=(select max(employee_ID) from ta_tbl_employee where swipecardno=@EmpID)
set @eCount=( select count(*) from TA_Tbl_PermanentShiftAllocation where employeeid=@employeeid and year=year(@fromdate) and month=month(@fromdate))
if (@eCount=0)
begin
insert into TA_Tbl_PermanentShiftAllocation(EmployeeId,year,month,TimeStamp,DateShift,Emp_Id) 
values(@employeeid,year(@fromdate),month(@fromdate),getdate(),dateadd(d,-1*(day(@fromdate)-1),@fromdate),1)
end
select @shiftID=(select isnull(Shift_Id,0)  from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
select @msql ='update TA_Tbl_PermanentShiftAllocation set Day' +ltrim(str(day(@fromdate)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @employeeid +''' and month='''+ ltrim(str(month(@fromdate))) +''' and year='''+ltrim(str(year(@fromdate))) +''''
exec  (@mSql)
set @Shift_TotalWHours=''
if  (@shiftID=166 )
begin
	set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
	update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@EmpID and Date= @fromdate
	set @shiftID=@NewshiftID
end
set @eCount=( select count(*) from dbo.TA_Tbl_Shift where Level_Id=@CompID and Shift_Id=  @shiftID)
if (@eCount=0)
begin
	set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
	update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@EmpID and Date= @fromdate
	set @shiftID=@NewshiftID
end
set @employeeid=(select max(employee_ID) from ta_tbl_employee where swipecardno=@EmpID)
set @eCount=( select count(*) from TA_Tbl_PermanentShiftAllocation where employeeid=@employeeid and year=year(@fromdate) and month=month(@fromdate))
if (@eCount=0)
begin
insert into TA_Tbl_PermanentShiftAllocation(employeeid,year,month,TimeStamp,DateShift,Emp_Id) values(@employeeid,year(@fromdate),month(@fromdate),getdate(),dateadd(d,-1*(day(@fromdate)-1),@fromdate),1)
end
select @msql ='update TA_Tbl_PermanentShiftAllocation set Day' +ltrim(str(day(@fromdate)))+ 'Shift ='''+ltrim(str(@shiftID)) + ''' where  employeeid= ''' + @employeeid +''' and month='''+ ltrim(str(month(@fromdate))) +''' and year='''+ltrim(str(year(@fromdate))) +''''
exec  (@mSql)
if  (@shiftID>0)
begin
	set @Shift_TotalWHours =(select isnull(Shift_TotalWorkingHours,'') from dbo.TA_Tbl_Shift where Shift_Id = @shiftID)
end
 if  (@Shift_TotalWHours='')
begin
	set @Shift_TotalWHours ='09:00'
--(select isnull(Shift_TotalWorkingHours,'') from dbo.TA_Tbl_Shift where Shift_Id = @shiftID)
end 
--update dbo.TA_Tbl_ProcessedData set WorkHrs=@Shift_TotalWHours where Employee_Code_Id =@EmpID and Date= @fromdate
select @S_workingHour=(select isnull(HrsWork,'0') from  dbo.TA_Tbl_ProcessedData  where Employee_Code_Id =@EmpID and Date= @fromdate)
if (@S_workingHour='0')
begin
select @WHours=(select abs(datediff(minute,intime,outtime)) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
if (isnumeric(@WHours)=1)
begin
	if (@WHours<1200)
	begin
			select @S_wH=convert(char,convert(int,(@WHours/60),2),2)
			select @S_wmin= convert(int,@WHours)%60
			if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
			if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
			select @S_workingHour= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
--
--if @RoundEnable='Y'
--begin
--
--if (convert(int,@pHrsOT_mm)<=15 )
--	begin
--	select @pHrsOT_mm='00'
--	end
--if (convert(int,@pHrsOT_mm)>15) and (convert(int,@pHrsOT_mm)<=30 )
--	begin
--	select @pHrsOT_mm='30'
--	end
--if (convert(int,@pHrsOT_mm)>30 and  convert(int,@pHrsOT_mm)<=45 )
--	begin
--	select @pHrsOT_mm='30'
--	end
--
--if  convert(int,@pHrsOT_mm)>45  
--	begin
--	select @pHrsOT_mm='00'
--	select @pHrsOT_hh=convert(int,@pHrsOT_hh)+1
--	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= '0'+@pHrsOT_hh
--	end
--
---- end of  Rounding off
--end
-- 	select @pHrsOT =rtrim(@pHrsOT_hh)+':'+rtrim(@pHrsOT_mm)
--
			--update dbo.TA_Tbl_ProcessedData set HrsWork=@S_workingHour,WorkHrs=@Shift_TotalWHours where Employee_Code_Id =@EmpID and Date= @fromdate
end
	end
end   
select @fromdate = DateAdd("D", 1, @fromdate)
end
--
--
--
--set @totpresent = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Attendance ='Present' and date between @frmdate and @todate)
--set @totAbsent = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and (Attendance ='Absent' or Attendance is null) and date between @frmdate and @todate)
--set @totHoliday = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Attendance ='Weekly Off' and date between @frmdate and @todate)
--set @totHrsWorks=(select sum(datediff(minute,'00:00',isnull(hrsWork,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate)          
--
--set @totHrsOT =(select sum(datediff(minute,'00:00',isnull(HrsOT,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate)          
--set @totNormOT =(select sum(datediff(minute,'00:00',isnull(NormOT,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHolOT =(select sum(datediff(minute,'00:00',isnull(HolOT,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totEarlyOut =(select sum(datediff(minute,'00:00',isnull(EarlyOut,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totLateIn =(select sum(datediff(minute,'00:00',isnull(LateIn,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totWorkHrs =(select sum(datediff(minute,'00:00',isnull(WorkHrs,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHrsLess =(select sum(datediff(minute,'00:00',isnull(HrsLess,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHrsExtra =(select sum(datediff(minute,'00:00',isnull(HrsExtra,'00:00'))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--
--declare @p_totHrsWork varchar(10)
--declare @p_totHrsOT varchar(10)
--declare @p_totNormOT varchar(10)
--declare @p_totOffOT varchar(10)
--declare @p_totHolOT varchar(10)
--declare @p_totEarlyOut varchar(10)
--declare @p_totLateIn varchar(10)
--declare @p_totWorkHrs varchar(10)
--declare @p_totHrsLess varchar(10)
--declare @p_totHrsExtra varchar(10)
--
--select @S_wH=convert(char,convert(int,(@totHrsWorks/60),2),2)
--select @S_wmin= convert(int,@totHrsWorks)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
--select @p_totHrsWork= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,( @totHrsOT/60),2),2)
--select @S_wmin= convert(int, @totHrsOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
--select @p_totHrsOT= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,(@totNormOT/60),2),2)
--select @S_wmin= convert(int,@totNormOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
--select @p_totNormOT= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,(@totOffOT/60),2),2)
--select @S_wmin= convert(int,@totOffOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= '0'+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= '0'+@S_wmin
--select @p_totOffOT= rtrim(@S_wH) +':'+   rtrim(@S_wmin)
--
--delete from dbo.TA_Tbl_PayrollProcessDetails where MonthClosure_Id=@MonthClosure_Id and Employee_Id=@EmpID 
--insert into dbo.TA_Tbl_PayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,AbsentDays,PresentDays,Holidays,LOPDays,Emp_Id,TimeStamp)
--values(@MonthClosure_Id,@EmpID,@p_totHrsWork,@p_totHrsOT,@p_totNormOT,@p_totOffOT,@totAbsent,@totpresent,@totHoliday,0,2,getdate())
  fetch emp_ReProcess into @EmpID,@Company
end   
deallocate emp_ReProcess
GO
/****** Object:  StoredProcedure [dbo].[sampleCount]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Procedure [dbo].[sampleCount]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(50),
	@TitleId int
) 
As
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	Select Count(TitleName)as TName from TA_Tbl_Title
		where TitleId<>@TitleId And TitleName=@TitleName AND TitleDescription=@TitleDescription AND Isdeleted=@Isdel	
END
GO
/****** Object:  StoredProcedure [dbo].[select_EmpLeavePolicyDetails_EDR]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <11-May-2019 05.56 PM>
-- Description:	<After release We created this procedure>
-- select_EmpLeavePolicyDetails_EDR 3,'04/01/2019'
-- =============================================
CREATE PROCEDURE [dbo].[select_EmpLeavePolicyDetails_EDR]
(
	@PolicyID int,
	@fromDat varchar(20)
)
AS
BEGIN
	Declare @Diff int
	set @Diff=11-DATEPART(month,CONVERT(datetime,@fromDat))
	if(@Diff<=0)
	begin
		set @Diff=1
	end
	select LP.Policy_Id,PolicyName,LT.LeaveType_Id,LeaveType,
	Permonth=
	CASE	WHEN SUBSTRING(CONVERT(VARCHAR(10),MaxDays_applicable/12.0),CHARINDEX('.',MaxDays_applicable/12.0)+1,LEN(MaxDays_applicable/12.0))%5!=0 then 
				CASE	WHEN DATEPART(MONTH,CONVERT(DATETIME,@fromdat)) In(11) then CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*4 
						WHEN DATEPART(MONTH,CONVERT(DATETIME,@fromdat)) In(12) then CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*2
						ELSE CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*@Diff+4 
				END
			ELSE CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,2)*(13-DATEPART(month,CONVERT(datetime,@fromDat))))
	END,
	MaxDays_applicable from TA_Tbl_LeavePolicyDetails LP 
	INNER JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id=LP.LeaveType_Id 
	INNER JOIN TA_Tbl_LeavePolicy L ON L.Policy_Id=LP.Policy_Id where LP.policy_id=@PolicyID
END
GO
/****** Object:  StoredProcedure [dbo].[SelectReportingToSanctionAuthorityForPermission]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[SelectReportingToSanctionAuthorityForPermission]
	-- Add the parameters for the stored procedure here
	@Permission_ID int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=(
	select Employee_id from ta_tbl_Permission where Permission_id=@Permission_ID)
END
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPattern]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Janakaraj>
-- ALTER  date: <ALTER  Date,,04July2007>
-- Description:	<Description,,>
-- SelectShiftPattern 'SuperAdmin','1,137,138,2,3,140,47,113,132,134,135,150,136,145,146,147,151,152,153,154,155,159,160,161,162,133'
-- =============================================
CREATE  PROCEDURE [dbo].[SelectShiftPattern]
@usergroupname nvarchar(250),
@UserLevels nvarchar(2000),
@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
DECLARE @Isdel int
declare @Query as varchar(7000)
SET @Isdel=0
if(@usergroupname='SuperAdmin')
	BEGIN
		SET NOCOUNT ON;
		--set @Query = 'SELECT LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,SP.Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id WHERE SP.Level_Id in ( '+ @UserLevels +' )'
		set @Query = 'SELECT LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,case when SP.IsDeleted=1 then ''True'' else ''False'' end Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id INNER JOIN #LevelRights ON #LevelRights.LevelId = SP.Level_Id'
	END
else
	BEGIN
		SET NOCOUNT ON;
		--set @Query = 'SELECT  LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,SP.Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id WHERE SP.Isdeleted='+cast(@Isdel as nvarchar(5))+' and SP.Level_Id in ( '+ @UserLevels +' )'
		set @Query = 'SELECT  LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,case when SP.IsDeleted=1 then ''True'' else ''False'' end Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id INNER JOIN #LevelRights ON #LevelRights.LevelId = SP.Level_Id WHERE SP.Isdeleted='+cast(@Isdel as nvarchar(5))+''
	END
exec(@Query)
drop table #LevelRights
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternById]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
Modified by	:	P.Prabakaran
Modified on	:	06-Feb-08
*/
CREATE    PROCEDURE [dbo].[SelectShiftPatternById](@PatternId int)
AS
	DECLARE @Isdel int
	SET @Isdel=0
	BEGIN
		SET NOCOUNT ON;
		--SELECT * FROM TA_Tbl_ShiftPattern WHERE Isdeleted=@Isdel and ShiftPattern_Id=@PatternId
		SELECT TA_Tbl_ShiftPattern.*,TA_Tbl_Leveldetails.Name 
		FROM TA_Tbl_ShiftPattern INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_ShiftPattern.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE ShiftPattern_Id=@PatternId
	END
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternDeleteById]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE  PROCEDURE [dbo].[SelectShiftPatternDeleteById]
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_ShiftRoaster WHERE Isdeleted=@Isdel 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeeLog]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Thilakraj Chinaaraj>
-- Create date: <10-Dec-2015>
-- Description:	<For Sample Web services>
/*
Exec TA_Proc_EmployeeLog '789','2016-02-26'
*/
-- =============================================
CREATE PROCEDURE [dbo].[TA_Proc_EmployeeLog]
(	@EmployeeCodeID  int=null,
	@date  date =null
)
AS
BEGIN
Declare @Monday as Date
Declare @Saturday as Date
DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), 
	    TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
Create table #TempAttendanceDetails (FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),LevelName nvarchar(250),Designation nvarchar(250),Date VARCHAR(20),InTime varchar(20),OutTime varchar(20),HrsWork varchar(20),
	TotalMinsWorked varchar(20),Shift_ShortName varchar(100),ShiftId int,shift_TotalWorkingHours nvarchar(50),LunchHours varchar(50),DefinedWorkHours varchar(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId int, CategoryName NVARCHAR(50),thirdSat bit,DinnerHours varchar(50),
	ArmisMin BIGINT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10), MinWorkHours BIGINT, ToolTip VARCHAR(MAX))
if (@EmployeeCodeID is null)
	Begin
		Set @EmployeeCodeID=973;
	End
if (@date is null)
	Begin
		Set @date=GETDATE();
	End
	SELECT RD.CLK_ID,RD.CLK_CARDID as 'Employee ID',RD.CLK_DATE as 'Date' ,RD.CLK_TIME as 'Time' ,T.Terminal_Name,PT.PunchType
	from TA_Tbl_Clk_RawData RD
	Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	Where RD.CLK_CARDID=@EmployeeCodeID and  RD.CLK_DATE=@date
	order by CLK_ID 
	SELECT E.Employee_FirstName + ' ' +E.Employee_LastName,PD.Employee_Code_Id as 'Employee ID',
	PD.Date as 'Date' , PD.InTime,PD.OutTime,
	CASE WHEN LEN(CAST((B.TotalBreakmin/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((B.TotalBreakmin/60) AS VARCHAR(25)) ELSE  CAST((B.TotalBreakmin/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((B.TotalBreakmin%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((B.TotalBreakmin%60) AS VARCHAR(25)) ELSE CAST((B.TotalBreakmin%60) AS VARCHAR(25)) END as 'Break Hrs',
	PD.HrsWork , '00:00' as 'Work so For'
	from  TA_Tbl_ProcessedData PD 
	Inner join TA_Tbl_Employee E On E.Employee_Code_Id=PD.Employee_Code_Id
	Inner Join ta_tbl_TotalBreakHours B on B.Employee_Code_Id=PD.Employee_Code_Id and B.ShiftDate=PD.Date
	Where PD.Employee_Code_Id=@EmployeeCodeID and  PD.Date=@date
Set @Monday= dateadd(wk, datediff(wk, 0, @date), 0)
Set @Saturday= dateadd(wk, datediff(wk, 0, @date), 0) + 5 
INSERT INTO @ArmisData
SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,'00:00',REPLACE(CAST(ISNULL(TotalTask, '0.0') AS VARCHAR), '.', ':')) AS BIGINT) END) FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@Monday, @Saturday, @EmployeeCodeID)
	insert into #TempAttendanceDetails
		select 
			pd.fnAttendanceCode + case  when Status is null then '' else '(BL)' end as FirstSession,
			pd.anAttendanceCode + case  when Status is null then '' else '(BL)' end  as SecondSession, 
			e.Employee_Code_Id as Employee_Id,
			isnull(e.Employee_FirstName,'') +  space(1) + isnull(e.Employee_LastName,'') as empName,
			replace(dbo.Ta_Tbl_levelDetails.name,'&amp;','&') as BranchName,
			replace(T.TitleName,'&amp;','&') as Designation,
			convert(varchar(11),pd.date,101) as Date,
			ISNULL(pd.InTime, '-'),
			ISNULL(pd.OutTime, '-'),
			ISNULL(pd.HrsWork, '-'), 
			((substring(isnull(pd.HrsWork,'00:00'),0,3)*60) + (substring(isnull(pd.HrsWork,'00:00'),4,2))) as TotalMinsWorked
			,(shf.Shift_ShortName + '(' + shf.Shift_StartTime + ' - '  + shf.Shift_EndTime + ')') as Shift_ShortName,
			pd.shift_id as ShiftID,
			shf.shift_TotalWorkingHours,
			ISNULL(pd.BreakHours, '-') as LunchHours , 
			TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours,
			DATENAME(DW,pd.date), 
			(CASE WHEN ((DATENAME(DW,pd.date) != 'Saturday') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,'.5', '.3'), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), ':', '.') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = 'Saturday') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,'.5', '.3'), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), ':', '.') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END)
			,(CASE WHEN ISNULL(Pd.BreakIn, '') <> '' AND ISNULL(Pd.BreakOut, '') <> '' AND (DATEDIFF(MI, ISNULL(SS.MaxLunchHours, '00:40'), ISNULL(REPLACE(pd.BreakHours, '-', ''), '00:00')) > 0) THEN 1 ELSE 0 END),TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,0,DinnerHours, 0, DATEDIFF(MI, '00:00', ISNULL(SS.MaxWorkPlaceInHours, '00:10')), '00:00', TBH.TotalBreakmin, (CASE WHEN (DATENAME(DW,pd.date) != 'Saturday') THEN DATEDIFF(MI, '00:00',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,'.5', '.3'), 0.0)), '.', ':')) ELSE DATEDIFF(MI, '00:00',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,'.5', '.3'), 0.0)), '.', ':')) END), NULL
		from Ta_Tbl_Employee e 
		inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id 	
		inner join ta_tbl_TotalBreakHours TBH on TBH.Employee_Code_Id=pd.Employee_Code_Id and TBH.Shiftdate=pd.date 
		inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id
		inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID 	
		inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId
		inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId   
		inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId
		inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId
		inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId
		inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId
		inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId 
		left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id
		LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId 
		where e.Isdeleted=0 and e.report_exclude=0 AND TA_Tbl_Grade.Grade_Level>=0 and (e.Employee_Code_Id = '' + cast(@EmployeeCodeID as nvarchar(100)) + '') and e.employee_Status=1 and((pd.date >= CONVERT(DATETIME, '' + cast(@Monday as nvarchar(11)) + '', 102) and pd.date <= CONVERT(DATETIME, '' + cast(@Saturday as nvarchar(11)) + '', 102)))
	Declare @firstsat date
	Declare @ThirdSat date
	 Select  @firstsat= dateadd(dd,(datediff(dd,-53685,dateadd(mm,datediff(mm,0,@Saturday),6))/7)*7,-53685)
	 Select @ThirdSat=DATEADD(dd,14,@firstsat)
	 Update #TempAttendanceDetails set thirdSat=1 where  #TempAttendanceDetails.Day='Saturday' and #TempAttendanceDetails.Date=@ThirdSat
	 create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATE, ArmisHrs BIGINT)
   INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.DefinedWorkHours,
			SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] != 'Saturday')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off') AND (TA.[Day] = 'Saturday')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off' ,'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN('Present', 'Absent', 'Weekly Off', 'Holiday')) OR (TA.ANAttendanceCode NOT IN ('Present', 'Absent', 'Weekly Off','Holiday'))) AND TA.[Day] = 'Saturday' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = 'Holiday' AND TA.ANAttendanceCode = 'Holiday' AND TA.[Day] = 'Saturday' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
			0,
			SUM(CAST(TA.totalMinsWorked AS INT)),
			0,
			TA.CategoryName,
			CAST(MAX(TA.[Date]) AS DATE),
			SUM(ArmisMin)
		FROM #TempAttendanceDetails TA
			INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != 'Sunday'
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
	 update #TempAttendanceSummary set SupposedToWorkHours = (DefinedWorkHours - (HoursToDeduct))
	 update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	 update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	 select 
		Employee_Code_Id,
		EmployeeName,
		DefinedWorkHours,		
		HoursToDeduct,
	    SupposedToWorkHours,
		CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN '0' +  cast((ActualWorkHours/60) as varchar(25)) ELSE  cast((ActualWorkHours/60) as varchar(25)) END  + ':' + CASE  WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN '0' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
		CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN '0' +  cast((LessHours/60) as varchar(25)) ELSE  cast((LessHours/60) as varchar(25)) END  + ':' + CASE  WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN '0' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
		CategoryName,
		(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN '0' +  CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END  + '.' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid,
		CASE WHEN LEN(CAST((ArmisHrs/60) AS VARCHAR(25)))=1 THEN '0' +  CAST((ArmisHrs/60) AS VARCHAR(25)) ELSE  CAST((ArmisHrs/60) AS VARCHAR(25)) END  + ':' + CASE  WHEN LEN(CAST((ArmisHrs%60) AS VARCHAR(25))) = 1 THEN '0' + CAST((ArmisHrs%60) AS VARCHAR(25)) ELSE CAST((ArmisHrs%60) AS VARCHAR(25)) END AS ArmisHrs
	 from #TempAttendanceSummary
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeePunchMonitor]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Thilakraj Chinaaraj>
-- Create date: <26-Feb-2016>
-- Description:	<For Sample Web services>
/*
Exec [TA_Proc_EmployeePunchMonitor] '789'
*/
-- =============================================
CREATE PROCEDURE [dbo].[TA_Proc_EmployeePunchMonitor]
(	
@EmployeeCodeID  int=null,
	@date  date =null
)
AS
BEGIN
	if (@EmployeeCodeID is null)
	Begin
		Set @EmployeeCodeID=973;
	End
	if (@date is null)
	Begin
		Set @date=GETDATE();
	End
		--Set @EmployeeCodeID=789;
	--Insert into Ta_tbl_EmployeePunch  
	--Select RD.CLK_CARDID as 'Employee ID',RD.CLK_DATE as 'Date' ,RD.CLK_TIME as 'Time'
	--from TA_Tbl_Clk_RawData RD
	--Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	--Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	--Where RD.CLK_CARDID=@EmployeeCodeID and RD.CLK_DATE=@date and(Rd.CLK_FLAG=0 or CLK_PROCESS=0)
	--order by CLK_ID 
	SELECT RD.CLK_ID,RD.CLK_CARDID as 'Employee ID',RD.CLK_DATE as 'Date' ,RD.CLK_TIME as 'Time' ,T.Terminal_Name,PT.PunchType
	from TA_Tbl_Clk_RawData RD
	Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	inner Join Ta_tbl_EmployeePunch EP on RD.CLK_CARDID=EP.EmployeeId
	Where RD.CLK_CARDID=@EmployeeCodeID and RD.CLK_DATE=@date and(Rd.CLK_FLAG=0 or CLK_PROCESS=0) 
	order by CLK_ID 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_checkHolidayLeaveApplication]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- TA_Tbl_checkHolidayLeaveApplication '2011-07-28','2011-07-28'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[TA_Tbl_checkHolidayLeaveApplication]
	@Fromdate datetime,
	@ToDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	select COUNT(*) as HolidayCount from TA_Tbl_Holiday where (Holiday_FromDate >= @Fromdate and Holiday_FromDate <= @ToDate) and (Holiday_ToDate >=@Fromdate and 
	Holiday_ToDate <= @ToDate) and Holiday_Type='G'
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_Proc_checkGroupName]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
	Created on : 11 August 2007
	Created by : Senthil
	Descripttion : Checking groupname for duplication
*/
CREATE procedure [dbo].[TA_Tbl_Proc_checkGroupName]
(
	@groupName as nvarchar(100)
)
as
Begin
	select count(*) as recCount from ta_tbl_userRights where groupName=@groupName
End
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftPatternId]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Temp_ShiftPatternId](@ShiftPatternid int)
 AS
SELECT *  FROM TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternid
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftRoaster]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[Temp_ShiftRoaster] AS
select * from TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id=1
GO
/****** Object:  StoredProcedure [dbo].[temp_UpdatePerShiftAllocation]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[temp_UpdatePerShiftAllocation] 
(@EmpId int,@year int,@month int,@Day1Shift int,@Day2Shift int,@Day3Shift int,@Day4Shift int,@Day5Shift int,@Day6Shift int,@Day7Shift int,@Day8Shift int,@Day9Shift int,@Day10Shift int,@Day11Shift int,@Day12Shift int,@Day13Shift int,@Day14Shift int,@Day15Shift int,@Day16Shift int,@Day17Shift int,@Day18Shift int,@Day19Shift int,@Day20Shift int,@Day21Shift int,@Day22Shift int,@Day23Shift int,@Day24Shift int,@Day25Shift int,@Day26Shift int,@Day27Shift int,@Day28Shift int,@Day29Shift int,@Day30Shift int,@Day31Shift int)
AS
	BEGIN 
		UPDATE TA_Tbl_PermanentShiftAllocation SET Day1Shift=@Day1Shift,Day2Shift=@Day2Shift,Day3Shift=@Day3Shift,Day4Shift=@Day4Shift,Day5Shift=@Day5Shift,Day6Shift=@Day6Shift,Day7Shift=@Day7Shift,Day8Shift=@Day8Shift,Day9Shift=@Day9Shift,Day10Shift=@Day10Shift,Day11Shift=@Day11Shift,Day12Shift=@Day12Shift,Day13Shift=@Day13Shift,Day14Shift=@Day14Shift,Day15Shift=@Day15Shift,Day16Shift=@Day16Shift,Day17Shift=@Day17Shift,Day18Shift=@Day18Shift,Day19Shift=@Day19Shift,Day20Shift=@Day20Shift,Day21Shift=@Day21Shift,Day22Shift=@Day22Shift,Day23Shift=@Day23Shift,Day24Shift=@Day24Shift,Day25Shift=@Day25Shift,Day26Shift=@Day26Shift,Day27Shift=@Day27Shift,Day28Shift=@Day28Shift,Day29Shift=@Day29Shift,Day30Shift=@Day30Shift,Day31Shift=@Day31Shift WHERE [Year]=@year and [Month]=@month and  EmployeeId=@EmpId
	END
GO
/****** Object:  StoredProcedure [dbo].[Temp_UpdateShift]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Temp_UpdateShift] (@ShiftName varchar(10),@Shift_ShortName varchar(20) )
AS
  UPDATE TA_Tbl_Shift SET Shift_Name=@ShiftName,Shift_ShortName=@Shift_ShortName
GO
/****** Object:  StoredProcedure [dbo].[Template_Delete]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Template_Delete]
AS
BEGIN
--DELETE FROM TBL_TEMPLATEMASTER
RETURN (@@ROWCOUNT)
END
GO
/****** Object:  StoredProcedure [dbo].[Template_Enroll]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Template_Enroll]
	( @EmpID   nvarchar(10),
	 @Template  	image,
	 @DeviceID 	nvarchar(20),
		@UserLevel varchar(2),
@Stemplate varchar(50),
@SHextemp varchar(50))
AS
Declare @idVAl  int
Declare @idLen  int
--Declare i  int
BEGIN
begin
set @idLen=len(@EmpID)
IF(@idLen=5)
begin
set @EmpID='0'+@EmpID
end
IF(@idLen=4)
begin
set @EmpID='00'+@EmpID
end
IF(@idLen=3)
begin
set @EmpID='000'+@EmpID
end
IF(@idLen=2)
begin
set @EmpID='0000'+@EmpID
end
IF(@idLen=1)
begin
set @EmpID='00000'+@EmpID
end
END
set @idVAl= (SELECT count(EmpID)   FROM tbl_templatemaster where empId=@EmpID)
if( @idVAl=0)
begin
insert into tbl_templatemaster(EmpID,Template,DeviceID,CreatedDate,UserLevel, STmpData,SHextemp)values(@EmpID,@Template,@DeviceID,getdate(),@UserLevel,@Stemplate,@SHextemp)
end
else
begin
update tbl_templatemaster set ModifiedDate=getdate(),DeviceID=@DeviceID,Template=@Template, STmpData=@Stemplate,SHextemp=@SHextemp where EmpID=@EmpID
end
update tblDeviceEnrUsers set Status='Y' where EmpCode=@EmpID
RETURN (@@ROWCOUNT)
END
GO
/****** Object:  StoredProcedure [dbo].[Template_LogInsert]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Template_LogInsert]
	(@UserID   nvarchar(15),@LogFlag  nvarchar(2),@DeviceID nvarchar(15),@DeviceName nvarchar(15),@devDate nvarchar(15),@DevTime  nvarchar(15),@LogType nvarchar(10),@KeyID nvarchar(15))
AS
DECLARE @dtDateTime AS DATETIME
DECLARE @nTNAEvent AS INT
DECLARE @nEvent AS INT
DECLARE @lType AS varchar(3)
SET @dtDateTime=@devDate +' ' +@DevTime
SET @nTNAEvent=@LogType
BEGIN
--"IV";// user identity varified    55
--"NH";// not currently used   54
--"UN";// valid user entered but hand rejected (Not Verified)   56
--"ER";//user enrolled at the reader   10
--"CM";// user entered through the terminal command mode      11
	IF(@LogFlag='IV')--user identity varified    55
	begin
		set @nEvent=55
	end
	 IF(@LogFlag='NH')--not currently used   54
	begin
		set @nEvent=54
	end
	 IF(@LogFlag='UN')-- valid user entered but hand rejected (Not Verified)   56
	begin
		set @nEvent=56
	end
 	IF(@LogFlag='ER')
	begin
		set @nEvent=10
	end
	 IF(@LogFlag='CM')
	begin
		set @nEvent=11
	end
--******************************************************************************************************************************************************************
	set @nTNAEvent='0'
	if @LogType='1'  --IN
	begin
		set @nTNAEvent='0'
	end
	if @LogType='3'--OUT
	begin
		set @nTNAEvent='1'
	end
	if @LogType='2'--Lunch IN 
	begin
		set @nTNAEvent='2'
	end
	if @LogType='4'--Lunch Out
	begin
		set @nTNAEvent='3'
	end
	if @LogType='5'
	begin
		set @nTNAEvent='5'
	end
	if @LogType='6'
	begin
		set @nTNAEvent='6'
	end
	if @LogType='7'
	begin
		set @nTNAEvent='7'
	end
	if @LogType='8'
	begin
		set @nTNAEvent='8'
	end
--*******Based on Mechine IO Type Change the LOgs***********************************************************
	set  @lType=(select D_INOUT from dbo.tblDevice_Mast where Device_ID=@DeviceID)
	if  @lType='IN'  --IN
	begin
		set @nTNAEvent='0'
	end
	if  @lType='OUT'--OUT
	begin
		set @nTNAEvent='1'
	end
if len(@UserID)>6
	begin
		set @UserID=right(@UserID,6)
	end
INSERT INTO tb_reportslist(nUserID,dtDateTime,nDeviceID,nEvent,nTNAEvent,strUniqueKey)VALUES(@UserID,@dtDateTime,@DeviceID,@nEvent,@nTNAEvent,@KeyID)
IF(@LogFlag='ER' or @LogFlag='CM')
	begin
		delete from  tblDeviceEnrUsers where EmpCode=@UserID
		insert into tblDeviceEnrUsers(EmpCode,EnrDateTime,DeviceID) values(@UserID,@dtDateTime,@DeviceID)
	end
END
GO
/****** Object:  StoredProcedure [dbo].[Template_Read]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[Template_Read]
	( @EmpID   nvarchar(10))
AS
BEGIN
SELECT Template FROM tbl_templatemaster WHERE EmpID=@EmpID
END
GO
/****** Object:  StoredProcedure [dbo].[TotalLeavesAvailedDetails_Employee]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-Apr-2019 06:56 PM>
-- Description:	<Get the total leave taken,balance details>
-- TotalLeavesAvailedDetails_Employee 41
-- select * from ta_tbl_employee
-- =============================================
CREATE PROCEDURE [dbo].[TotalLeavesAvailedDetails_Employee]
	@Employee_id bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @YearSettingId INT
	SELECT @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where IsActive=1
	Declare @EarnedLeave decimal(18,1)
	Declare @LOP decimal(18,1)
	Declare @LeaveBal decimal(18,1)
	Declare @WaiveOff decimal(18,1)
	print @YearSettingId
	if not exists(select LeaveApplication_Id from TA_Tbl_LeaveApplication where Employee_Id=@Employee_id and IsDeleted=0)
	begin
		select	@EarnedLeave	=0,
				@LOP			=0,
				@LeaveBal		=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)),
				@WaiveOff		=0
		from TA_tbl_Yearclosure yc  
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
		inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
		left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
		and la.Status  not in ('Rejected') and la.Type not in ('Restricted Holiday','Comp Off','ESI')   
		and la.IsBorrow=0 group by la.LeaveType_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
	end
	else
	begin
		CREATE TABLE #Temp(Employee_id bigint,EarnedLeave decimal(18,1),LOP decimal(18,1),LeaveBal decimal(18,1),WaiveOff decimal(18,1))
		Insert into #Temp(Employee_id)values(@Employee_id)
		--select * from #Temp
		update T set LeaveBal=a.NumberOfDays from #Temp T inner join
		(
			select	yc.Employee_id,NumberOfDays=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))
			from TA_tbl_Yearclosure yc  
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
			and la.Status  not in ('Rejected') and la.Type not in ('Restricted Holiday','Comp Off','ESI')   
			and la.IsBorrow=0 group by yc.Employee_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
		)as a on a.Employee_Id=T.Employee_id
		update T set EarnedLeave=b.ELNumberOfDays,LOP=b.LOPNumberOfDays,WaiveOff=b.WONumberOfDays from #Temp T inner join
		(
			select ELNumberOfDays=sum(ELNumberOfDays),WONumberOfDays=sum(WONumberOfDays),LOPNumberOfDays=sum(LOPNumberOfDays),Employee_Id from
			( 
				select  ELNumberOfDays=case when lt.LeaveType='EL' and la.Type!='LOP' then la.NumberOfDays else 0 end,
						WONumberOfDays=case when lt.LeaveType='WO' then la.NumberOfDays else 0 end,
						LOPNumberOfDays=case when la.Type='LOP' then la.NumberOfDays else 0 end,
						Employee_Id from TA_Tbl_LeaveApplication la
				inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
				where la.Status  not in ('Rejected') and la.IsDeleted=0				
			)as a group by Employee_Id
		)as b on b.Employee_Id=T.Employee_id
		--update T set WaiveOff=a.NumberOfDays from #Temp T inner join
		--(
		--	select  NumberOfDays=SUM(la.NumberOfDays),Employee_Id,la.LeaveType_id from TA_Tbl_LeaveApplication la
		--	inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
		--	where lt.LeaveType='WO' and la.Status  not in ('Rejected') and la.IsDeleted=0
		--	group by Employee_Id,la.LeaveType_id
		--)as a on a.Employee_Id=T.Employee_id
		--update T set LOP=a.NumberOfDays from #Temp T inner join
		--(
		--	select  NumberOfDays=SUM(la.NumberOfDays),Employee_Id,la.LeaveType_id from TA_Tbl_LeaveApplication la
		--	inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
		--	where la.Type='LOP' and la.Status  not in ('Rejected') and la.IsDeleted=0
		--	group by Employee_Id,la.LeaveType_id
		--)as a on a.Employee_Id=T.Employee_id
		select	@EarnedLeave=EarnedLeave,@LOP=LOP,@LeaveBal=LeaveBal,@WaiveOff=WaiveOff from #Temp
	end
	Declare @ConcernName varchar(500)
	--select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id
	select top 1 @ConcernName=name from Ta_Tbl_levelDetails where description in(select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id)
	select	LeaveTaken=(isnull(@EarnedLeave,0)+isnull(@LOP,0)+isnull(@WaiveOff,0)),
			EarnedLeave=isnull(@EarnedLeave,0),
			LOP=isnull(@LOP,0),
			LeaveBal=isnull(@LeaveBal,0),
			WaiveOff=isnull(@WaiveOff,0),
			ConcernName=isnull(@ConcernName,'')
END
GO
/****** Object:  StoredProcedure [dbo].[TransferGetDesign]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TransferGetDesign]

	@ParentID nvarchar(50) = '1' 
AS
BEGIN
	
	Select * from TA_Tbl_Title where  LevelID = @ParentID
END
GO
/****** Object:  StoredProcedure [dbo].[UpdateDefaultGradeForSEFromDemo]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[UpdateDefaultGradeForSEFromDemo]
	-- Add the parameters for the stored procedure here
	@gradeName nvarchar(50),
    @gradeLevel int,
	@empAutoId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @RecordCount as int
	set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name='SEGrade')
	/**********/
	delete from TempEmployee 
	delete from temptitle
	delete from TempApprovalSettings
	Insert into temptitle	
	select TitleName, TitleDescription, LevelID, LeavePolicyID, GradeID, Emp_Id, IsDeleted, Time_Stamp,
	TitleId from TA_Tbl_Title 
	Insert into TempEmployee 
		select Employee_Id,Leave_Sanc_Authority,Reporting_To from TA_Tbl_Employee WHERE Employee_Code_Id <> '18000000'
	Insert into TempApprovalSettings
	select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry , Approval,ShiftRequisition
	from TA_Tbl_ApprovalSettings
	/**********/
	if(@RecordCount=0)
		begin	
			INSERT INTO TA_Tbl_Grade(Grade_Name,Grade_Level,Emp_ID,Time_Stamp,Isdeleted) VALUES(@gradeName,@gradeLevel,@empAutoId,getdate(),0)
			select @@identity
			UPDATE TA_Tbl_Title SET GradeID = @@identity
			UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> '18000000'
			update TA_Tbl_Grade set Isdeleted=1 where Grade_ID <> @@identity
			--DELETE TA_Tbl_Grade WHERE Grade_ID <> @@identity
			DELETE FROM TA_Tbl_ApprovalSettings
		end
	else
		begin
			UPDATE TA_Tbl_Grade SET Isdeleted =0 where Grade_ID=(select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=1)
			UPDATE TA_Tbl_Title SET GradeID = (select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1)
			UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> '18000000'
			update TA_Tbl_Grade set Isdeleted=1 WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=0)
			--DELETE TA_Tbl_Grade WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name='SEGrade' and Grade_Level=1 and IsDeleted=0)
			DELETE FROM TA_Tbl_ApprovalSettings
		end		
END

GO
/****** Object:  StoredProcedure [dbo].[VerifyShift]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[VerifyShift] 
as
declare @Employee_Code varchar(20)
declare @Emp_year varchar(20)
declare @Emp_month varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @scount  int 
declare @Day1Shift int
declare @Day2Shift int
declare @Day3Shift int
declare @Day4Shift int
declare @Day5Shift int
declare @Day6Shift int
declare @Day7Shift int
declare @Day8Shift int
declare @Day9Shift int
declare @Day10Shift int
declare @Day11Shift int
declare @Day12Shift int
declare @Day13Shift int
declare @Day14Shift int
declare @Day15Shift int
declare @Day16Shift int
declare @Day17Shift int
declare @Day18Shift int
declare @Day19Shift int
declare @Day20Shift int
declare @Day21Shift int
declare @Day22Shift int
declare @Day23Shift int
declare @Day24Shift int
declare @Day25Shift int
declare @Day26Shift int
declare @Day27Shift int
declare @Day28Shift int
declare @Day29Shift int
declare @Day30Shift int
declare @Day31Shift int
declare @shiftIDS int
declare emp_ReProcess cursor for 
select EmployeeId,Year,Month,Day1Shift,Day2Shift,Day3Shift,Day4Shift,Day5Shift,Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
 from dbo.TA_Tbl_PermanentShiftAllocation where Month >6
open emp_ReProcess
fetch emp_ReProcess into @Employee_Code,@Emp_year,@Emp_month,@Day1Shift,@Day2Shift,@Day3Shift,@Day4Shift,@Day5Shift,@Day6Shift,@Day7Shift,@Day8Shift,@Day9Shift,@Day10Shift,@Day11Shift,@Day12Shift,@Day13Shift,@Day14Shift,@Day15Shift,@Day16Shift,@Day17Shift,@Day18Shift,@Day19Shift,@Day20Shift,@Day21Shift,@Day22Shift,@Day23Shift,@Day24Shift,@Day25Shift,@Day26Shift,@Day27Shift,@Day28Shift,@Day29Shift,@Day30Shift,@Day31Shift
while (@@fetch_status = 0 )
begin
set @shiftIDS=167
-- select * from dbo.TA_Tbl_ProcessedData where
-- Shift_Id not in ( select Shift_Id from dbo.TA_Tbl_Shift) and Shift_Id<>0 and  Shift_Id<>-1 order by date 
 if (@Day1Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day1Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day1Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day2Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day2Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day2Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day3Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day3Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day3Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day4Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day4Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day4Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day5Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day5Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day5Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day6Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day6Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day6Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day7Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day7Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day7Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day8Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day8Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day8Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day9Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day9Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day9Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day10Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day10Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day10Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day11Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day11Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day11Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day12Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day12Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day12Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day13Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day13Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day13Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day14Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day14Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day14Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day15Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day15Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day15Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day16Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day16Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day16Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day17Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day17Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day17Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day18Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day18Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day18Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day19Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day19Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day19Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day20Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day20Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day20Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day21Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day21Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day21Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day22Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day22Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day22Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day23Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day23Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day23Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day24Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day24Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day24Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day25Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day25Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day25Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day26Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day26Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day26Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day27Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day27Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day27Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day28Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day28Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day28Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day29Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day29Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day29Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day30Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day30Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day30Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day31Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day31Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day31Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
--select @scount=2
--While @scount <= 30
--begin
--set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id ='@Day'+ltrim(str(@scount))+'Shift')
-- if (@eCount=0)
--begin
-- end
--select @scount=2+1
--end
  fetch emp_ReProcess into @Employee_Code,@Emp_year,@Emp_month,@Day1Shift,@Day2Shift,@Day3Shift,@Day4Shift,@Day5Shift,@Day6Shift,@Day7Shift,@Day8Shift,@Day9Shift,@Day10Shift,@Day11Shift,@Day12Shift,@Day13Shift,@Day14Shift,@Day15Shift,@Day16Shift,@Day17Shift,@Day18Shift,@Day19Shift,@Day20Shift,@Day21Shift,@Day22Shift,@Day23Shift,@Day24Shift,@Day25Shift,@Day26Shift,@Day27Shift,@Day28Shift,@Day29Shift,@Day30Shift,@Day31Shift
end   
deallocate emp_ReProcess
GO
/****** Object:  StoredProcedure [dbo].[VerifyWarningAlertMsgTriggerredAlready]    Script Date: 10-30-2024 09:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-Nov-2019 05:30 PM>
-- Description:	<Verifying already alert message sent or not to current employee on this month>
-- VerifyWarningAlertMsgTriggerredAlready  787,1
-- =============================================
CREATE PROCEDURE [dbo].[VerifyWarningAlertMsgTriggerredAlready] 
	@EmployeeID VARCHAR(50),
	@scheduleID BIGINT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @FromDate DATETIME
	DECLARE @Todate DATETIME
	DECLARE @isCross INT
	--Which is used to define cross month need to check or straight case
	--1 means cross month. 0 means straight case.
	SET @isCross=0
	DECLARE @ScheduleName VARCHAR(50)
	SET @ScheduleName=''
	--Get Current Schedule Name
	SELECT @ScheduleName=ScheduleName FROM TA_Tbl_EmailSchedule WHERE ScheduleId=@scheduleID AND IsDeleted=0
	--Get current Date here
	Declare @CurrentDate DATETIME
	SET @CurrentDate=CONVERT(VARCHAR(11),DATEADD(d,0,GETDATE()))
	IF(@isCross=0)
	BEGIN
		SELECT @FromDate=DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate),0)
	END
	ELSE
	BEGIN
		DECLARE @currentDay INT
		SET @currentDay=DATEPART(d,@CurrentDate)
		--from 1 to 15 it will check the previous month 16 to till date. after that it will check the current month 16 to current date 
		IF(@currentDay>=1 and @currentDay<=15)
		BEGIN
			SELECT @FromDate=DATEADD(d,15,DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate)-1,0))
		END
		ELSE
		BEGIN
			SELECT @FromDate=DATEADD(d,15,DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate),0))
		END			
	END
	SET @Todate=@CurrentDate
	--SELECT @FromDate,@Todate
	IF(@ScheduleName='Warning Message - Late Entry' OR @ScheduleName='Warning Message - Early Exit')
	BEGIN
		IF EXISTS(SELECT ESS.Status FROM TA_Tbl_EmailSchedule ES
		INNER JOIN TA_tbl_EmailScheduleStatus ESS on ES.ScheduleId=ESS.ScheduleId
		INNER JOIN TA_Tbl_EmailScheduled_Employees ESE on ESS.ScheduleId=ESE.ScheduleId
		WHERE ESS.ScheduleId=@scheduleID and ESE.Employee_id=@EmployeeID and ESS.Status=1
		and (ESS.DurationFrom between @FromDate and @Todate))
		BEGIN
			SELECT 1 'Sent'
		END
		ELSE
		BEGIN
			SELECT 0 'Sent'
		END
	END
	ELSE
	BEGIN
		SELECT 0 'Sent'
	END	
END

GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "TA_Tbl_ProcessedData"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 322
               Right = 249
            End
            DisplayFlags = 280
            TopColumn = 27
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 3390
         Alias = 2040
         Table = 2580
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'SPMPClientSAPView'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'SPMPClientSAPView'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakFirstInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakFirstInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "SIP"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "FIP"
            Begin Extent = 
               Top = 6
               Left = 246
               Bottom = 125
               Right = 416
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "FT"
            Begin Extent = 
               Top = 6
               Left = 454
               Bottom = 125
               Right = 645
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "ST"
            Begin Extent = 
               Top = 6
               Left = 683
               Bottom = 125
               Right = 874
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunchDifference'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunchDifference'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_LunchInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_LunchInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_ShiftInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_ShiftInPunches'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1[50] 2[25] 3) )"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1[56] 3) )"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 12
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "P"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 239
            End
            DisplayFlags = 280
            TopColumn = 94
         End
         Begin Table = "TA_Tbl_Shift"
            Begin Extent = 
               Top = 138
               Left = 38
               Bottom = 268
               Right = 321
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
      PaneHidden = 
   End
   Begin DataPane = 
      PaneHidden = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      PaneHidden = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'VW_FetchDataFromProcessedData'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'VW_FetchDataFromProcessedData'
GO




/****** Default Script Date: 10/29/2024 15:39:33 ******/

SET IDENTITY_INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ON 
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (1, N'AF', N'Afghanistan', N'Kabul, Afghanistan', N'UTC+04:30', 4, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (2, N'AX', N'Åland Islands', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Åland Islands', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (3, N'AL', N'Albania', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Albania', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (4, N'DZ', N'Algeria', N'West Central Africa, Algeria', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (5, N'AS', N'American Samoa', N'Coordinated Universal Time-11, American Samoa', N'UTC-11:00', -11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (6, N'AD', N'Andorra', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Andorra', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (7, N'AO', N'Angola', N'West Central Africa, Angola', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (8, N'AI', N'Anguilla', N'Georgetown, La Paz, Manaus, San Juan, Anguilla', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (9, N'AQ', N'Antarctica', N'Santiago, Antarctica', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (10, N'AG', N'Antigua and Barbuda', N'Georgetown, La Paz, Manaus, San Juan, Antigua and Barbuda', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (11, N'AR', N'Argentina', N'City of Buenos Aires, Argentina', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (12, N'AM', N'Armenia', N'Yerevan, Armenia', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (13, N'AW', N'Aruba', N'Georgetown, La Paz, Manaus, San Juan, Aruba', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (14, N'AU', N'Australia', N'Canberra, Melbourne, Sydney, Australia', N'UTC+10:00', 10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (15, N'AT', N'Austria', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Austria', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (16, N'AZ', N'Azerbaijan', N'Baku, Azerbaijan', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (17, N'BS', N'Bahamas, The', N'Eastern Time (US & Canada), Bahamas, The', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (18, N'BH', N'Bahrain', N'Kuwait, Riyadh, Bahrain', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (19, N'BD', N'Bangladesh', N'Dhaka, Bangladesh', N'UTC+06:00', 6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (20, N'BB', N'Barbados', N'Georgetown, La Paz, Manaus, San Juan, Barbados', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (21, N'BY', N'Belarus', N'Minsk, Belarus', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (22, N'BE', N'Belgium', N'Brussels, Copenhagen, Madrid, Paris, Belgium', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (23, N'BZ', N'Belize', N'Central America, Belize', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (24, N'BJ', N'Benin', N'West Central Africa, Benin', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (25, N'BM', N'Bermuda', N'Atlantic Time (Canada), Bermuda', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (26, N'BT', N'Bhutan', N'Dhaka, Bhutan', N'UTC+06:00', 6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (27, N'VE', N'Bolivarian Republic of Venezuela', N'Caracas, Bolivarian Republic of Venezuela', N'UTC-04:30', -4, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (28, N'BO', N'Bolivia', N'Georgetown, La Paz, Manaus, San Juan, Bolivia', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (29, N'BQ', N'Bonaire, Sint Eustatius and Saba', N'Georgetown, La Paz, Manaus, San Juan, Bonaire, Sint Eustatius and Saba', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (30, N'BA', N'Bosnia and Herzegovina', N'Sarajevo, Skopje, Warsaw, Zagreb, Bosnia and Herzegovina', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (31, N'BW', N'Botswana', N'Harare, Pretoria, Botswana', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (32, N'BV', N'Bouvet Island', N'Coordinated Universal Time, Bouvet Island', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (33, N'BR', N'Brazil', N'Brasilia, Brazil', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (34, N'IO', N'British Indian Ocean Territory', N'Astana, British Indian Ocean Territory', N'UTC+06:00', 6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (35, N'BN', N'Brunei', N'Kuala Lumpur, Singapore, Brunei', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (36, N'BG', N'Bulgaria', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Bulgaria', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (37, N'BF', N'Burkina Faso', N'Monrovia, Reykjavik, Burkina Faso', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (38, N'BI', N'Burundi', N'Harare, Pretoria, Burundi', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (39, N'CV', N'Cabo Verde', N'Cabo Verde Is., Cabo Verde', N'UTC-01:00', -1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (40, N'KH', N'Cambodia', N'Bangkok, Hanoi, Jakarta, Cambodia', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (41, N'CM', N'Cameroon', N'West Central Africa, Cameroon', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (42, N'CA', N'Canada', N'Eastern Time (US & Canada), Canada', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (43, N'KY', N'Cayman Islands', N'Bogota, Lima, Quito, Rio Branco, Cayman Islands', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (44, N'CF', N'Central African Republic', N'West Central Africa, Central African Republic', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (45, N'TD', N'Chad', N'West Central Africa, Chad', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (46, N'CL', N'Chile', N'Santiago, Chile', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (47, N'CN', N'China', N'Beijing, Chongqing, Hong Kong SAR, Urumqi, China', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (48, N'CX', N'Christmas Island', N'Bangkok, Hanoi, Jakarta, Christmas Island', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (49, N'CC', N'Cocos (Keeling) Islands', N'Yangon (Rangoon), Cocos (Keeling) Islands', N'UTC+06:30', 6, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (50, N'CO', N'Colombia', N'Bogota, Lima, Quito, Rio Branco, Colombia', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (51, N'KM', N'Comoros', N'Nairobi, Comoros', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (52, N'CG', N'Congo', N'West Central Africa, Congo', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (53, N'CD', N'Congo (DRC)', N'West Central Africa, Congo (DRC)', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (54, N'CK', N'Cook Islands', N'Hawaii, Cook Islands', N'UTC-10:00', -10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (55, N'CR', N'Costa Rica', N'Central America, Costa Rica', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (56, N'CI', N'Côte d Ivoire', N'Monrovia, Reykjavik, Côte d Ivoire', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (57, N'HR', N'Croatia', N'Sarajevo, Skopje, Warsaw, Zagreb, Croatia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (58, N'CU', N'Cuba', N'Eastern Time (US & Canada), Cuba', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (59, N'CW', N'Curaçao', N'Georgetown, La Paz, Manaus, San Juan, Curaçao', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (60, N'CY', N'Cyprus', N'E. Europe, Cyprus', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (61, N'CZ', N'Czech Republic', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Czech Republic', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (62, N'TL', N'Democratic Republic of Timor-Leste', N'Osaka, Sapporo, Tokyo, Democratic Republic of Timor-Leste', N'UTC+09:00', 9, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (63, N'DK', N'Denmark', N'Brussels, Copenhagen, Madrid, Paris, Denmark', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (64, N'DJ', N'Djibouti', N'Nairobi, Djibouti', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (65, N'DM', N'Dominica', N'Georgetown, La Paz, Manaus, San Juan, Dominica', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (66, N'DO', N'Dominican Republic', N'Georgetown, La Paz, Manaus, San Juan, Dominican Republic', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (67, N'EC', N'Ecuador', N'Bogota, Lima, Quito, Rio Branco, Ecuador', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (68, N'EG', N'Egypt', N'Cairo, Egypt', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (69, N'SV', N'El Salvador', N'Central America, El Salvador', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (70, N'GQ', N'Equatorial Guinea', N'West Central Africa, Equatorial Guinea', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (71, N'ER', N'Eritrea', N'Nairobi, Eritrea', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (72, N'EE', N'Estonia', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Estonia', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (73, N'ET', N'Ethiopia', N'Nairobi, Ethiopia', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (74, N'FK', N'Falkland Islands', N'Cayenne, Fortaleza, Falkland Islands', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (75, N'FO', N'Faroe Islands', N'Dublin, Edinburgh, Lisbon, London, Faroe Islands', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (76, N'FJ', N'Fiji Islands', N'Fiji, Fiji Islands', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (77, N'FI', N'Finland', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Finland', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (78, N'FR', N'France', N'Brussels, Copenhagen, Madrid, Paris, France', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (79, N'GF', N'French Guiana', N'Cayenne, Fortaleza, French Guiana', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (80, N'PF', N'French Polynesia', N'Hawaii, French Polynesia', N'UTC-10:00', -10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (81, N'TF', N'French Southern and Antarctic Lands', N'Ashgabat, Tashkent, French Southern and Antarctic Lands', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (82, N'GA', N'Gabon', N'West Central Africa, Gabon', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (83, N'GM', N'Gambia, The', N'Monrovia, Reykjavik, Gambia, The', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (84, N'GE', N'Georgia', N'Tbilisi, Georgia', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (85, N'DE', N'Germany', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Germany', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (86, N'GH', N'Ghana', N'Monrovia, Reykjavik, Ghana', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (87, N'GI', N'Gibraltar', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Gibraltar', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (88, N'GR', N'Greece', N'Athens, Bucharest, Greece', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (89, N'GL', N'Greenland', N'Greenland, Greenland', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (90, N'GD', N'Grenada', N'Georgetown, La Paz, Manaus, San Juan, Grenada', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (91, N'GP', N'Guadeloupe', N'Georgetown, La Paz, Manaus, San Juan, Guadeloupe', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (92, N'GU', N'Guam', N'Guam, Port Moresby, Guam', N'UTC+10:00', 10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (93, N'GT', N'Guatemala', N'Central America, Guatemala', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (94, N'GG', N'Guernsey', N'Dublin, Edinburgh, Lisbon, London, Guernsey', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (95, N'GN', N'Guinea', N'Monrovia, Reykjavik, Guinea', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (96, N'GW', N'Guinea-Bissau', N'Monrovia, Reykjavik, Guinea-Bissau', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (97, N'GY', N'Guyana', N'Georgetown, La Paz, Manaus, San Juan, Guyana', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (98, N'HT', N'Haiti', N'Eastern Time (US & Canada), Haiti', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (99, N'HM', N'Heard Island and McDonald Islands', N'Port Louis, Heard Island and McDonald Islands', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (100, N'HN', N'Honduras', N'Central America, Honduras', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (101, N'HK', N'Hong Kong SAR', N'Beijing, Chongqing, Hong Kong SAR, Urumqi, Hong Kong SAR', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (102, N'HU', N'Hungary', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Hungary', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (103, N'IS', N'Iceland', N'Monrovia, Reykjavik, Iceland', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (104, N'IN', N'India', N'Chennai, Kolkata, Mumbai, New Delhi, India', N'UTC+05:30', 5, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (105, N'ID', N'Indonesia', N'Bangkok, Hanoi, Jakarta, Indonesia', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (106, N'IR', N'Iran', N'Tehran, Iran', N'UTC+03:30', 3, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (107, N'IQ', N'Iraq', N'Baghdad, Iraq', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (108, N'IE', N'Ireland', N'Dublin, Edinburgh, Lisbon, London, Ireland', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (109, N'IL', N'Israel', N'Middle East, Israel', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (110, N'IT', N'Italy', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Italy', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (111, N'JM', N'Jamaica', N'Bogota, Lima, Quito, Rio Branco, Jamaica', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (112, N'SJ', N'Jan Mayen', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Jan Mayen', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (113, N'JP', N'Japan', N'Osaka, Sapporo, Tokyo, Japan', N'UTC+09:00', 9, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (114, N'JE', N'Jersey', N'Dublin, Edinburgh, Lisbon, London, Jersey', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (115, N'JO', N'Jordan', N'Amman, Jordan', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (116, N'KZ', N'Kazakhstan', N'Astana, Kazakhstan', N'UTC+06:00', 6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (117, N'KE', N'Kenya', N'Nairobi, Kenya', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (118, N'KI', N'Kiribati', N'Coordinated Universal Time+12, Kiribati', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (119, N'KR', N'Korea', N'Seoul, Korea', N'UTC+09:00', 9, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (120, N'XK', N'Kosovo', N'Sarajevo, Skopje, Warsaw, Zagreb, Kosovo', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (121, N'KW', N'Kuwait', N'Kuwait, Riyadh, Kuwait', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (122, N'KG', N'Kyrgyzstan', N'Astana, Kyrgyzstan', N'UTC+06:00', 6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (123, N'LA', N'Laos', N'Bangkok, Hanoi, Jakarta, Laos', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (124, N'LV', N'Latvia', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Latvia', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (125, N'LB', N'Lebanon', N'Beirut, Lebanon', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (126, N'LS', N'Lesotho', N'Harare, Pretoria, Lesotho', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (127, N'LR', N'Liberia', N'Monrovia, Reykjavik, Liberia', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (128, N'LY', N'Libya', N'E. Europe, Libya', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (129, N'LI', N'Liechtenstein', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Liechtenstein', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (130, N'LT', N'Lithuania', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Lithuania', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (131, N'LU', N'Luxembourg', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Luxembourg', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (132, N'MO', N'Macao SAR', N'Beijing, Chongqing, Hong Kong SAR, Urumqi, Macao SAR', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (133, N'MK', N'Republic of North Macedonia', N'Sarajevo, Skopje, Warsaw, Zagreb, Republic of North Macedonia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (134, N'MG', N'Madagascar', N'Nairobi, Madagascar', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (135, N'MW', N'Malawi', N'Harare, Pretoria, Malawi', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (136, N'MY', N'Malaysia', N'Kuala Lumpur, Singapore, Malaysia', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (137, N'MV', N'Maldives', N'Ashgabat, Tashkent, Maldives', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (138, N'ML', N'Mali', N'Monrovia, Reykjavik, Mali', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (139, N'MT', N'Malta', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Malta', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (140, N'IM', N'Man, Isle of', N'Dublin, Edinburgh, Lisbon, London, Man, Isle of', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (141, N'MH', N'Marshall Islands', N'Coordinated Universal Time+12, Marshall Islands', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (142, N'MQ', N'Martinique', N'Georgetown, La Paz, Manaus, San Juan, Martinique', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (143, N'MR', N'Mauritania', N'Monrovia, Reykjavik, Mauritania', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (144, N'MU', N'Mauritius', N'Port Louis, Mauritius', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (145, N'YT', N'Mayotte', N'Nairobi, Mayotte', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (146, N'MX', N'Mexico', N'Guadalajara, Mexico City, Monterrey, Mexico', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (147, N'FM', N'Micronesia', N'Guam, Port Moresby, Micronesia', N'UTC+10:00', 10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (148, N'MD', N'Moldova', N'Athens, Bucharest, Moldova', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (149, N'MC', N'Monaco', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Monaco', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (150, N'MN', N'Mongolia', N'Ulaanbaatar, Mongolia', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (151, N'ME', N'Montenegro', N'Sarajevo, Skopje, Warsaw, Zagreb, Montenegro', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (152, N'MS', N'Montserrat', N'Georgetown, La Paz, Manaus, San Juan, Montserrat', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (153, N'MA', N'Morocco', N'Casablanca, Morocco', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (154, N'MZ', N'Mozambique', N'Harare, Pretoria, Mozambique', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (155, N'MM', N'Myanmar', N'Yangon (Rangoon), Myanmar', N'UTC+06:30', 6, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (156, N'NA', N'Namibia', N'Windhoek, Namibia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (157, N'NR', N'Nauru', N'Coordinated Universal Time+12, Nauru', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (158, N'NP', N'Nepal', N'Kathmandu, Nepal', N'UTC+05:45', 5, 45, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (159, N'NL', N'Netherlands', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Netherlands', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (160, N'NC', N'New Caledonia', N'Solomon Is., New Caledonia, New Caledonia', N'UTC+11:00', 11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (161, N'NZ', N'New Zealand', N'Auckland, Wellington, New Zealand', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (162, N'NI', N'Nicaragua', N'Central America, Nicaragua', N'UTC-06:00', -6, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (163, N'NE', N'Niger', N'West Central Africa, Niger', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (164, N'NG', N'Nigeria', N'West Central Africa, Nigeria', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (165, N'NU', N'Niue', N'Coordinated Universal Time-11, Niue', N'UTC-11:00', -11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (166, N'NF', N'Norfolk Island', N'Solomon Is., New Caledonia, Norfolk Island', N'UTC+11:00', 11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (167, N'KP', N'North Korea', N'Seoul, North Korea', N'UTC+09:00', 9, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (168, N'MP', N'Northern Mariana Islands', N'Guam, Port Moresby, Northern Mariana Islands', N'UTC+10:00', 10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (169, N'NO', N'Norway', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Norway', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (170, N'OM', N'Oman', N'Abu Dhabi, Muscat, Oman', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (171, N'PK', N'Pakistan', N'Islamabad, Karachi, Pakistan', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (172, N'PW', N'Palau', N'Osaka, Sapporo, Tokyo, Palau', N'UTC+09:00', 9, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (173, N'PS', N'Palestinian Authority', N'Cairo, Palestinian Authority', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (174, N'PA', N'Panama', N'Bogota, Lima, Quito, Rio Branco, Panama', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (175, N'PG', N'Papua New Guinea', N'Guam, Port Moresby, Papua New Guinea', N'UTC+10:00', 10, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (176, N'PY', N'Paraguay', N'Asuncion, Paraguay', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (177, N'PE', N'Peru', N'Bogota, Lima, Quito, Rio Branco, Peru', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (178, N'PH', N'Philippines', N'Kuala Lumpur, Singapore, Philippines', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (179, N'PN', N'Pitcairn Islands', N'Pacific Time (US & Canada), Pitcairn Islands', N'UTC-08:00', -8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (180, N'PL', N'Poland', N'Sarajevo, Skopje, Warsaw, Zagreb, Poland', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (181, N'PT', N'Portugal', N'Dublin, Edinburgh, Lisbon, London, Portugal', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (182, N'PR', N'Puerto Rico', N'Georgetown, La Paz, Manaus, San Juan, Puerto Rico', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (183, N'QA', N'Qatar', N'Kuwait, Riyadh, Qatar', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (184, N'RE', N'Reunion', N'Port Louis, Reunion', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (185, N'RO', N'Romania', N'Athens, Bucharest, Romania', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (186, N'RU', N'Russia', N'Moscow, St. Petersburg, Volgograd (RTZ 2), Russia', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (187, N'RW', N'Rwanda', N'Harare, Pretoria, Rwanda', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (188, N'BL', N'Saint Barthélemy', N'Georgetown, La Paz, Manaus, San Juan, Saint Barthélemy', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (189, N'SH', N'Saint Helena, Ascension and Tristan da Cunha', N'Monrovia, Reykjavik, Saint Helena, Ascension and Tristan da Cunha', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (190, N'KN', N'Saint Kitts and Nevis', N'Georgetown, La Paz, Manaus, San Juan, Saint Kitts and Nevis', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (191, N'LC', N'Saint Lucia', N'Georgetown, La Paz, Manaus, San Juan, Saint Lucia', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (192, N'MF', N'Saint Martin (French part)', N'Georgetown, La Paz, Manaus, San Juan, Saint Martin (French part)', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (193, N'PM', N'Saint Pierre and Miquelon', N'Greenland, Saint Pierre and Miquelon', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (194, N'VC', N'Saint Vincent and the Grenadines', N'Georgetown, La Paz, Manaus, San Juan, Saint Vincent and the Grenadines', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (195, N'WS', N'Samoa', N'Samoa, Samoa', N'UTC+13:00', 13, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (196, N'SM', N'San Marino', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, San Marino', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (197, N'ST', N'São Tomé and Príncipe', N'Monrovia, Reykjavik, São Tomé and Príncipe', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (198, N'SA', N'Saudi Arabia', N'Kuwait, Riyadh, Saudi Arabia', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (199, N'SN', N'Senegal', N'Monrovia, Reykjavik, Senegal', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (200, N'RS', N'Serbia', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Serbia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (201, N'SC', N'Seychelles', N'Port Louis, Seychelles', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (202, N'SL', N'Sierra Leone', N'Monrovia, Reykjavik, Sierra Leone', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (203, N'SG', N'Singapore', N'Kuala Lumpur, Singapore, Singapore', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (204, N'SX', N'Sint Maarten (Dutch part)', N'Georgetown, La Paz, Manaus, San Juan, Sint Maarten (Dutch part)', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (205, N'SK', N'Slovakia', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Slovakia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (206, N'SI', N'Slovenia', N'Belgrade, Bratislava, Budapest, Ljubljana, Prague, Slovenia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (207, N'SB', N'Solomon Islands', N'Solomon Is., New Caledonia, Solomon Islands', N'UTC+11:00', 11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (208, N'SO', N'Somalia', N'Nairobi, Somalia', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (209, N'ZA', N'South Africa', N'Harare, Pretoria, South Africa', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (210, N'GS', N'South Georgia and the South Sandwich Islands', N'Coordinated Universal Time-02, South Georgia and the South Sandwich Islands', N'UTC-02:00', -2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (211, N'SS', N'South Sudan', N'Nairobi, South Sudan', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (212, N'ES', N'Spain', N'Brussels, Copenhagen, Madrid, Paris, Spain', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (213, N'LK', N'Sri Lanka', N'Sri Jayawardenepura, Sri Lanka', N'UTC+05:30', 5, 30, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (214, N'SD', N'Sudan', N'Nairobi, Sudan', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (215, N'SR', N'Suriname', N'Cayenne, Fortaleza, Suriname', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (216, N'SJ', N'Svalbard', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Svalbard', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (217, N'SZ', N'Swaziland', N'Harare, Pretoria, Swaziland', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (218, N'SE', N'Sweden', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Sweden', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (219, N'CH', N'Switzerland', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Switzerland', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (220, N'SY', N'Syria', N'Damascus, Syria', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (221, N'TW', N'Taiwan', N'Taipei, Taiwan', N'UTC+08:00', 8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (222, N'TJ', N'Tajikistan', N'Ashgabat, Tashkent, Tajikistan', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (223, N'TZ', N'Tanzania', N'Nairobi, Tanzania', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (224, N'TH', N'Thailand', N'Bangkok, Hanoi, Jakarta, Thailand', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (225, N'TG', N'Togo', N'Monrovia, Reykjavik, Togo', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (226, N'TK', N'Tokelau', N'Nuku alofa, Tokelau', N'UTC+13:00', 13, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (227, N'TO', N'Tonga', N'Nuku alofa, Tonga', N'UTC+13:00', 13, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (228, N'TT', N'Trinidad and Tobago', N'Georgetown, La Paz, Manaus, San Juan, Trinidad and Tobago', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (229, N'TN', N'Tunisia', N'West Central Africa, Tunisia', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (230, N'TR', N'Türkiye', N'Istanbul, Türkiye', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (231, N'TM', N'Turkmenistan', N'Ashgabat, Tashkent, Turkmenistan', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (232, N'TC', N'Turks and Caicos Islands', N'Eastern Time (US & Canada), Turks and Caicos Islands', N'UTC-05:00', -5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (233, N'TV', N'Tuvalu', N'Coordinated Universal Time+12, Tuvalu', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (234, N'UM', N'U.S. Minor Outlying Islands', N'Coordinated Universal Time-11, U.S. Minor Outlying Islands', N'UTC-11:00', -11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (235, N'UG', N'Uganda', N'Nairobi, Uganda', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (236, N'UA', N'Ukraine', N'Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius, Ukraine', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (237, N'AE', N'United Arab Emirates', N'Abu Dhabi, Muscat, United Arab Emirates', N'UTC+04:00', 4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (238, N'GB', N'United Kingdom', N'Dublin, Edinburgh, Lisbon, London, United Kingdom', N'UTC', 0, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (239, N'US', N'United States', N'Mountain Time (US & Canada), United States', N'UTC-07:00', -7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (240, N'US', N'United States', N'Pacific Time (US & Canada), United States', N'UTC-08:00', -8, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (241, N'UY', N'Uruguay', N'Montevideo, Uruguay', N'UTC-03:00', -3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (242, N'UZ', N'Uzbekistan', N'Ashgabat, Tashkent, Uzbekistan', N'UTC+05:00', 5, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (243, N'VU', N'Vanuatu', N'Solomon Is., New Caledonia, Vanuatu', N'UTC+11:00', 11, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (244, N'VA', N'Vatican City', N'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna, Vatican City', N'UTC+01:00', 1, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (245, N'VN', N'Vietnam', N'Bangkok, Hanoi, Jakarta, Vietnam', N'UTC+07:00', 7, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (246, N'VI', N'Virgin Islands, U.S.', N'Georgetown, La Paz, Manaus, San Juan, Virgin Islands, U.S.', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (247, N'VG', N'Virgin Islands, British', N'Georgetown, La Paz, Manaus, San Juan, Virgin Islands, British', N'UTC-04:00', -4, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (248, N'WF', N'Wallis and Futuna', N'Coordinated Universal Time+12, Wallis and Futuna', N'UTC+12:00', 12, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (249, N'YE', N'Yemen', N'Kuwait, Riyadh, Yemen', N'UTC+03:00', 3, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (250, N'ZM', N'Zambia', N'Harare, Pretoria, Zambia', N'UTC+02:00', 2, 0, NULL)
GO
INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] ([TimezoneID], [CountryCode], [TimezoneName], [TimezoneDesc], [TimeZoneValue], [HoursToBeAdded], [MinToBeAdded], [ServerDefault]) VALUES (251, N'ZW', N'Zimbabwe', N'Harare, Pretoria, Zimbabwe', N'UTC+02:00', 2, 0, NULL)
GO
SET IDENTITY_INSERT [dbo].[TA_Tbl_UTCTimeZonesCountryDetails] OFF
GO






SET IDENTITY_INSERT [dbo].[TA_Tbl_TerminalBrand] ON
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (1, CONVERT(TEXT, N'Hanvon Face Recognition'), CONVERT(TEXT, N'Hanvon'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (2, CONVERT(TEXT, N'Others'), CONVERT(TEXT, N'Others'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (3, CONVERT(TEXT, N'Suprema'), CONVERT(TEXT, N'Suprema'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (4, CONVERT(TEXT, N'Suprema-Biostar 2'), CONVERT(TEXT, N'Suprema-Biostar 2'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (5, CONVERT(TEXT, N'ESSL'), CONVERT(TEXT, N'ESSL'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (6, CONVERT(TEXT, N'ZK Teco'), CONVERT(TEXT, N'ZK Teco'))
SET IDENTITY_INSERT [dbo].[TA_Tbl_TerminalBrand] OFF
Go
--Page Table
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (194, N'Menu_Configuration', N'', 0, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (189, N'Organization_Settings', N'', 0, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (187, N'Device_Management', N'', 0, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (204, N'Menu_EMp_Master', N'', 188, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (190, N'Privilege_Management', N'', 0, 13, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (188, N'Employee_Management', N'', 0, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (235, N'Shift_Management', N'', 0, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (236, N'Leave_Permission_Management', N'', 0, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (237, N'ManualTimeEntry', N'', 0, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (192, N'Menu_Reports', N'', 0, 11, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (193, N'Other_useful_features', N'', 0, 14, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (230, N'Menu_Vehicle', N'Masters/TA_UI_MasterTransportationVehicleList.aspx', 12, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (195, N'Menu_LeaveType', N'Masters/TA_UI_MasterLeaveTypeList.aspx', 209, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (177, N'Masters_EmailConfiguration', N'Masters/TA_UI_EmailScheduleList.aspx', 0, 12, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (209, N'Menu_Leave_Master', N'', 236, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (196, N'Menu_LeavePolicy', N'Masters/TA_UI_MasterLeavePolicyList.aspx', 209, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (205, N'Menu_EMp_Report', N'', 188, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (197, N'Menu_LicenseRequistion', N'System Settings/SystemSetting_LicenseRequest.aspx', 107, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (198, N'Menu_Licenseupdater', N'System Settings/SystemSetting_LicenseUpdater.aspx', 107, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (199, N'Menu_LicenseInfo', N'System Settings/SystemSetting_ViewLicenseInfo.aspx', 107, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (231, N'Menu_Route', N'Masters/TA_UI_MasterTransportationRouteList.aspx', 12, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (202, N'ShiftAllocationExport', N'Transactions/TA_UI_Transaction_ShiftExport.aspx', 207, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (203, N'DataReprocessing', N'Transactions/TA_UI_Transaction_DataReprocessing.aspx', 207, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (206, N'Menu_Shift_Master', N'', 235, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (207, N'Menu_Shift_Transaction', N'', 235, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (208, N'Menu_Shift_Reports', N'', 235, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (210, N'Menu_Leave_Transaction', N'', 236, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (211, N'Menu_Leave_Reports', N'', 236, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (212, N'Menu_ME_Transaction', N'', 237, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (213, N'Menu_ME_Reports', N'', 237, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (214, N'Menu_OTCOMPOff', N'', 0, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (215, N'Menu_OnDuty', N'', 0, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (216, N'Menu_Permission_Transaction', N'', 236, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (218, N'Menu_ED_Transaction', N'', 217, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (217, N'Menu_ExportData', N'', 0, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (219, N'Menu_ED_Reports', N'', 217, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (220, N'Menu_ME_Import', N'Transactions/TA_UI_Transactions_ManualEntryImport.aspx', 212, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (221, N'Menu_ME_Export', N'Transactions/TA_UI_Transactions_ManualEntryExport.aspx', 212, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (222, N'Menu_ME_Discrepancy', N'Transactions/TA_UI_Transactions_DiscrepancyList.aspx', 212, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (223, N'Menu_TerminalDB', N'Masters/TA_UI_Master_TerminalDatatype.aspx', 10, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (224, N'Menu_TerminalMaster', N'Masters/TA_UI_Master_Terminal.aspx', 10, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (225, N'Menu_Country', N'Masters/TA_UI_Master_CountryList.aspx', 204, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (226, N'Menu_State', N'Masters/TA_UI_Master_StateList.aspx', 204, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (227, N'Menu_City', N'Masters/TA_UI_Master_CityList.aspx', 204, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (228, N'Menu_Grade', N'Masters/TA_UI_Master_GradeList.aspx', 204, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (229, N'Menu_Region', N'Masters/TA_UI_Master_ReligionList.aspx', 204, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (232, N'Menu_Dev_EmpDetails', N'Reports/TA_UI_XGReportEmployeeDetail.aspx', 147, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (233, N'Menu_Dev_Attendance', N'Reports/TA_UI_XGReportAttendance.aspx', 147, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (234, N'Menu_Dev_AllSwipes', N'Reports/TA_UI_XGReportMovementsEntry.aspx', 147, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (179, N'Menu_Master_Dashboard', N'DashBoard.aspx', 0, 0, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (6, N'Master_Organization', N'Masters/TA_UI_Master_OrganisationLevels.aspx', 189, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (10, N'Master_Terminal', N'', 187, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (15, N'Master_Entrance', N'Masters/TA_UI_Master_Entrance.aspx', 187, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (68, N'Master_Punch', N'Masters/TA_UI_Master_PunchTypes_List.aspx', 187, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (17, N'Master_Designation', N'Masters/TA_UI_Master_TitleFirstList.aspx', 204, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (94, N'Master_Category', N'Masters/TA_UI_Master_EmployeeCategoryList.aspx', 204, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (95, N'Master_Type', N'Masters/TA_UI_Master_EmployeeTypeList.aspx', 204, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (18, N'Master_Employee', N'Masters/TA_UI_Master_Employee.aspx', 204, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (19, N'Master_Shift', N'Masters/TA_UI_Master_ShiftDetails.aspx', 206, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (20, N'Master_Shift_Pattern', N'Masters/TA_UI_Master_ShiftPattern.aspx', 206, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (69, N'Master_Shift_Roster', N'Masters/TA_UI_Master_ShiftRoaster.aspx', 206, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (16, N'Master_Holidays', N'Masters/TA_UI_Master_Holiday.aspx', 194, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (99, N'Master_AttandanceCode', N'Masters/TA_UI_Master_AttandanceCode.aspx', 193, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (100, N'Master_OverTimeType', N'Masters/TA_UI_Master_OverTimeType.aspx', 193, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (12, N'Master_Transportation', N'', 193, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (21, N'Master_User_Groups', N'Masters/TA_UI_Master_groupView.aspx', 190, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (26, N'Transcation_Manual_Time', N'Transactions/TA_UI_Transactions_ManualTimeEntry.aspx', 212, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (98, N'Transcation_ManualTimeEntry_Approval', N'Transactions/TA_UI_Transactions_ManualTimeEntrySanction.aspx', 212, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (22, N'Transaction_Leave_Application', N'Transactions/TA_UI_Transactions_LeaveApplication.aspx', 210, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (173, N'Transaction_OnDuty', N'Transactions/TA_UI_Transactions_OnDutyList.aspx', 215, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (108, N'Transaction_LeavePolicyAllocation', N'Transactions/TA_UI_Transactions_GroupLeavePolicy.aspx', 210, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (96, N'Transaction_BonusLeave', N'Transactions/TA_UI_Transactions_BonusLeaveAllocation.aspx', 210, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (23, N'Transaction_Permission', N'Transactions/TA_UI_Transactions_LeavePermission.aspx', 216, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (248, N'Transaction_Approvals', N'Transactions/TA_UI_Transaction_Sanctions.aspx', 236, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (28, N'Transaction_Shift_Allocation', N'Transactions/TA_UI_Transaction_ShiftAllocation.aspx', 207, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (29, N'Tranaction_Temporary_Shift', N'Transactions/TA_UI_Transaction_TemporaryShiftAllocationadd.aspx', 207, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (60, N'Transaction_Shift_Exchange', N'Transactions/TA_UI_Transaction_ShiftExchangeList.aspx', 207, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (116, N'Caption_ShiftReAllocation', N'Transactions/TA_UI_Transactions_ShiftReAllocation.aspx', 207, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (97, N'Transaction_OverTime_Sanction', N'Transactions/TA_UI_Transactions_OverTimeSanction.aspx', 214, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (102, N'Transaction_SwipesHandling', N'Transactions/TA_UI_Transactions_SwipesHandlingList.aspx', 212, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (27, N'Transcation_Payroll', N'Transactions/TA_UI_Transactions_MonthClosure.aspx', 218, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (62, N'Transaction_Year_Closure', N'Transactions/TA_UI_Transactions_YearClosureAdd.aspx', 218, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (76, N'Transaction_Encashment', N'Transactions/TA_UI_Transaction_Encashment.aspx', 210, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (144, N'Menu_Report_Attendace', N'', 192, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (180, N'Report_GeneralMonthly_Attendance', N'Reports/TA_UI_Report_GeneralMonthlyAttendance.aspx', 144, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (41, N'Report_All_Swipes', N'Reports/TA_UI_Report_MovementsEntry.aspx', 144, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (40, N'Report_Monthly_Attendance', N'Reports/TA_UI_Report_MonthlyAttendance.aspx', 144, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (30, N'Report_Detailed_Attendance', N'Reports/TA_UI_Report_DetailAttendance.aspx', 144, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (105, N'MustoRollReport', N'Reports/TA_UI_report_EmployeeInOut.aspx', 144, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (118, N'Report_SummaryReport', N'Reports/TA_UI_Report_Summary.aspx', 144, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (45, N'Report_Total_Days', N'Reports/TA_UI_Report_TotalDays.aspx', 144, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (39, N'Report_Punctuality', N'Reports/TA_UI_Report_Punctuality.aspx', 144, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (92, N'Report_ManualTimeEntry', N'Reports/TA_UI_Report_ManualTimeEntry.aspx', 213, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (175, N'Report_OnDutyEntry', N'Reports/TA_UI_Report_OnDutyEntry.aspx', 215, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (145, N'Menu_Reports_Entries', N'', 192, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (34, N'Report_Absent', N'Reports/TA_UI_Report_Absentes.aspx', 145, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (33, N'Report_Discrepancy', N'Reports/TA_UI_Report_Discrepancy.aspx', 213, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (37, N'Report_Late_Entry', N'Reports/TA_UI_Report_LateInstance.aspx', 145, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (127, N'Report_LessHoursWorked', N'Reports/TA_UI_Report_LessHoursWorked.aspx', 145, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (147, N'Menu_Reports_Shifts', N'', 192, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (44, N'Report_Shift', N'Reports/TA_UI_Report_Shift.aspx', 208, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (32, N'Report_Employee_Shift_Allocation', N'Reports/TA_UI_Report_EmployeeShiftAllocation.aspx', 208, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (36, N'Report_Overtime', N'Reports/TA_UI_Report_OverTime.aspx', 214, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (35, N'Report_Leave', N'Reports/TA_UI_Report_LeaveApplication.aspx', 211, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (117, N'Report_LeavePolicyNotAllocated', N'Reports/TA_UI_Report_LeavePolicyNotAllocated.aspx', 211, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (183, N'Report_RawData', N'Reports/TA_UI_Report_RawData.aspx', 144, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (89, N'Report_Permission', N'Reports/TA_UI_Report_Permission.aspx', 236, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (42, N'Report_Employee_Details', N'Reports/TA_UI_Report_Employee.aspx', 205, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (84, N'Report_EmployeeHistory', N'Reports/TA_UI_Report_EmployeeHistory.aspx', 205, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (71, N'Report_Payroll', N'Reports/TA_UI_Report_PayRoll.aspx', 219, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (70, N'Report_Year_Closure', N'Reports/TA_UI_Report_YearClosure.aspx', 219, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (79, N'Report_Audit_Trail', N'Reports/TA_UI_Report_AuditTrail.aspx', 147, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (43, N'Report_Document_Expiry', N'Reports/TA_UI_Report_DocumentExpiry.aspx', 147, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (160, N'Report_WeeklyWorkHours', N'Reports/TA_UI_Report_WeeklyWorkHours.aspx', 147, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (171, N'Report_CountFactor_WorkingDays', N'Reports/TA_UI_Report_TotalWorkingDays.aspx', 147, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (47, N'Org_Level_Settings', N'Organization Settings/Organization_levels.aspx', 189, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (51, N'Org_Shift_Settings', N'Organization Settings/Organization_shiftSetting.aspx', 194, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (52, N'Org_Holiday_Setting', N'Organization Settings/Organization_HolidaySetting.aspx', 194, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (50, N'Org_Year_Setting', N'Organization Settings/Organization_YearSetting.aspx', 194, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (103, N'Flexi_Settings_Menu', N'Organization Settings/Organization_EmployeeFlexiEligible.aspx', 204, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (48, N'Org_Temporary_Weekday', N'Organization Settings/Organization_Tempweekdaylist.aspx', 193, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (49, N'Org_Additional_Weeklyoff', N'Organization Settings/Organization_AddlWeekoff.aspx', 193, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (72, N'Org_Login_List', N'Organization Settings/LoginList.aspx', 193, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (53, N'Org_News', N'Organization Settings/Organization_NewsView.aspx', 193, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (54, N'System_Change_Password', N'System Settings/System_ChangePassword.aspx', 190, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (55, N'System_Reset_Password', N'System Settings/System_ResetPassword.aspx', 190, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (104, N'Import_Data', N'System Settings/importEmployee.aspx', 204, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (66, N'System_Export_Data', N'System Settings/ExportData.aspx', 218, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (78, N'System_Audit_Trail', N'System Settings/System_AuditTrail.aspx', 193, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (75, N'System_MultiLingual', N'System Settings/System_Multilingual.aspx', 194, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (107, N'System_LicenseManager', N'', 193, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (109, N'System_DatabaseInformation', N'System Settings/SystemSetting_DatabaseInformation.aspx', 193, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu])  VALUES (246, N'Menu_Master_MyCalendar', N'MyCalendar.aspx', 0, 0.1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu])  VALUES (254, N'Menu_CompOffCreditEntry', N'Transactions/TA_UI_Transactions_ManualCompensationEntry.aspx', 214, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (255, N'NearestShiftAllocation', N'Transactions/TA_UI_Transaction_NearestShiftAllocation.aspx', 207, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (249, N'Menu_help', N'Help/Help.aspx', 0, 15, NULL)
--User Group Table
INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N'SuperAdmin', 0, NULL, GETDATE(), 0, NULL)
INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N'IndividualUsers', 1, 0, GETDATE(), 0, N'1')
--User Rights Table
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 144, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 145, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 147, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 19, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 20, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 69, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 28, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 29, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 60, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 76, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 116, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 44, 208, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 32, 208, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 22, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 23, 216, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 248, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 27, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 62, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 96, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 108, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 35, 211, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 89, 236, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 117, 211, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 26, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 97, 214, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 98, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 102, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 92, 213, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 173, 215, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 175, 215, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 10, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 15, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 68, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 17, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 18, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 94, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 95, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 42, 205, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 84, 205, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 103, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 6, 189, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 12, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 99, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 100, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 197, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 47, 189, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 48, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 49, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 50, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 51, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 53, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 72, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 21, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 30, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 36, 214, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 39, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 41, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 40, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 45, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 105, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 118, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 43, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 79, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 71, 219, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 70, 219, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 16, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 52, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 37, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 34, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 33, 213, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 127, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 198, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 66, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 75, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 67, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 77, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 106, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 109, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 54, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 55, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 104, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 107, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 78, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 160, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 171, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 216, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 180, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 183, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 199, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 195, 209, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 196, 209, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 232, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 204, 188, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 205, 188, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 206, 235, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 207, 235, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 208, 235, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 209, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 210, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 211, 236, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 212, 237, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 213, 237, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 218, 217, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 219, 217, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 201, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 202, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 203, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 220, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 221, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 222, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 223, 10, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 224, 10, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 225, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 226, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 227, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 228, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 229, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 230, 12, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 231, 12, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 233, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 234, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 179, 179, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 177, 177, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 243, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 244, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 245, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 246, 246, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 254, 214, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 255, 207, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin',1,249,249,1,1,1,1,1,GETDATE(),1)
--Employee Table
INSERT  INTO [dbo].[TA_Tbl_Employee] ([UserGroup_Id], [ShiftPattern_Id], [Bus_Id], [Employee_FirstName], [Employee_MiddleName], [Employee_LastName], [Father_name], [Mother_name], [DateofBirth], [DateofBirth_Record], [Blood_Group], [EmailId], [Contact_Address], [Permanent_Address], [Phone_Number], [Mobile_Number], [Gender], [Marital_status], [Nationality], [Religion], [Photo], [Personal_mailid], [Passport_No], [Passport_expirydate], [Visa_No], [Visa_expirydate], [Vehicle_Type], [Vehicle_No], [Anniversary_Date], [Native_Place], [District], [State], [Country], [Spouse_No], [Children_No], [Employee_Code_Id], [DateOfJoining], [Reporting_To], [Leave_Sanc_Authority], [Prev_Experience], [UserName], [Emp_password], [Qual_JoiningTime], [Qual_Employment], [OutDoorJob], [CompOff_Eligible], [OT_Eligible], [ESI_Eligible], [PF_Eligible], [Report_Exclude], [Employee_Status], [SwipeCardNo], [Time_Stamp], [Emp_ID], [Isdeleted], [Hostel], [IsComplete], [IsFlexible], [InActiveDate], [CustomField1], [CustomField2], [CustomField3], [CustomField4], [CustomField5], [Isdeleted_Status], [InActive_Status], [IsImported]) VALUES (1, NULL, NULL, N'Administrator', N'', N'', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, N'18000000', NULL, NULL, NULL, NULL, N'Admin', N'QL5OWbmiorXf+5GMDoaz1w==', NULL, NULL, 0, 1, 1, 0, 0, 1, 1, N'18000000', GETDATE(), NULL, 0, NULL, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0)
--Language Table
INSERT  INTO [dbo].[TA_Tbl_MultiLingual] ([Language_Name], [Resource_File_Name], [IsActive]) VALUES ( N'English', N'Resource_EN', 1)
INSERT  INTO [dbo].[TA_Tbl_MultiLingual] ([Language_Name], [Resource_File_Name], [IsActive]) VALUES ( N'Arabic', N'Resource_AR', 0)
INSERT  INTO [dbo].[TA_Tbl_DateandTimeFormat] ([DateFormat], [TimeFormat], [Time_Stamp], [Emp_Id],[isDomain]) VALUES (N'MM/dd/yyyy', N'hh:mm tt', GETDATE(), 1,1)
INSERT  INTO [dbo].[TA_Tbl_Version] ([DatabaseVersionNo], [DatabaseVersionName], [ApplicationVersionNo], [ApplicationVersionName], [DatabaseVersionDate], [ApplicationVersionDate]) VALUES (1, N'TimeCheck_DB_V3.10', 1, N'TimeCheck_AP_V3.10', GETDATE(), GETDATE())
INSERT  INTO [dbo].[TA_Tbl_Shift] ([Level_Id], [Shift_Name], [Shift_ShortName], [Shift_Description], [Shift_StartTime], [Shift_EndTime], [Shift_FirstHalf_StartTime], [Shift_FirstHalf_EndTime], [Shift_SecondHalf_StartTime], [Shift_SecondHalf_EndTime], [Shift_GraceInTime], [Shift_GraceOutTime], [Shift_BreakStartTime1], [Shift_BreakEndTime1], [Shift_BreakStartTime2], [Shift_BreakEndTime2], [Shift_BreakStartTime3], [Shift_BreakEndTime3], [Shift_MinTimeOT], [Shift_MaxTimeOT], [Shift_WorkingDay_OverTime], [Shift_TotalWorkingHours], [Isdeleted], [Emp_ID], [Shift_FirstHalfWorkingHours], [Shift_SecondHalfWorkingHours], [IsBreakDeducted], [DefaultShift], [ShiftType], [CreatedDate], [ModifiedDate], [24HrsShift]) VALUES (0, N'No Shift', N'NOS', N'No Shift', N'07:00 AM', N'07:00 PM', N'07:00 AM', N'01:00 PM', N'01:00 PM', N'07:00 PM', N'00:05', N'00:05', NULL, NULL, NULL, NULL, NULL, NULL, N'01:00', N'07:30', 1, N'12:00', 0, N'1', N'06:00', N'06:00', 1, 0, 0, NULL, NULL, 0)
INSERT  INTO [dbo].[TA_Tbl_ShiftSettings] ([CompanyId], [MaxHoursBeforeShift], [MaxHoursAfterShift], [ShiftBreak], [ShiftMaxBreakHours], 
[MonthlyWorkingHours], [WeeklyWorkingHours], [EmpID], [HolidayOT], [WeekOffOT], [otOption], [DefaultMonthClosureDate], [IsFlexible], 
[FlexibleFlag], [OTRoundoffEnable], [FullDayAttendanceHrs], [HalfDayAttendanceHrs], [HalfDayAttendance], [FullDayAttendance],
[WeeklyOffStartHours], [IgnoreDuplicatePunch], [PunchInterval], [AfterShiftTime], [BeforeShiftTime], [DefinedWorkhrs], [NoOfSuccessiveDaysInYear],
[CompensationValitityDays], [VaildityCompOffDays], [HalfDayCompOff], [FullDayCompOff], [LateEntry], [EarlyEntry], [EarlyExit], [LateExit], [TimeStamp],
[TimeStamp1], [IsLunchDeduction], [LunchDeductionHours], [Flexi_AfterShiftTime], [Flexi_BeforeShiftTime], [Flexi_DefinedWorkhrs], 
[MaxHoursBeforeShift_24HrsShift], [WeeklyOffStartHours_24HrsShift], [CumulativeWeekStartDay], [CumulativeWeekEndDay], [MonthStartDay], [MonthEndDay],
[Carry_Forward_COff_Year], [isRequestingforCompOff], [LateMinsPerDay] ,[LateDaysPerMonth], [EarlyExitMinsPerDay],[EarlyExitDaysPerMonth],[EnableAbsent] ) 
VALUES (-1, N'02:00', N'02:00', N'', N'', N'', N'', N'1', CAST(1.0 AS Decimal(18, 1)),    CAST(1.0 AS Decimal(18, 1)),    N'WeeklyOff', DATEADD(MONTH,DATEDIFF(MONTH,0,dateadd(month,-1,GETDATE())),-1), 0, 0, 0, N'', N'', 1, 1,
N'16:00', 1, N'00:10', 1, 1, 1, 30,	 0, 90, N'11:00', N'12:00', 1, 1, 1, 1,	 NULL, NULL, 0, N'00:00', 0, 0, 0, N'00:02', N'23:00', N'1', N'7',N'1',N'31',1,0,30,3,20,5,1)
insert into Ta_tbl_EmailScripts (ScriptId,ScriptText,ScriptType) values ('1','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%" height="25"><b><span class="Header">&nbsp;<<lblleaveapplicationform>></span></b>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td height="19" width="30%">  <b><font face="Arial" size="2"><<lblemployeeid>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<employeeid>></font></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblemployeename>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<employeename>></font></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblapplicationdate>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<applicationdate>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblleavetype>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<leavetype>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblnumberdaysapplied>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<numberdaysapplied>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblleavedate>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblfromdate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<fromdate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lbltodate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<todate>></font></td></tr></table></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblsession>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="Table1">  <tr><td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblfromsession>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<fromsession>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lbltosession>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<tosession>></font></td></tr></table></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblreason>></font></b></td><td height="19">  <font face="Arial" size="2">&nbsp;<<reason>></font></td></tr></table>  <br/><a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>  </body></html>','New Leave Application Form')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('3','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span class="Header">&nbsp;<<PermissionForm>></span>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>> </font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">      <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> :</font></b></td>  <td width="36%">      <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">      <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">      <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr>  </table>  <br/>   <a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>  </body>  </html>','New Permission Form')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('4','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span class="Header">&nbsp;<<PermissionForm>></span>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>> </font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">  <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> : </font></b>  </td>  <td width="36%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr>  </table>  <br/>   <a href=<<LinkData>>>      <font face="Arial" size="2">Click here for approval</font></a>   </body>  </html>','Permission Modify Form')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('5','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%"> <b> <span class="Header">&nbsp;<<lblPermissionSanction>></span> </b> </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1" height="122">  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td width="70%" height="16">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">  <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> :</font></b></td>  <td width="36%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr> <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr> <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table>  <br />      <a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>   </body>  </html>','Permission Application Sanction By Reporting to Person')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('6','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span>&nbsp;<<lblPermissionSanction>></span></td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1" height="122">  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td width="70%" height="16">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="10%">  <b><font face="Arial" size="2"><<lblFromTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table>  </body>  </html>','Forwarded Permission Application Sanction')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('7','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%"><b>  <span>&nbsp;<<lblLeaveApplicationForm>></span></b></td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>> </font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblApplicationDate>> </font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<ApplicationDate>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblLeaveType>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<LeaveType>></font>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblNumberDaysApplied>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<NumberDaysApplied>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblLeaveDate>></font></b>  </td>  <td width="70%" height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%">  <b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<ToDate>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblSession>></font></b></td>  <td width="70%" height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="Table1">  <tr>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblFromSession>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<FromSession>></font></td>  <td width="5%">  <b><font face="Arial" size="2">&nbsp;<<lblToSession>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<ToSession>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr><tr><td height="19"><b><font face="Arial" size="2"> <<lblreason>> </font></b></td><td height="19"><font face="Arial" size="2">&nbsp;<<reason>> </font></td></tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblRemarks>></font></b><lblremarks>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table><br/><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval</a></font>  </body>  </html>','Leave Application Sanction By Reporting to Person')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('9','<html><body direction="<<ltr_rtl>>">
<table width="750px" style="border: solid 1px black;"   cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;">
<td style="width: 100%;"> <img src="cid:image1" style="float: left;  padding-left: 10px; border: none;">
<a href="http://www.angleritech.com" target="_blank">
<img src="cid:imgCompLogo" align="right" style="float: right; padding-right:10px; padding-top:10px; border: none;" /></a></td></tr>
<tr><td style="background-color: #E0E6EE;"><br />
<table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="AutoNumber2">
<tr><td     width="100%" style="padding-left: 10px;"><b><font face="Verdana" color="#000">Dear     Admin,</font></b></td></tr>
<tr><td height="12"></td></tr><tr><td width="100%"     style="padding-left: 10px;">
<font face="Verdana" color="#000"     size="2"><<licenserequestdetails>></font></td></tr><tr><td     height="35"></td></tr></table>  
<table border="1" cellpadding="2" style="margin-left: 30px;display:none;"     bordercolor="#666666" width="400 px" id="AutoNumber1">
<tr><td width="80%"     height="19"><font face="Verdana" size="2"><<lblemployee>></font></td>
<td     width="20%" height="19" style="text-align: left;"><b><font face="Verdana"     size="2"><<employee>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblconcurrentusers>> </font>  </td>
<td height="19" style="text-align: left;"><b><font face="Verdana"     size="2"><<concurrentusers>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblterminals>></font></td>
<td height="19"     style="text-align: left;"><b><font face="Verdana"     size="2"><<terminals>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblversion>></font></td><td height="19"     style="text-align: left;">
<b><font face="Verdana"     size="2"><<version>></font></b></td></tr></table>  <table style="width: 100%; padding-left: 20px;">
<tr><td colspan="2"     height="35"></td></tr><tr><td colspan="2" height="19" style="padding-left: 10px;">
<font face="Verdana" color="#000" size="2"><<regards>></font></td></tr><tr><td colspan="2" height="19" style="padding-left: 10px;">
<font face="Verdana" color="#000"     size="2"><<clientname>></font></td></tr></table><br /></td></tr>
<tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;">
<a href="http://www.angleritech.com" target="_blank" style="text-decoration: none; color: #224d6a;padding-right: 10px;">Angler Technologies </a></td></tr></table></body></html>','License Request')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('10','<html><body direction="<<ltr_rtl>>">  
<table width="750px" style="border: solid 1px black;" cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;"> 
<td style="width: 100%;">  <img src="cid:image1" style="float: left; padding-left: 10px; border: none;">
<a href="http://www.angleritech.com" target="_blank"> <img src="cid:imgCompLogo" align="right" style="float: right;    padding-right: 10px; padding-top: 10px; border: none;" /></a></td></tr><tr>  
<td style="background-color: #E0E6EE;"><br />
<table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="Table1">  
<tr><td width="100%" style="height: 18px" style="padding-left: 10px;">
<font face="Verdana" color="#000"> <<licenserequestusername>>,</font></td></tr>  <tr><td height="12"></td></tr><tr>
<td width="100%" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<licenserequestdetails>></font></td></tr>
<tr><td height="35"></td></tr>  </table>
<table border="1" cellpadding="2" style="margin-left: 30px;display:none;" bordercolor="#666666" width="400" id="Table2"> 
<tr><td width="80%" height="19"><font face="Verdana" size="2"><<lblemployee>></font></td>  
<td width="20%" height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<employee>></font></b></td></tr>  
<tr><td height="19" ><font face="Verdana" size="2"><<lblconcurrentusers>> </font></td>  <td height="19"  style="text-align: left;"><b>
<font face="Verdana" size="2"><<concurrentusers>></font></b></td></tr>  <tr><td height="19" >
<font face="Verdana" size="2"><<lblterminals>></font></td>  <td height="19"  style="text-align: left;"><b>
<font face="Verdana" size="2"><<terminals>></font></b></td>  </tr><tr><td height="19" ><font face="Verdana" size="2"><<lblversion>></font></td> 
<td height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<version>></font></b></td></tr>  </table><br />
<table style="width: 100%; padding-left: 20px;"><tr><td colspan="2" height="35"></td></tr>  <tr>
<td colspan="2" height="19" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<regards>></font></td></tr> 
<tr><td colspan="2" height="19" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<clientname>></font></td>
</tr></table><br />  </td></tr><tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;"> 
<a href="http://www.angleritech.com" target="_blank" style="text-decoration: none; color: #224d6a; padding-right: 10px;">Angler Technologies </a></td>
  </tr></table></body></html>','License Request Client')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('11','<html><body direction="<<ltr_rtl>>"><table width="750px" style="border: solid 1px black;" cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;"> <td style="width: 100%;"><img src="cid:image1" style="float: left; padding-left: 10px; border: none;"><a href="http://www.angleritech.com" target="_blank"><img src="cid:imgCompLogo"  align="right"  style="float: right; padding-right: 10px; padding-top: 10px; border: none;" /></a></td></tr><tr>
<td style="background-color: #E0E6EE;"><br /><table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="Table1"><tr><td height="12"></td></tr><tr><td width="100%" style="padding-left: 10px;"><font face="Verdana" color="#000"><<licenserequestdetails>></font></td></tr><tr><td height="35"></td></tr></table>
<table border="1" cellpadding="2" style="margin-left: 30px;" bordercolor="#666666" width="400" id="Table2"><tr><td width="80%" height="19"><font face="Verdana" size="2"><<lblemployee>></font></td><td width="20%" height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<employee>></font></b></td></tr><tr><td height="19" ><font face="Verdana" size="2"><<lblconcurrentusers>> </font></td><td height="19"  style="text-align: left;"><b><font face="Verdana" size="2"><<concurrentusers>></font></b></td></tr><tr><td height="19" ><font face="Verdana" size="2"><<lblterminals>></font></td><td height="19"  style="text-align: left;"><b><font face="Verdana" size="2"><<terminals>></font></b></td>
</tr><tr><td height="19" ><font face="Verdana" size="2"><<lblversion>></font></td><td height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<version>></font></b></td></tr></table><br /><table style="width: 100%; padding-left: 20px;"><tr><td colspan="2" height="35"></td></tr><tr><td colspan="2" height="19"><<regards>></td></tr><tr><td colspan="2" height="19"><<clientname>></td></tr></table><br />
</td></tr><tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;"><a href="http://angeritech.com" target="_blank" style="text-decoration: none; color: #224d6a; padding-right: 10px;">Angler Technologies </a></td></tr></table></body></html>','License Activation')
insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('12','<html>  <body direction="<<ltr_rtl>>"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="700" id="AutoNumber2">    <tr bgcolor="#003466">  <td width="100%" height="25"><span class="Header">&nbsp;<<lblOndutyForm>></span></td>    </tr></table><table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"    width="700" id="AutoNumber1">    <tr>  <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblApplicationDate>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<ApplicationDate>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblODDate>></font></b>  </td>  <td height="19"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="100%" id="AutoNumber3">    <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<ToDate>></font></td>    </tr></table>  </td>    </tr>  <tr>  <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font>  </td>    </tr>   <tr>  <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font>  </td>    </tr></table>  </body>  <br /><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval </a></font>  </html>','Onduty Application From')
insert into TA_TBL_EmailScripts (ScriptId,ScriptText,ScriptType) values ('13','<html>  <body direction="<<ltr_rtl>>"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="700" id="AutoNumber2">    <tr bgcolor="#003466">  <td width="100%" height="25"><b><span class="Header">&nbsp;<<lblOndutyForm>></span></b></td>    </tr></table><table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"    width="700" id="AutoNumber1">    <tr>  <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblApplicationDate>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<ApplicationDate>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblODDate>></font></b>  </td>  <td height="19"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="100%" id="AutoNumber3">    <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<ToDate>></font></td>    </tr></table>  </td>    </tr>  <tr>  <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font>  </td>    </tr><tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>   <tr>  <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font>  </td>    </tr></table>  </body>  <br /><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval </a></font>  </html>','Onduty Application Modify')
insert into ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values(14,'
<font face="Arial" size="2">
Dear <<lblusername>>,
</font>
<br/>
<br/>
<font face="Arial" size="2">Your Timecheck password has been reset successfully.
</font>
<br/>
<br/>
<font face="Arial" size="2">
Note:Use the default password <b>(i.e. welcome)</b> of timecheck for login right now. 
After the successful login into Timecheck, change the password immediately.
</font>
<br/>
<br/>
<font face="Arial" size="2">Regards,</font>
<br/>
<font face="Arial" size="2">TimeCheck</font>','ResetPassword')
insert into TA_TBL_EmailScripts (ScriptId,ScriptText,ScriptType) values (15,'<html>
<body direction="<<ltr_rtl>>">
    <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="600" id="AutoNumber1">
	<tr bgcolor="#003466">
            <td width="100%" height="25" colspan=''2''><b><span class="Header">&nbsp;<<lblCompform>></span></b></td>
        </tr>
        <tr>
            <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b></td>
            <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblDutyDate>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<DutyDate>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblInTime>></font> / <font face="Arial" size="2"><<lblOutTime>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<Intime>></font> / <font face="Arial" size="2">&nbsp;<<OutTime>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblDayWorked>></font> / <font face="Arial" size="2"><<lblWorkedHours>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<DayWorked>></font> / <font face="Arial" size="2">&nbsp;<<WorkedHours>></font></td>
        </tr>
              <tr style=''display:<<disvalue>>''>
                     <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b></td>
                     <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font></td>
              </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font></td>
        </tr>
    </table>
</body>
</html>','CompOff Application form')
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (50, N'Ta_Tbl_yearsetting', N'Organization_YearSetting.aspx', N'../Organization%20Settings/Organization_YearSetting.aspx', N'Year Settings in Configuration', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (6, N'TA_Tbl_leveldetails', N'TA_UI_Master_OrganisationLevels.aspx', N'../Masters/TA_UI_Master_OrganisationLevels.aspx', N'Organization Levels in Organization Management', 3, 1)
--Commented on 15-05-2019 06:56 PM
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (7, N'TA_Tbl_LeavePolicy', N'TA_UI_MasterLeavePolicyAdd.aspx', N'../Masters/TA_UI_MasterLeavePolicyAdd.aspx', N'Leave Policy Master', 2, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (223, N'TA_Tbl_terminaldatatype', N'TA_UI_Master_TerminalDatatypeAdd.aspx', N'../Masters/TA_UI_Master_TerminalDatatypeAdd.aspx', N'Terminal Data Type in Device Management', 1, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (224, N'TA_Tbl_terminal', N'TA_UI_Master_TerminalAdd.aspx', N'../Masters/TA_UI_Master_TerminalAdd.aspx', N'Terminal Master', 3, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (15, N'TA_Tbl_entrance', N'TA_UI_Master_EntranceAdd.aspx', N'../Masters/TA_UI_Master_EntranceAdd.aspx', N'Entrance Master', 1, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (68, N'TA_Tbl_punchTypes', N'TA_UI_Master_PunchTypes_Add.aspx', N'../Masters/TA_UI_Master_PunchTypes_Add.aspx', N'Punch Types', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (17, N'TA_Tbl_Title', N'TA_UI_Master_TitleFirstAdd.aspx', N'../Masters/TA_UI_Master_TitleFirstAdd.aspx', N'Designation', 0, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (18, N'TA_Tbl_Employee', N'TA_UI_Master_EmployeeAdd.aspx', N'../Masters/TA_UI_Master_EmployeeAdd.aspx', N'Employee Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (28, N'Ta_tbl_permanentshiftallocation', N'TA_UI_Transaction_ShiftAllocationAdd.aspx', N'../Transactions/TA_UI_Transaction_ShiftAllocationAdd.aspx', N'Shift Allocation for Employee', 24, 0)
GO
--Standard Demo
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (50, N'Ta_Tbl_yearsetting', N'Organization_YearSetting.aspx', N'../Organization%20Settings/Organization_YearSetting.aspx', N'Year Settings in Configuration', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (6, N'TA_Tbl_leveldetails', N'TA_UI_Master_OrganisationLevels.aspx', N'../Masters/TA_UI_Master_OrganisationLevels.aspx', N'Organization Levels in Organization Management', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (7, N'TA_Tbl_LeavePolicy', N'TA_UI_MasterLeavePolicyAdd.aspx', N'../Masters/TA_UI_MasterLeavePolicyAdd.aspx', N'Leave Policy Master', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (223, N'TA_Tbl_terminaldatatype', N'TA_UI_Master_TerminalDatatypeAdd.aspx', N'../Masters/TA_UI_Master_TerminalDatatypeAdd.aspx', N'Terminal Data Type in Device Management', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (224, N'TA_Tbl_terminal', N'TA_UI_Master_TerminalAdd.aspx', N'../Masters/TA_UI_Master_TerminalAdd.aspx', N'Terminal Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (15, N'TA_Tbl_entrance', N'TA_UI_Master_EntranceAdd.aspx', N'../Masters/TA_UI_Master_EntranceAdd.aspx', N'Entrance Master', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (68, N'TA_Tbl_punchTypes', N'TA_UI_Master_PunchTypes_Add.aspx', N'../Masters/TA_UI_Master_PunchTypes_Add.aspx', N'Punch Types', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (17, N'TA_Tbl_Title', N'TA_UI_Master_TitleFirstAdd.aspx', N'../Masters/TA_UI_Master_TitleFirstAdd.aspx', N'Designation', 0, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (18, N'TA_Tbl_Employee', N'TA_UI_Master_EmployeeAdd.aspx', N'../Masters/TA_UI_Master_EmployeeAdd.aspx', N'Employee Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (28, N'Ta_tbl_permanentshiftallocation', N'TA_UI_Transaction_ShiftAllocationAdd.aspx', N'../Transactions/TA_UI_Transaction_ShiftAllocationAdd.aspx', N'Shift Allocation for Employee', 24, 1)
INSERT [dbo].[TA_Tbl_Level] ([levelName], [parentLevelID], [isDeleted], [timeStamp], [emp_Id]) VALUES (N'Company', 0, 0, GETDATE(), N'1')
INSERT [dbo].[TA_Tbl_Level] ([levelName], [parentLevelID], [isDeleted], [timeStamp], [emp_Id]) VALUES (N'Department', 1, 0, GETDATE(), N'1')
-----Default Leave Types
insert into TA_Tbl_LeaveType VAlues('CL','Casual Leave',0,1,getdate(),0,0,0,'Both',0,0,0,0)
insert into TA_Tbl_LeaveType VAlues('SL','Sick Leave',0,1,getdate(),0,0,0,'Both',0,0,0,0)
insert into TA_Tbl_LeaveType VAlues('ML','Maternity Leave',0,1,getdate(),0,0,0,'Both',0,0,0,0)
insert into TA_Tbl_LeaveType VAlues('EL','Earned Leave',0,1,getdate(),1,0,0,'Both',0,0,0,0)
insert into TA_Tbl_LeaveType VAlues('WFH','Work From Home',0,1,getdate(),0,0,0,'Both',0,1,0,0)
insert into TA_Tbl_LeaveType VAlues('WFO','Work From Office',0,1,getdate(),0,0,0,'Both',0,1,0,0)
insert into TA_Tbl_LeaveType VAlues('PL','Paternity Leave',0,1,getdate(),0,0,0,'Both',0,1,0,0)
insert into TA_Tbl_LeaveType VAlues('COM-L','Commuted Leave',0,1,getdate(),0,0,0,'Both',0,1,0,0)
insert into TA_Tbl_Category values('Staff',0,1,0,'48',8,'08:00',null,null,null)
insert into TA_Tbl_Type values('Permanent',0,1,0,1)
insert into TA_Tbl_Religion values('All','All',0)
--Dashboard Rights tabls
insert into ta_tbl_DashboardData values('AttendanceData','Present',1)
insert into ta_tbl_DashboardData values('AttendanceData','Absent',2)
insert into ta_tbl_DashboardData values('AttendanceData','Approved Leave',3)
insert into ta_tbl_DashboardData values('AttendanceData','Approved Onduty',4)
insert into ta_tbl_DashboardData values('AttendanceData','Punctuality',5)
insert into ta_tbl_DashboardData values('AttendanceData','Attendance Summary',6)
insert into ta_tbl_DashboardData values('ApprovalData','Leave',1)
insert into ta_tbl_DashboardData values('ApprovalData','Onduty',2)
insert into ta_tbl_DashboardData values('ApprovalData','Permission',3)
insert into ta_tbl_DashboardData values('ExceptionData','Late Entry',1)
insert into ta_tbl_DashboardData values('ExceptionData','Early Exit',2)
insert into ta_tbl_DashboardData values('ExceptionData','Shift Not Allocated',3)
insert into ta_tbl_DashboardData values('ExceptionData','Approved Overtime',4)
insert into ta_tbl_DashboardData values('ExceptionData','Discrepancy',5)
insert into ta_tbl_DashboardData values('ExceptionData','Non Processed Record',6)
insert into ta_tbl_DashboardUserrights  values(1,1,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,2,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,3,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,4,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,5,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,6,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,7,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,8,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,9,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,10,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,11,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,12,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,13,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,14,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,15,1,1,1,1,1)
--Individual usergroup Dashboard rights
insert into ta_tbl_DashboardUserrights  values(2,1,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,2,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,3,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,4,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,5,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,6,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,7,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,8,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,9,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,10,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,11,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,12,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,13,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,14,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,15,0,1,0,0,1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 179, 179, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 246, 246, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 208, 235, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 32, 208, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 210, 236, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 22, 210, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 211, 236, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 35, 211, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 216, 236,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 23, 216,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 89, 236,  0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 173, 215,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 175, 215, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 213, 237, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 33, 213, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 144, 192, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 41, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 39, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 40, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 105, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 183, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 145, 192, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 34, 145, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 37, 145, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 55, 190, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,0,0,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,50,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,51,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,52,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,16,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,75,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,47,189,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,6,189,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,10,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,223,10,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,224,10,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,15,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,68,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,204,188,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,17,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,228,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,94,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,95,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,104,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,18,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,103,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,225,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,226,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,227,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,229,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,205,188,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,42,205,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,84,205,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,206,235,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,19,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,20,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,69,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,207,235,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,28,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,29,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,255,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,202,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,60,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,116,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,203,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,208,235,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,32,208,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,44,208,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,254,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,97,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,36,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,209,236,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,195,209,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,196,209,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,108,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,96,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,76,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,211,236,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,35,211,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,117,211,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,89,236,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,248,236,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,175,215,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,212,237,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,220,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,26,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,98,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,222,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,102,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,221,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,213,237,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,92,213,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,33,213,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,218,217,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,27,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,62,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,66,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,219,217,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,71,219,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,70,219,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,144,192,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,41,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,30,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,39,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,180,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,40,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,105,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,45,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,118,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,183,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,145,192,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,34,145,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,37,145,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,127,145,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,147,192,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,160,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,171,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,79,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,265,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,43,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,233,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,232,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,234,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,177,177,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,21,190,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,54,190,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,53,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,49,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,48,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,78,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,99,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,100,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,72,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,107,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,197,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,198,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,199,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,12,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,230,12,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,231,12,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,109,193,0,0,0,0,0,GETDATE(),1)
--INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,249,249,0,0,0,0,0,GETDATE(),1)
/*********************/
insert into ta_tbl_SMSTags values('{Employee ID}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Late By Hrs}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Early Exit Hrs}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Less Hours}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Count}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Leave From - Leave To}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Leave Type}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{No.of Days}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Permission From - Permission To}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{No.of Hrs}','PermissionApplication',GETDATE())
Go
insert into ta_tbl_SMSTags values('{Employee ID}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{OnDuty From - OnDuty To}','OnDuty',GETDATE())
Go
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (243, N'Menu_SMSConfiguration', N'Masters/SMS_Configuration.aspx', 194, 10, NULL)
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (244, N'Menu_SMSTemplate', N'Masters/SMS_TemplateList.aspx', 194, 11, NULL)
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (245, N'Menu_SMSLogDetails', N'Masters/SMS_LogDetails.aspx', 194, 12, NULL)
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Late Entry', N'Dear {User Name}, The following employees are late comers today', 1, CAST(0x0000A6EF011D1238 AS DateTime), 1, N'03:00', N'01:00', 0, N'', 0, N'{Employee Name}-{Late By Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Early Exit', N'Dear {User Name}, The following employees are left before shift end time', 0, CAST(0x0000A68D00B93DE5 AS DateTime), 1, N'00:05', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Early Exit Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Less Hours Worked', N'Dear {User Name}, The following employees are not met the defined work hours,', 0, CAST(0x0000A689012CF23B AS DateTime), 1, N'01:00', N'', 0, N'00:10', 0, N'{Employee ID}-{Employee Name}-{Less Hours}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Absent - Single Day', N'Dear {User Name}, The following employees are absent today', 1, CAST(0x0000A6EF01047AEA AS DateTime), 1, N'00:59', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Continuous Absent', N'Dear {User Name}, The following employees are continously absent from last {count} days', 0, CAST(0x0000A68D00C0CFEA AS DateTime), 1, N'00:20', N'', 0, N'', 4, N'{Employee ID}-{Employee Name}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Apply', N'Dear {User Name}, The below employees applied the leave for below duration,', 0, CAST(0x0000A68E01209068 AS DateTime), 1, N'', N'', 1, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Forward', N'Dear {User Name}, The following employees leave is forward to approval,', 0, CAST(0x0000A681013554FD AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Approved', N'Dear {User Name}, The below leave was approved,', 0, CAST(0x0000A68101357062 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Apply', N'Dear {User Name}, The below employee applied the permission for below date,', 0, CAST(0x0000A68F00C78563 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Forward', N'Dear Manikandan', 0, CAST(0x0000A6A900D41391 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Approved', N'Dear {UserName},The following employee permission was approved.', 1, CAST(0x0000A6A900D44EEA AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Apply', N'Dear {User Name}, The below employee applied the Onduty for below date,', 0, CAST(0x0000A68F00C78563 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Forward', N'Dear {User Name}, the below employee OnDuty forwarded to approval,', 0, CAST(0x0000A6A900D41391 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Approved', N'Dear {UserName},The following employee OnDuty was approved.', 1, CAST(0x0000A6A900D44EEA AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
insert into TA_Tbl_Grade values('Grade 1',1,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 2',2,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 3',3,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 4',4,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 5',5,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 6',6,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 7',7,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 8',8,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 9',9,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 10',10,1,GETDATE(),0)
Insert into Ta_tbl_ReasonForNonProcessedData values(1,'Employee id is not available')
Insert into Ta_tbl_ReasonForNonProcessedData values(2,'Device is not created')
Insert into Ta_tbl_ReasonForNonProcessedData values(3,'Shift is not allocated')
Insert into Ta_tbl_ReasonForNonProcessedData values(4,'Punch Type is not created for this device')
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (243, N'Menu_SMSConfiguration', N'Masters/SMS_Configuration.aspx', 194, 10, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (244, N'Menu_SMSTemplate', N'Masters/SMS_TemplateList.aspx', 194, 11, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (245, N'Menu_SMSLogDetails', N'Masters/SMS_LogDetails.aspx', 194, 12, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (267, N'AutoShiftConfiguration', N'Transactions/TA_UI_Transaction_AutoShiftConfiguration.aspx', 207, 3, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (271, N'CanteenReport', N'Reports/TA_UI_Report_CanteenReport.aspx', 144, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) 
VALUES (N'SuperAdmin', 1, 267, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) 
VALUES (N'SuperAdmin', 1, 271, 144, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
Insert into ta_tbl_HelpContent values('How to create employees in TimeCheck?',' <p style="text-align: left !important; padding-left: 10px !important;">
                                        Once you have created the details of your organization, the next step is to add up your employees to application.
                                    </p>
                                    <p style="text-align: left !important; padding-left: 10px !important;">Employees can be added to your organization in any of the below two methods:</p>
                                    <ul>
                                        <li><a href="#">Create Employee(s) manually</a></li>
                                        <li><a href="#">Import Employee(s)</a></li>
                                    </ul>
                                    <p style="text-align: left !important; padding-left: 10px !important;">Create Employee(s) manually is a method to add employees manually to application. You can give the users user id and password. They can change their password later.</p>
                                    <ul>
                                        <li>Click Employee Management > Masters > Employee Master</li>
                                        <li>Click ''Add'' Button, it will redirect to add page for create employee manually.</li>
                                    </ul>
                                    <p style="text-align: left !important; padding-left: 10px !important;">''Import Employee(s)''</p>
                                    <ul>
                                        <li>Click Employee Management > Masters > Master Data Import</li>
                                        <li>Download Template file</li>
                                        <li>Fill the document as per information mentioned in the screen and then upload it</li>
                                    </ul>',GETDATE())
Insert into ta_tbl_HelpContent values('Where to configure Overtime in TimeCheck?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    For calculating overtime on working day , you need to configure overtime in below pages.
                                    <ul>
                                        <li>In Employee master, you need to configure overtime eligible as <b>Yes</b></li>
                                        <li>And then in shift master, you need to configure below fields for overtime calculation.
                                            <ul>
                                                <li>Minimum Extra time for overtime </li>
                                                <li>Maximum Extra time for overtime</li>
                                                <li>And Over Time On Working Days</li>
                                            </ul>
                                        </li>
                                        <li>Based on the above configurations the system will calculate overtime.</li>
                                        <li>Note: if any one of above mentioned fields are not configured, that case the system wont calculate Overtime.</li>
                                    </ul>
                                    For calculating overtime on weekly off and Holiday, you need to configure overtime value in below page.
                                    <ul>
                                        <li>Configuration -> Organization Settings -> OT & Comp Off Tab</li>
                                    </ul>
                                </p>',GETDATE())                                    
Insert into ta_tbl_HelpContent values('How to allocate Shift to employees?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    For allocating the shift to employee(s), please proceed the below steps,
                                    <ul>
                                        <li>Click Shift Management > Transaction > Shift Allocation > Add </li>
                                        <li>Choose the Employee selection mode, based on your needs.</li>
                                        <li>If you want to allocate shift for one employee alone, please choose Single option otherwise choose Multiple option for allocation</li>
                                        <li>Based on the employee selection, it will load shift details into shift dropdown.</li>
                                        <li>Pick the Shift and select the weekly off days</li>
                                        <li>And then enter the from and to date</li>
                                        <li>Click Save Button.</li>
                                        Note:Based on the from and to date mentioning, it will allocate the shift to employee(s).
                                    </ul>
                                </p>',GETDATE())
Insert into ta_tbl_HelpContent values('How to update email id to all employees?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    Using CSV / excel file, we can update email id to all employees within few seconds.
                                    For updating email ids to all employee(s), proceed the below steps.
                                    <ul>
                                        <li>Click Employee Management > Masters > Employee Master > Bulk Configuration Button, it will redirect you to one new window for updation. </li>
                                        <li>Click Download Template Button, it will download one excel file in CSV format.</li>
                                        <li>Fill employee Id, Official / person Email id of the employees.</li>
                                        <li>Then save and close the file</li>
                                        <li>Now click choose file button, it will open one new window. Please choose the file where you are saved the filled document.</li>
                                        <li>And then choose the category as Official Email ID / Personal Email ID option. Based on this selection only, the system will refer the data in excel document and update it into database.</li>
                                        <li>Now click upload button. if it successfully updated into database you will receive updated successfully alert message otherwise you will receive some other alert message.</li>
                                    </ul>
                                </p>',GETDATE())
Insert into ta_tbl_HelpContent values('How many employees can able to create in demo version?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    User can able to create <b>N Number </b>of employees into demo version using Manual creation / Import Master in Timecheck, but they can able to do any transaction / viewing report for <b>5 employees</b> alone in <b>Demo Version</b>.
                                </p>',GETDATE())
Insert into ta_tbl_HelpContent values('How to add devices and Punch Types in TimeCheck?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    To create device:
                                </p>
                                <ul>
                                    <li>Click Device Management > Terminal > Terminal Master</li>
                                    <li>Click ''Add'' Button in list page, it will redirect you to add page for create device manually.</li>
                                    <li>Enter the device ID, Name and select raw data Format (i.e which database the device logs will be saved, that one select here in the dropdown) </li>
                                    <li>Then Click Save Button</li>
                                </ul>
                                <br />
                                <ul>
                                    <li>After creation of devices in terminal master, you need to define which devices are you using as In device and Out device in each door / entrances. Based on this configuration only, we are differentiating each punches as in and out and saved in database.</li>
                                    <li><strong>So whenever you are purchasing / replacing the devices that time you need to create device in terminal master and in Entrance master.</strong></li>
                                </ul>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    To Configure In & Out device:
                                </p>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    To configure In and Out device of each door / entrance, please proceed the below steps,
                                </p>
                                <ul>
                                    <li>Click Device Management > Entrance Master > Add</li>
                                    <li>Click ''Add'' Button in list page, it will redirect you to add page for create device manually.</li>
                                    <li>Enter the meaningful name in Entrance Name field for your quick access in furture if you have more than one entrance.</li>
                                    <li>Then select the Number of In and Out terminal count of this particular entrance.</li>
                                    <li>Based on the selection, it will load the dropdowns, select device in each dropdowns and then Click save button</li>
                                </ul>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    Create Punch Type:
                                </p>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    After creation of entrance master, create the punch types for each devices,
                                </p>
                                <ul>
                                    <li>Click Device Management > PunchType Master > Add</li>
                                    <li>Select Device</li>
                                    <li>Select Punch Type</li>
                                    <li>Enter Punch Type value</li>
                                    <li>Click Save Button</li>
                                </ul>',GETDATE())
Insert into ta_tbl_HelpContent values('What is meant by Freescan and Function Key in shift master?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    Free Scan:<br />
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Before doing an punch in device if any key is not pressed by employee, that should be called as Free Scan.
                                    <br />
                                    Function Key:<br />
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Before doing an punch in device any key is pressed by employee, that should be called as Function Key.
                                </p>',GETDATE())                                                                
Insert into ta_tbl_HelpContent values('Where to Configure Mail Domain details for Email Triggerring?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    Mail Configuration :
                                </p>
                                <ul>
                                    <li>Click Device Management > PunchType Master > Add</li>
                                    <li>Select Device</li>
                                    <li>Select Punch Type</li>
                                    <li>Enter Punch Type value</li>
                                    <li>Click Save Button</li>
                                </ul>',GETDATE())	
															