SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [dbo].[DateRange]
(
	@StartDate DATETIME,
	@EndDate DATETIME
)
RETURNS 
@SelectedRange TABLE
(IndividualDate Datetime, theValue1 int)
AS
BEGIN
	;WITH theDates (theDate)AS
     (SELECT @StartDate as theDate
      UNION ALL
      SELECT DATEADD(day, 1, theDate)
        FROM theDates
       WHERE DATEADD(day, 1, theDate) <= @EndDate
     )
     INSERT INTO @SelectedRange (IndividualDate,theValue1)
SELECT theDate, 1 as theValue
  FROM theDates
OPTION (MAXRECURSION 0)
Return
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select dbo.fgetResultinTD()
-- drop function dbo.fgetResultinTD
CREATE OR ALTER FUNCTION [dbo].[fgetResultinTD](@days int,@str varchar(max),@rs varchar(max),@rpress int,@daypart int,@flg int)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @tbl TABLE(tid INT IDENTITY(1,1),item INT,s VARCHAR(100),flg INT)
	INSERT INTO @tbl
	SELECT val1,val2,0 FROM sCommon.fnSplit(@rs,',') CROSS APPLY dbo.fnc_BifurcateString(ISNULL(Item,''),'-') WHERE Item<>''
	
	DECLARE @tbltmp TABLE(ttid INT IDENTITY(1,1),itm VARCHAR(100),intitem INT)
	INSERT INTO @tbltmp
	SELECT CASE WHEN item=0 THEN 'Sunday' WHEN item=1 THEN 'Monday' WHEN item=2 THEN 'Tuesday' WHEN item=3 THEN 'Wednesday' 
	WHEN item=4 THEN 'Thursday' WHEN item=5 THEN 'Friday' WHEN item=6 THEN 'Saturday' ELSE '' END,Item
	FROM sCommon.fnSplit(@str,',') WHERE Item<>''
	
	UPDATE S set S.flg=1 FROM @tbl S LEFT JOIN @tbltmp T ON S.s = T.itm
	WHERE S.s = T.itm
	
	DECLARE @i INT,@result VARCHAR(MAX)='',@cnt INT,@j INT,@s VARCHAR(100),@itm VARCHAR(100),@it INT,@header VARCHAR(MAX)
	
	SELECT @cnt = COUNT(*),@i=1,@j=0 FROM @tbl
	
	IF @flg=1
	BEGIN
		SELECT @j=CASE WHEN @rpress = 0 THEN @j+1 ELSE @j END		
		SELECT @it = CASE WHEN @rpress = 1 THEN @it+1 ELSE @it END
		
		SELECT @result = @result + CASE WHEN flg=1 THEN '<td align="center" style="background-color:#FFFFCC; width:2.5%;">' + 
		CASE WHEN @rpress=1 AND item=@daypart THEN '<img src="../../Images/Yes.png" />' WHEN @rpress=0 THEN '<img src="../../Images/No.png" />' 
		ELSE '' END + '</td>' ELSE '<td align="center" style="width:2.5%;">' + CASE WHEN @rpress=1 AND item=@daypart THEN 
		'<img src="../../Images/Yes.png" />' WHEN @rpress=0 THEN  '<img src="../../Images/No.png" />' ELSE '' END + '</td>' END FROM @tbl
	END
	ELSE
	BEGIN
		SELECT @result = @result + '<th>Roll No</th><th>Code</th><th>Student Name</th>'
		SELECT @result = @result + CASE WHEN flg=1 THEN '<th id="' + CONVERT(VARCHAR,item) + '" align="center" 
		style="background-color: #FFFFCC;" scope="col">' + CONVERT(VARCHAR,item) + '</th>' 
		ELSE '<th align="center" scope="col">' + CONVERT(VARCHAR,item) + '</th>' END FROM @tbl
		SELECT @result = @result + '<th>Absent Cnt.</th><th>Present Cnt.</th><th>Present Upto</th><th>Total</th>'
	END
	
	RETURN ISNULL(@result,'')	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select * from dbo.fnc_BifurcateString('darshan{%data%}thakkar','{%data%}')  
-- drop function dbo.fnc_BifurcateString  
CREATE OR ALTER FUNCTION [dbo].[fnc_BifurcateString](@String varchar(max),@Separator varchar(50))  
returns @Table table(val1 varchar(max), val2 varchar(max))  
as  
begin  
	declare @sLen as int, @v1 as varchar(max), @v2 as varchar(max),@c as int  
	select @sLen= len(@Separator)  
	if @String<>''  
	begin  
		if @sLen>0  
		begin  
			select @c=charindex(@Separator,@String)  
			select @c=isnull(@c,0)  
			if @c>0  
			begin  
				select @v1=LEFT(@String,@c-1)  
				select @v2=RIGHT(@String,LEN(@String)-(@c-1)-@sLen)  
			end  
			else  
			begin  
				select @v1=@String, @v2=''  
			end  
		end  
		else  
		begin  
			select @v1=@String, @v2=''  
		end  
	end  
	else  
	begin  
		select @v1='', @v2=''  
	end  
	insert into @Table select @v1,@v2  
	return  
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--- select dbo.fnc_SearchPagingFormat(1,5,1)    
--- Drop function fnc_SearchPagingFormat    
CREATE OR ALTER FUNCTION [dbo].[fnc_SearchPagingFormat](@PageIndex as int,@TotalRecords as int,@PageSize as int)   
returns varchar(5000)    
as     
begin        
Declare @MiddleRecord as int ,@Totalpages as int     
select @MiddleRecord  =4,@Totalpages= 0     
select @Totalpages = case @TotalRecords % @PageSize when 0 then (@TotalRecords / @PageSize)    
else cast(((@TotalRecords / @PageSize)) as int) + 1  end  
  
if @Totalpages =1    
return ''    
  
Declare @startRecord as int ,@EndRecord as int    
select @startRecord = 1,@EndRecord = @MiddleRecord *2    
if((@PageIndex + @MiddleRecord) < = @Totalpages)    
begin  
 select @startRecord = case when (@PageIndex - @MiddleRecord)> 0 then (@PageIndex - @MiddleRecord)+1 else  @startRecord end,    
 @EndRecord = case when (@PageIndex - @MiddleRecord)> 0 then (@PageIndex + @MiddleRecord) else  @EndRecord end          
end     
else     
begin             
 select @StartRecord  = case when  (@Totalpages - @MiddleRecord * 2)< =0 then 1 else  (@Totalpages - @MiddleRecord * 2) end ,@EndRecord = @Totalpages          
end     
  
if(@Totalpages < @EndRecord )     
begin     
 select  @EndRecord = @Totalpages    
end     
  
Declare @count as int,@OutPutPaging as varchar(5000),@TotalPage as int     
select @count =1 ,@OutPutPaging = '',@TotalPage = @EndRecord -@startRecord   +1    
  
while(@count <= @TotalPage)    
begin               
 select @OutPutPaging = @OutPutPaging + case @startRecord + (@count-1)   when  @Pageindex then           
 '<li style="float:left; display: inline; margin-right: 5px;">
 <a href="javascript:;" style="padding: 5px 7px 5px 7px; border: 1px solid #999999; border-radius:5px; text-decoration: none; white-space: nowrap; background: #FFFFFF; color:#CCC" class="disabled">' +   
 cast(@startRecord + (@count-1) as varchar(20))  + '</a></li>'
else     
 '<li style="float:left; display: inline; margin-right: 5px;">
 <a style="padding: 5px 7px 5px 7px; border: solid 1px #CCC; border-radius:5px; text-decoration: none; white-space: nowrap; background: #FFFFFF; color:#CCC" 
 onclick="ChangePage(' +cast(@startRecord + (@count-1) as varchar(20))  + ');" href="javascript:;" title="Go to page'     
 + CAST(@startRecord + (@count-1) as varchar(20)) + '">' +    CAST(@startRecord + (@count-1) as varchar(20))    + ' </a></li>'
end     
select @count = @count + 1    
end     
  
if(@PageIndex > 1)    
begin     
 select @OutPutPaging = '<li style="float:left; display: inline; margin-right: 5px;">
 <a style="padding: 5px 7px 5px 7px; border: solid 1px #CCC; border-radius:5px; text-decoration: none; white-space: nowrap; background: #FFFFFF; color:#CCC" 
 onClick="ChangePage(' +cast(@PageIndex -1 as varchar(20)) + ');"  href="javascript:;"  title="Go to First page">    
 <img src="../../Images/arrowLeft.gif" style="margin:0px; padding:0px;" align="absmiddle"/></a></li>' +  @OutPutPaging     
end     
if(@PageIndex < @Totalpages)    
begin     
 select @OutPutPaging =   @OutPutPaging  + '<li style="float:left; display: inline; margin-right: 5px;">
 <a style="padding: 5px 7px 5px 7px; border: solid 1px #CCC; border-radius:5px; text-decoration: none; white-space: nowrap; background: #FFFFFF; color:#CCC"
  href="javascript:;" title="Go to Next Page"  onClick="ChangePage(' + cast(@PageIndex + 1 as varchar(20)) + ');">    
 <img src="../../Images/arrowRight.gif" style="margin:0px; padding:0px;" align="absmiddle"/></a></li>'
end     
  
return '<div id="Paging" style="float:right; padding-right:10px;">'+  @OutPutPaging + '</div>'    
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [dbo].[RupieFormat](@v varchar(500))
returns varchar(200)
as
begin
  declare @res varchar(50)
  declare @p1 varchar(40)
  declare @p2 varchar(10)
  declare @return varchar(200)
  set @res = replace(convert (varchar(20), convert(money, @v), 3 ) , ',','')


  if(len(@res)>5)
  begin
	  set @p1 = left(@res, charindex('.', @res)-1)
	  set @p2 = substring(@res, charindex('.', @res), 10)

	  set @res = right(@p1, 3) + @p2
	  set @p1 = left(@p1, len(@p1)-3)

	  while (@p1<>'')
	  begin
		set @res = right(@p1, 2) + ',' + @res
		if (len(@p1) > 2)
		  set @p1 = left(@p1, len(@p1)-2)
		else 
		  set @p1= ''
	  end
	  set  @return=@res
	end

	else
	begin
		set @return=@res
	end

  return(@return)
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [dbo].[ufn_CSVToTable] ( @StringInput VARCHAR(8000), @Delimiter nvarchar(1))
RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN

    DECLARE @String    VARCHAR(10)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [String] )
        VALUES ( @String )
    END

    RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAccounting].[fDecimalValueGet] (@rValue decimal(20,5), @rDecimal int)
RETURNS nvarchar(200)
AS
BEGIN
	
	DECLARE @len INT, @lastNonSpacePosition INT, @return nvarchar(200)
	set	@len = LEN(@rValue)
	if(@rDecimal>0)
	BEGIN
		set @lastNonSpacePosition = @len - PATINDEX('%.%', REVERSE(@rValue)) + 1 + @rDecimal
	END
	ELSE
	BEGIN
		set @lastNonSpacePosition = @len - PATINDEX('%.%', REVERSE(@rValue))
	END
	set @return = LEFT(ROUND(@rValue, @rDecimal),@lastNonSpacePosition)
	return @return
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAccounting].[fNarrationSearchStringGet](@rSearchString [nvarchar](1000))
RETURNS [nvarchar](1000) WITH EXECUTE AS CALLER
AS 
BEGIN
	SET @rSearchString = sCommon.fReplace(@rSearchString, '*', '%')
	IF SUBSTRING(@rSearchString, 1, 1) <> '%'
	AND SUBSTRING(@rSearchString, LEN(@rSearchString), 1) <> '%'
	AND @rSearchString <> ''
		BEGIN
			SET @rSearchString = @rSearchString + '%'
		END
		
	RETURN @rSearchString
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAccounting].[fOpeningClosingBalanceGet](@1StartDate date,@1EndDate Date ,@1LedgerId int,@1IsOpening bit,@1OrgId int,@1AccountingYearId int) 
RETURNS Decimal(22,2) WITH EXECUTE AS CALLER
AS 
BEGIN
   DECLARE @lOpeningBalance  decimal(22,2)
   DECLARE @lCloseBalance  decimal(22,2)
   DECLARE @1OpeningClosingBal Decimal(22,2) 
        
       IF(@1IsOpening = 1)
          BEGIN             
					select @lOpeningBalance = OpeningBalance from sAccounting.tLedgerMaster Where Id = @1LedgerId
					
                    SELECT @1OpeningClosingBal = ISNULL(@lOpeningBalance,0) + ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @1OrgId AND T.AccountingYearId = @1AccountingYearId
					AND T.TransactionDate < @1StartDate AND TD.LedgerId=@1LedgerId 
				    --(TD.LedgerId = @rLedgerId OR @rLedgerId = 0)              
          END             
 
    RETURN @1OpeningClosingBal 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAdmission].[fAdmissionFormDisplayFieldGet](@rDisplayFieldId int,@rOrgId int)
RETURNS bit WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lSelected  bit

Select @lSelected = (CASE WHEN DO.DisplayFieldId Is Null THEN 0
						  WHEN DO.DisplayFieldId=0 THEN 0  ELSE 1 END) 
FROM 
sConfig.tDisplayFieldMaster DM LEFT JOIN sConfig.tDisplayFieldOrg DO ON DO.DisplayFieldId = DM.Id AND DO.OrgId =@rOrgId 
WHERE 
DM.FieldSource = 'Admission Form' 
AND DM.Id = @rDisplayFieldId

RETURN @lSelected

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId bigint,@rEventId smallint,@rAlertModeId tinyint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rResult nvarchar(2000)=''
	DECLARE @rEmailIds nvarchar(2000)=''
	DECLARE @rDefaultEmailIds nvarchar(2000)=''
	DECLARE @rMobileIds nvarchar(2000)=''
	DECLARE @rDefaultMobileIds nvarchar(2000)=''
	
	IF @rAlertModeId = 1
	BEGIN 
		SELECT @rEmailIds=ISNULL(EmailIds,'') FROM sAlert.tAssociateRecipient AR WHERE AR.ForUserId = @rUserId AND AR.EventId = @rEventId
		SELECT @rDefaultEmailIds=ISNULL(DefaultEmailIds,'') FROM sAlert.tAssociateRecipient AR WHERE AR.ForUserId = @rUserId AND AR.EventId = @rEventId
		
		IF(ISNULL(@rEmailIds,'')!='')
		BEGIN 
			SET @rResult = @rEmailIds
		END
		
		IF(ISNULL(@rDefaultEmailIds,'')!='')
		BEGIN 
			SET @rResult = @rDefaultEmailIds
		END
		
		IF(ISNULL(@rEmailIds,'')!='' AND ISNULL(@rDefaultEmailIds,'')!='')
		BEGIN 
			SET @rResult = @rEmailIds+','+@rDefaultEmailIds
		END
	END
	IF @rAlertModeId = 2
	BEGIN 
		SELECT @rMobileIds=ISNULL(MobileIds,'') FROM sAlert.tAssociateRecipient AR WHERE AR.ForUserId = @rUserId AND AR.EventId = @rEventId
		SELECT @rDefaultMobileIds=ISNULL(DefaultMobileIds,'') FROM sAlert.tAssociateRecipient AR WHERE AR.ForUserId = @rUserId AND AR.EventId = @rEventId
		
		IF(ISNULL(@rMobileIds,'')!='')
		BEGIN 
			SET @rResult = @rMobileIds
		END
		
		IF(ISNULL(@rDefaultMobileIds,'')!='')
		BEGIN 
			SET @rResult = @rDefaultMobileIds
		END
		
		IF(ISNULL(@rMobileIds,'')!='' AND ISNULL(@rDefaultMobileIds,'')!='')
		BEGIN 
			SET @rResult = @rMobileIds+','+@rDefaultMobileIds
		END
		
	END
	
	
    RETURN ISNULL(@rResult,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sAlert].[fExamDetailGet](@rExamId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			ISNULL(ED.ExamTopic,'')
			)
			    + ' , '
	FROM 
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE IF (@rTypeId=2)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			ISNULL(ED.ExamTime,'')
			)
			    + ' , '
	FROM 
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END

ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			CONVERT(VARCHAR(10), ED.ExamDate, 103)
			)
			    + ' , '
	FROM  
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END

    RETURN @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER FUNCTION [sAlert].[fHighestMarkGet](@rExamId bigint, @rSubjectId int, @rDivisionId int, @rClassId int, @rBatchId int )

RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER

AS
BEGIN

DECLARE @lHighestMark NVARCHAR(MAX)

--SELECT @lHighestMark = MAX(
--							   CASE 
--            WHEN @rSubjectId > 0 THEN ''
--            ELSE ISNULL(CS.SubjectCode,'') + ' - '
--        END +
--        CASE  
--            WHEN RD.IsPresent IS NULL THEN '0'
--            WHEN RD.IsPresent = 0 THEN '0'
--            WHEN E.IsMarksInDecimal = 1 THEN CONVERT(NVARCHAR(11), RD.Obtain)
--            WHEN E.IsMarksInDecimal = 0 THEN CONVERT(NVARCHAR(11), CAST(RD.Obtain AS INT))
--        END)
	(SELECT @lHighestMark  = COALESCE(@lHighestMark ,'')
		+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - ' END +
		Convert(varchar(11),ISNULL(MAX(RD.Obtain),0)) + ','

                                 
    FROM sAssessment.tResult R 
    INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
    INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
    INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
    INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sStudent.tStudentMaster SAM ON  A.StudentId = SAM.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
    WHERE
        E.Id=@rExamId
        AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND ((A.DivisionId=@rDivisionId) OR @rDivisionId=0)
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((E.BatchId=@rBatchId) OR @rBatchId=0)
		AND SAM.StatusId = 1
	GROUP BY CS.SubjectCode
	)
    SET @lHighestMark = LEFT(@lHighestMark, LEN(@lHighestMark) - 1)   
    RETURN @lHighestMark;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAlert].[fPendingDocumentsGet](@rSourceId bigint,@rSourceTypeId smallint)
RETURNS NVARCHAR(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
		DECLARE @lOrgId int=0

		DECLARE @rPendingDocumentsList nvarchar(2000)

		IF(@rSourceTypeId=2001)
		BEGIN
		
			SELECT @lOrgId = OrgId FROM sStudent.tStudentMaster WHERE Id = @rSourceId
			
			SELECT 
				@rPendingDocumentsList=COALESCE(@rPendingDocumentsList+',','') +  SDM.DocumentName
			FROM sCommon.tSubmitDocumentMaster SDM 
			WHERE 
				SDM.OrgId = @lOrgId AND SDM.SubmitDocumentFunctionalityId = 1 
				AND Id NOT IN (SELECT SubmitDocumentMasterId FROM sStudent.tStudentDocument WHERE StudentId  = @rSourceId)
				
		END
		IF(@rSourceTypeId=95)
		BEGIN
			
			SELECT @lOrgId = OrgId FROM sHrm.tEmployeeMaster WHERE Id = @rSourceId AND  ISNULL(IsOtherUser,0) = 0
			
			SELECT 
				@rPendingDocumentsList=COALESCE(@rPendingDocumentsList+',','') +  SDM.DocumentName
			FROM sCommon.tSubmitDocumentMaster SDM 
			WHERE
				SDM.OrgId = @lOrgId AND SDM.SubmitDocumentFunctionalityId = 2 
				AND Id NOT IN (SELECT SubmitDocumentMasterId FROM sHrm.tEmployeeDocument WHERE EmployeeId  = @rSourceId)	
				
		END
	
	    RETURN ISNULL(@rPendingDocumentsList,'') 
	    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAlert].[fPeriodWiseAttendanceGet](@rAcademicId bigint,@rSubjectId nvarchar(max), @rAttendanceDate date,@OrgId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lSubjectName  VARCHAR(MAX)
Declare @v Table 
(
Id int IDENTITY,
SubjectId int
)
INSERT INTO @v
SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSubjectId,',')

--Select * from #tmp

DECLARE @lCountSubjectId int,@lId int,@lSubjectId bigint

SELECT @lCountSubjectId=COUNT(Id) FROM @v
SELECT Top 1 @lId=Id FROM @v
DECLARE @lfinalResult  VARCHAR(MAX)=''
DECLARE @lResult  VARCHAR(MAX)=''
WHILE @lId <= @lCountSubjectId

			BEGIN
		
				SELECT @lSubjectId=SubjectId FROM @v WHERE Id=@lId
			
				SELECT @lSubjectName=Code from [sSetup].[tSubjectMaster] Where Id=@lSubjectId
				SET @lResult= @lSubjectName +':'
				(SELECT @lResult  = COALESCE(@lResult ,'') + ' P '
							+ CONVERT(VARCHAR(11),SR.PeriodNo,106) + ' - ' +
							(
							CASE  
							WHEN SR.IsPresent = 0 THEN 'Ab'
							WHEN  SR.IsPresent = 1 then 'Pr'
							END)
								+ ' , '
					from 
					sStudent.vStudentCommunication SC
					INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
					INNER JOIN [sSetup].[tSubjectMaster] SM ON SR.SubjectId=SM.Id 	
					WHERE (SC.OrgId=@OrgId) AND SR.AcademicId=@rAcademicId AND SubjectId=@lSubjectId AND AttendanceDate=@rAttendanceDate
						)
		
				  
				  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)

				  --Select @lResult
				  SET @lfinalResult=@lfinalResult + @lResult
				  --Set  @lResult1= '       '+ @lSubjectName +':' + @lResult
				  --Select @lResult1
				SET @lId=@lId+1
			END

--DROP TABLE #tmp

  RETURN  @lfinalResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER FUNCTION [sAlert].[fResultGet](@rResultId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'')
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER FUNCTION [sAlert].[fResultGetWithLineBreak](@rResultId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) --+ CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT)) 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+  CHAR(13) --+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'') 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAlert].[fResultWithMaxGet](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE 
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN E.IsMarksInDecimal = 1 THEN  CONVERT(VARCHAR(11),RD.Obtain)
			else CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END)
			+(CASE 
			WHEN RD.IsPresent = 0 THEN ''
			WHEN RD.IsPresent != 0 THEN + ' / ' + CONVERT(VARCHAR(11),Cast(Round(ED.Maximum,0) AS int)) + ' , ' END)
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult)- 1)
    RETURN @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAlert].[fResultWithMaxGetWithLineBreak](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) -- + CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE 
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN E.IsMarksInDecimal = 1 THEN  CONVERT(VARCHAR(11),RD.Obtain)
			else CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END)
			+(CASE 
			WHEN RD.IsPresent = 0 THEN ''
			WHEN RD.IsPresent != 0 THEN + ' / ' + CONVERT(VARCHAR(11),Cast(Round(ED.Maximum,0) AS int)) + ' , ' END)
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult)- 1)
    RETURN @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAppraisal].[fClassTeacherGet](@rEmployeeId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
	  DECLARE @lTempClassTeacher TABLE(ClassTeacher nvarchar(100))
	  INSERT INTO @lTempClassTeacher (ClassTeacher) 
	  Select (CM.DisplayTitle + '-' + DM.DisplayTitle) AS ClassTeacher from sSetup.tDivisionMaster DM
	  INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
	  Where ((DM.InchargeEmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	  
	  DECLARE @rAttClassTeacher nvarchar(500)
	  SELECT @rAttClassTeacher= coalesce(@rAttClassTeacher+',','')+convert(nvarchar(500),ClassTeacher )
	  FROM @lTempClassTeacher
		
      RETURN  ISNULL(@rAttClassTeacher,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select [sAppraisal].[fGetInnerHtml](1001000000016,3,52)
-- drop function [sAppraisal].[fGetInnerHtml]
CREATE OR ALTER FUNCTION [sAppraisal].[fGetInnerHtml](@rKEDID bigint)
returns varchar(max)
as
begin
	declare @res varchar(max)='',@i int	= 1
	select @res = @res + '<td width="80%"><table width="100%"><tr>'		
		
	select @res = @res + '
	<td width="30" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KRD.MyRating) + '</td>
	<td width="50" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KRD.ManagerRating) + '</td>
	<td width="85" style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 3px;">' + convert(varchar,KR.BusinessHeadRating) + '</td>'


	from [sAppraisal].[tKPAEmployeeRatingDetail] KRD
	LEFT JOIN [sAppraisal].[tKPAEmployeeRating] KR on 	KR.Id = KRD.KPAEmployeeRatingId
	LEFT JOIN [sAppraisal].[tAppraisalTypeMaster] AS ATM ON ATM.id=KR.AppraisalTypeId
	where KRD.KPAEmployeeDetailId = @rKEDID AND ATM.IsObsolete=0
	AND Kr.RatingStatusId>=5
	select @res = @res +'</tr></table></td>'
	
	return @res
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAppraisal].[fTeacherSujectClassGet](@rEmployeeId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
		DECLARE @rClassSubject nvarchar(max)=''
		
		SELECT @rClassSubject= ISNULL(@rClassSubject,'') + ISNULL(CM.DisplayTitle,'') + 
		ISNULL(DM.DisplayTitle,'') + ' - ' + ISNULL(SM.Title,'') + ','
		FROM sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = TSD.DivisionId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
		WHERE TSD.EmployeeId = @rEmployeeId
        ORDER BY CM.Id,DM.Id,SM.Id
        
        IF (RIGHT(@rClassSubject, 1) = ',')
        SET @rClassSubject = LEFT(@rClassSubject, LEN(@rClassSubject) - 1)
   
      RETURN  isnull(@rClassSubject,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 CREATE OR ALTER FUNCTION [sAssessment].[fCSGradeStringGet](@rGradeId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lGradeString  VARCHAR(MAX)
 
SELECT @lGradeString = COALESCE(@lGradeString ,'') +   d.GradeCode +  ','  + d.MarkRange + ' | ' 
FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
ORDER BY d.MinimumScore desc

RETURN @lGradeString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fGetAbsentCount](@rExamId int,@rAcademicId bigint,@rSubjectId bigint)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @AbsentCount int

Select @AbsentCount= COUNT(RD.IsPresent)
		From 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		Where 
		EC.ExamId=@rExamId AND
		R.AcademicId=@rAcademicId AND CS.SubjectId=@rSubjectId 
		AND RD.IsPresent=0


	return  @AbsentCount 



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetAverageDivisionMark](@rDivisionId int,@rExamDetailId int)
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId Decimal(8,2)
 SELECT @lResultId = ISNULL(AVG(Obtain),0) FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
  WHERE RD.ExamDetailId = @rExamDetailId
  AND A.DivisionId = @rDivisionId
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 CREATE OR ALTER FUNCTION [sAssessment].[fGetConfigGrade](@rOrgId nvarchar(200),@rObtain nvarchar(100))
RETURNS   nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lGrade nvarchar(10)
	DECLARE @GradeSetId int
	 Declare @M1 nvarchar(20),@M2 nvarchar(20),@M3 nvarchar(20),@M4 nvarchar(20),@M5 nvarchar(20),@M6 nvarchar(20),@M7 nvarchar(20),@M8 nvarchar(20),@M9 nvarchar(20),@M10 nvarchar(20)	
	 
	Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)

	
	Declare @Temp Table
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2)
	)

	insert into @Temp(GradeCode,MinimumScore)

		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @M1=(Select MinimumScore from @Temp where Id=1) 
	 	 Set @M2=(Select MinimumScore from @Temp where Id=2) 
	 	 Set @M3=(Select MinimumScore from @Temp where Id=3) 
	 	 Set @M4=(Select MinimumScore from @Temp where Id=4) 
	     Set @M5=(Select MinimumScore from @Temp where Id=5) 
         Set @M6=(Select MinimumScore from @Temp where Id=6) 
	     Set @M7=(Select MinimumScore from @Temp where Id=7) 
	 	 Set @M8=(Select MinimumScore from @Temp where Id=8) 
	 	 Set @M9=(Select MinimumScore from @Temp where Id=9) 
		 Set @M10=(Select MinimumScore from @Temp where Id=10)

		 IF(@rObtain >= @M1)
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=1
		 END
		 ELSE IF((@rObtain >= @M2 )AND (@rObtain < @M1))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=2
		 END
		 ELSE IF((@rObtain >= @M3)AND (@rObtain < @M2))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=3
		 END
		 ELSE IF((@rObtain >= @M4 )AND (@rObtain < @M3))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=4
		 END
		 ELSE IF((@rObtain >= @M5 )AND (@rObtain < @M4))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=5
		 END
		 ELSE IF((@rObtain >= @M6)AND (@rObtain < @M5))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=6
		 END
		 ELSE IF((@rObtain >= @M7)AND (@rObtain < @M6))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=7
		 END
		 ELSE IF((@rObtain >= @M8)AND (@rObtain < @M7))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=8
		 END
		 ELSE IF((@rObtain >= @M9)AND (@rObtain < @M8))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=9
		 END
		 ELSE IF((@rObtain >= @M10)AND (@rObtain < @M9))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=10
		 END


	return  @lGrade 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetConfigurationGrade](@rOrgId nvarchar(200),@rObtain decimal(6,2))
RETURNS   nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lGrade nvarchar(10)
	DECLARE @GradeSetId int
	 Declare @M1 decimal(6,2),@M2 decimal(6,2),@M3 decimal(6,2),@M4 decimal(6,2),@M5 decimal(6,2),@M6 decimal(6,2),@M7 decimal(6,2),@M8 decimal(6,2),@M9 decimal(6,2),@M10 decimal(6,2)
	 
	Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)

	
	Declare @Temp Table
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2)
	)

	insert into @Temp(GradeCode,MinimumScore)

		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @M1=(Select MinimumScore from @Temp where Id=1) 
	 	 Set @M2=(Select MinimumScore from @Temp where Id=2) 
	 	 Set @M3=(Select MinimumScore from @Temp where Id=3) 
	 	 Set @M4=(Select MinimumScore from @Temp where Id=4) 
	     Set @M5=(Select MinimumScore from @Temp where Id=5) 
         Set @M6=(Select MinimumScore from @Temp where Id=6) 
	     Set @M7=(Select MinimumScore from @Temp where Id=7) 
	 	 Set @M8=(Select MinimumScore from @Temp where Id=8) 
	 	 Set @M9=(Select MinimumScore from @Temp where Id=9) 
		 Set @M10=(Select MinimumScore from @Temp where Id=10)

		 IF(@rObtain >= @M1)
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=1
		 END
		 ELSE IF((@rObtain >= @M2 )AND (@rObtain < @M1))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=2
		 END
		 ELSE IF((@rObtain >= @M3)AND (@rObtain < @M2))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=3
		 END
		 ELSE IF((@rObtain >= @M4 )AND (@rObtain < @M3))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=4
		 END
		 ELSE IF((@rObtain >= @M5 )AND (@rObtain < @M4))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=5
		 END
		 ELSE IF((@rObtain >= @M6)AND (@rObtain < @M5))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=6
		 END
		 ELSE IF((@rObtain >= @M7)AND (@rObtain < @M6))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=7
		 END
		 ELSE IF((@rObtain >= @M8)AND (@rObtain < @M7))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=8
		 END
		 ELSE IF((@rObtain >= @M9)AND (@rObtain < @M8))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=9
		 END
		 ELSE IF((@rObtain >= @M10)AND (@rObtain < @M9))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=10
		 END


	return  @lGrade 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetdayNumber](@rDate nvarchar(20))
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDayNumber int
	 
	SELECT @lDayNumber = CASE DATENAME(WEEKDAY,@rDate)
		WHEN 'Sunday' THEN 1
		WHEN 'Monday' THEN 2
		WHEN 'Tuesday' THEN 3
		WHEN 'Wednesday' THEN 4
		WHEN 'Thursday' THEN 5
		WHEN 'Friday' THEN 6
		WHEN 'Saturday' THEN 7
	END
	
	return  @lDayNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetGradepoint](@rGrade nvarchar(20))
RETURNS   decimal(6,2) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lResultId decimal(6,2)
	if(@rGrade='A')
	BEGIN
		Set @lResultId =5
	ENd
	ELSE if(@rGrade='B')
	BEGIN
		set @lResultId=4
	END
	ELSE if(@rGrade='C')
	BEGIN
		set @lResultId=3
	END
	ELSE if(@rGrade='D')
	BEGIN
		set @lResultId=2
	END
	ELSE if(@rGrade='E')
	BEGIN
		set @lResultId=1
	END
	ELSE
		BEGIN
		set @lResultId=0
	END
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetHigherGrade](@rGrade nvarchar(10))
RETURNS   nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lResultId nvarchar(10)
	if(@rgrade='A2')
	BEGIN
		Set @lResultId ='A1'
	ENd
	if(@rgrade='B1')
	BEGIN
		set @lResultId='A2'
	END
	if(@rgrade='B2')
	BEGIN
		set @lResultId='B1'
	END
	if(@rgrade='C1')
	BEGIN
		set @lResultId='B2'
	END
	if(@rgrade='C2')
	BEGIN
		set @lResultId='C1'
	END
	if(@rgrade='D')
	BEGIN
		set @lResultId='C2'
	END
	 
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetHigherGradepoint](@rGradepoint decimal(6,2))
RETURNS   decimal(6,2) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lResultId decimal(6,2)
	if(@rGradepoint=9)
	BEGIN
		Set @lResultId =10
	ENd
	if(@rGradepoint=8)
	BEGIN
		set @lResultId=9
	END
	if(@rGradepoint=7)
	BEGIN
		set @lResultId=8
	END
	if(@rGradepoint=6)
	BEGIN
		set @lResultId=7
	END
	if(@rGradepoint=5)
	BEGIN
		set @lResultId=6
	END
	if(@rGradepoint=4)
	BEGIN
		set @lResultId=5
	END
	 
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetHighestDivisionGrade](@rDivisionId int,@rExamDetailId int)
RETURNS nvarchar(10) WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId nvarchar(10)
 SELECT @lResultId = ISNULL(min(SubjectGrade),'') FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
  WHERE RD.ExamDetailId = @rExamDetailId
  AND A.DivisionId = @rDivisionId AND ( (SubjectGrade IS NOT NULL) OR (SubjectGrade <> ''))
  
	RETURN  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fGetHighestDivisionMark](@rDivisionId int,@rExamDetailId int)
RETURNS [float] WITH EXECUTE AS CALLER
AS 
BEGIN
 DECLARE @lResultId float
 SELECT @lResultId = convert(decimal(10,2),ISNULL(MAX(Obtain),0)) FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
  WHERE RD.ExamDetailId = @rExamDetailId
  AND A.DivisionId = @rDivisionId
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fGetResultId](@rAcademicId bigint,@rExamId int)
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lResultId bigint
	IF(@rAcademicId <> 0)
		BEGIN
			SELECT @lResultId=Id FROM sAssessment.tResult WHERE AcademicId=@rAcademicId AND ExamId=@rExamId
		END
	ELSE
		BEGIN
			SET @lResultId=0
		END	
	return  @lResultId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sAssessment].[fGetResuultGradeCount](@rOrgId nvarchar(200),@rObtain nvarchar(100),@rExamId int,@rStrOrgMainGroupId nvarchar(max),@rStrOrgSubGroupId nvarchar(max),@rStrOrgId nvarchar(max),@rStrDepartmentId nvarchar(max),@rStrClassId nvarchar(max),@rOrgGroupBatchId int,@rClassId  int,@rDivisionId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lGradeCount int
	Declare @lGrade nvarchar(10)
	DECLARE @GradeSetId int
	 Declare @M1 nvarchar(20),@M2 nvarchar(20),@M3 nvarchar(20),@M4 nvarchar(20),@M5 nvarchar(20),@M6 nvarchar(20),@M7 nvarchar(20),@M8 nvarchar(20),@M9 nvarchar(20),@M10 nvarchar(20)	
	 
	Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)

	
	Declare @Temp Table
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2)
	)

	insert into @Temp(GradeCode,MinimumScore)

		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @M1=(Select MinimumScore from @Temp where Id=1) 
	 	 Set @M2=(Select MinimumScore from @Temp where Id=2) 
	 	 Set @M3=(Select MinimumScore from @Temp where Id=3) 
	 	 Set @M4=(Select MinimumScore from @Temp where Id=4) 
	     Set @M5=(Select MinimumScore from @Temp where Id=5) 
         Set @M6=(Select MinimumScore from @Temp where Id=6) 
	     Set @M7=(Select MinimumScore from @Temp where Id=7) 
	 	 Set @M8=(Select MinimumScore from @Temp where Id=8) 
	 	 Set @M9=(Select MinimumScore from @Temp where Id=9) 
		 Set @M10=(Select MinimumScore from @Temp where Id=10)

		 IF(@rObtain >= @M1)
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=1
		 END
		 ELSE IF((@rObtain >= @M2 )AND (@rObtain < @M1))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=2
		 END
		 ELSE IF((@rObtain >= @M3)AND (@rObtain < @M2))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=3
		 END
		 ELSE IF((@rObtain >= @M4 )AND (@rObtain < @M3))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=4
		 END
		 ELSE IF((@rObtain >= @M5 )AND (@rObtain < @M4))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=5
		 END
		 ELSE IF((@rObtain >= @M6)AND (@rObtain < @M5))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=6
		 END
		 ELSE IF((@rObtain >= @M7)AND (@rObtain < @M6))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=7
		 END
		 ELSE IF((@rObtain >= @M8)AND (@rObtain < @M7))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=8
		 END
		 ELSE IF((@rObtain >= @M9)AND (@rObtain < @M8))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=9
		 END
		 ELSE IF((@rObtain >= @M10)AND (@rObtain < @M9))
		 BEGIN
			Select @lGrade= GradeCode from @Temp where Id=10
		 END

Select @lGradeCount =
COUNT( distinct AcademicId)
 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId

		WHERE		
			ETM.Id=@rExamId
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND  R.ResultGrade = @lGrade
			AND CM.Id = @rClassId
			AND DM.Id = @rDivisionId
	return  @lGradeCount 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGetWeekdayNumber](@rDate nvarchar(20))
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDayNumber int
	 
	SELECT @lDayNumber = CASE DATENAME(WEEKDAY,@rDate)
		WHEN 'Sunday' THEN 0
		WHEN 'Monday' THEN 1
		WHEN 'Tuesday' THEN 2
		WHEN 'Wednesday' THEN 3
		WHEN 'Thursday' THEN 4
		WHEN 'Friday' THEN 5
		WHEN 'Saturday' THEN 6
	END
	
	return  @lDayNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGradeStringGet](@rGradeId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lGradeString  VARCHAR(MAX)

--SELECT @lGradeString = COALESCE(@lGradeString ,'') + '>= ' + CONVERT(VARCHAR(11),d.MinimumScore,106) + ' '  + d.GradeCode + ',' + d.GradeTitle + ';' 
--FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
--ORDER BY d.MinimumScore desc

--SELECT @lGradeString = COALESCE(@lGradeString ,'') + '>= ' + CONVERT(VARCHAR(11),d.MinimumScore,106) + ' '  + d.GradeCode + ';' 
--FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
--ORDER BY d.MinimumScore desc

SELECT @lGradeString = COALESCE(@lGradeString ,'') +   d.GradeTitle +  ','  + d.GradeCode + ';' 
FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
ORDER BY d.MinimumScore desc

RETURN @lGradeString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fGradeStringIndicatorGet](@rGradeId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lGradeString  VARCHAR(MAX)

--SELECT @lGradeString = COALESCE(@lGradeString ,'') + '>= ' + CONVERT(VARCHAR(11),d.MinimumScore,106) + ' '  + d.GradeCode + ',' + d.GradeTitle + ';' 
--FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
--ORDER BY d.MinimumScore desc

SELECT @lGradeString = COALESCE(@lGradeString ,'') +   d.GradeTitle +  ','  + d.GradeCode + ';' 
FROM sAssessment.tGradeSetDetail d WHERE GradeSetId = @rGradeId
ORDER BY d.MinimumScore desc

RETURN @lGradeString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fSubjectEmployeeGet](@rDivisionId int,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lEmployeeString  VARCHAR(MAX)

SELECT 
	@lEmployeeString = COALESCE(@lEmployeeString,'') + ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'')+ ',' 
	
	 
FROM 
	sHrm.tEmployeeMaster Emp 
	INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.EmployeeId = Emp.Id  
WHERE 
	TSD.SubjectId = @rSubjectId AND TSD.DivisionId = @rDivisionId AND  ISNULL(EMP.IsOtherUser,0) = 0

RETURN @lEmployeeString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fSubjectGradeGet](@rAcademicId bigint,@rExamId int,@rClassSubjectId int)
RETURNS [nvarchar](10) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rGrade nvarchar(10)
	select @rGrade=RD.SubjectGrade 
	from sAssessment.tResult R
			INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId 
			INNER JOIN sAssessment.tExamDetail ED ON RD.EXamDetailId = ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id AND CS.Id= @rClassSubjectId
	WHERE R.AcademicId = @rAcademicId AND R.ExamId = @rExamId

RETURN @rGrade
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAssessment].[fSubjectObtainGet](@rAcademicId bigint,@rExamId int,@rClassSubjectId int)
RETURNS decimal(5,2) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rObtain decimal(5,2)
	select @rObtain=RD.Obtain 
	from sAssessment.tResult R
			INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId 
			INNER JOIN sAssessment.tExamDetail ED ON RD.EXamDetailId = ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id AND CS.Id= @rClassSubjectId
	WHERE R.AcademicId = @rAcademicId AND R.ExamId = @rExamId

RETURN @rObtain
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAssessment].[fSubjectWiseGradeGet](@rAcademicId bigint,@rExamId int,@rActivityId int,@rClassSubjectId int,@rBatchId int,@rClassId int)
RETURNS nvarchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lGrade nvarchar(100)=''
  
	DECLARE @lMarks decimal(5,2), @lScore decimal(5,2),@lGradeSetId int, @lTotalActivityCount int , @lSubjectMaximum decimal(5,2)

	SELECT @lMarks = SUM(AIS.Marks) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lTotalActivityCount = COUNT(1) from sAssessment.tCCESubjectSubActivityExamScore AIS
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id
		INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId
		WHERE AIS.AcademicId = @rAcademicId AND AIS.ExamId = @rExamId AND SAM.Id = @rActivityId

	SELECT @lSubjectMaximum = ED.Maximum from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ED.ExamId = @rExamId AND ED.ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId

	SELECT @lGradeSetId = ED.GradeSetId from [sAssessment].[tExamDetail] ED
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		WHERE ExamId = @rExamId AND ClassSubjectId = @rClassSubjectId AND EM.BatchId = @rBatchId AND EM.ClassId = @rClassId
	
	SET @lScore = (@lMarks * 100) / (@lSubjectMaximum * @lTotalActivityCount)

	SELECT TOP 1 @lGrade = GradeCode
		FROM sAssessment.tGradeSetDetail
		WHERE MinimumScore <= @lScore AND GradesetId = @lGradeSetId
		ORDER BY MinimumScore DESC
	


	return  @lGrade
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fAbsentCountGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int, @rOrgId smallint , @rClassId int, @rDivisionId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	declare @lCount int=0
	declare @ldate date=CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	SELECT @lCount=
		(
 				Select count(A.Id) AS AcademicId FROM sAttendance.tStudentRegister SR 
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id  
					WHERE  
					  SR.AttendanceDate =@ldate
					AND SR.IsPresent = 0	  
					AND ((SR.AttendanceTypeId=1)) 
					AND (A.BatchId=@rBatchId)       
					AND A.DivisionId=Dm.Id
			        
		) 
		From sSetup.tDivisionMaster  DM 
		Where OrgId=@rOrgId 
		And ((Dm.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dm.ClassId=@rClassId) OR (@rClassId=0))

			 
 
	RETURN @lCount	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fAbsentDatesGet](@rFromDate date,@rToDate date, @rAttendanceTypeId tinyint,@rSubjectId int,@rAcademicId bigint)
RETURNS nvarchar(500) WITH EXECUTE AS CALLER
AS 
BEGIN
    declare @rAbsentDates nvarchar(500)
(Select 
			@rAbsentDates=COALESCE(@rAbsentDates+',','') + CONVERT(VARCHAR(10), SR.attendancedate, 103)
			 FROM 		
		    sAttendance.tStudentRegister SR 
			WHERE SR.AcademicId=@rAcademicId 
			AND SR.IsPresent=0
			AND SR.AttendanceTypeId=@rAttendanceTypeId
			AND (SR.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 		 
			AND ((SR.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0)))
			ORDER BY SR.attendancedate
			
			
    RETURN ISNULL(@rAbsentDates,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAttendance].[fAbsentDaysGet](@rForMonth tinyint,@rForYear smallint, @rAttendanceTypeId tinyint,@rSubjectId int,@rAcademicId bigint)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
    declare @rAbsentDays nvarchar(200)
(Select 
			@rAbsentDays=COALESCE(@rAbsentDays+',','') + cast(DATEPART(DAY,SR.attendancedate) AS nvarchar(2))
			 FROM 		
		    sAttendance.tStudentRegister SR -- SR.AttendanceDate=DM.CurrentDate
			WHERE SR.AcademicId=@rAcademicId 
			AND SR.IsPresent=0
			AND SR.AttendanceTypeId=@rAttendanceTypeId
			AND datepart(MONTH,SR.attendancedate) = @rForMonth
			AND datepart(Year,SR.attendancedate) = @rForYear			 
			AND ((SR.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0)))
			ORDER BY SR.attendancedate
			
			
    RETURN ISNULL(@rAbsentDays,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sAttendance].[fAttendanceAdmissionDateGet]( @rAdmissionDate date,@rAttendanceDate nvarchar(20),@rLeftDate date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDate nvarchar(20)
	
	
if isnull(@rStatus,'') = ''
BEGIN
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1
	BEGIN
		if(@rAdmissionDate > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'
			RETURN @rStatus
		END
		if(@rLeftDate <= @rAttendanceDate)
		BEGIN
			SET @rStatus='L'
			RETURN @rStatus
		END
		 
	 END	
	END	    
	RETURN @rStatus
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAttendance].[fAttendanceGet](@rAcademicId bigint,@rAttendanceTypeId tinyint,@rSubjectId int,@rFromDate date,@rToDate date)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lAttendanceDate  VARCHAR(MAX)
(SELECT @lAttendanceDate  = COALESCE(@lAttendanceDate ,'') + CONVERT(VARCHAR(6),SR.AttendanceDate,106) + ' , ' 
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	WHERE SA.AcademicId = @rAcademicId AND SR.IsPresent=0 
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					) order by AttendanceDate
					  
  SET @lAttendanceDate = LEFT(@lAttendanceDate, LEN(@lAttendanceDate) - 1)
    RETURN @lAttendanceDate 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fAttendanceTotalDayGet](@rAcademicId bigint,@rMonth int,@rYear int,@rPresent tinyint)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lCount int=0
	IF(@rPresent = 0)
	BEGIN
		SELECT @lCount = COUNT(SR.AttendanceDate)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		GROUP BY AttendanceDate
	END
	ELSE IF(@rPresent = 1)
    BEGIN
		SELECT @lCount = COUNT(SR.AcademicId)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		AND SR.IsPresent = 1
		GROUP BY SR.AcademicId
	END
    ELSE IF(@rPresent = 2)
    BEGIN
		SELECT @lCount = COUNT(SR.AcademicId)
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 1
		WHERE SA.AcademicId = @rAcademicId  
		AND DATEPART(MONTH,SR.AttendanceDate) = @rMonth
		AND DATEPART(YEAR,SR.AttendanceDate) = @rYear 
		AND SR.IsPresent = 0
		GROUP BY SR.AcademicId
	END
	RETURN @lCount 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fAttendanceWithRemarkGet](@rAcademicId bigint,@rAttendanceTypeId tinyint,@rSubjectId int,@rFromDate date,@rToDate date)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lAttendanceDate  VARCHAR(MAX)
(SELECT @lAttendanceDate  = COALESCE(@lAttendanceDate ,'') + CONVERT(VARCHAR(6),SR.AttendanceDate,106) + (case when SR.AttendanceRemark='' Then ''
	else ' (' + SR.AttendanceRemark + ')' end) + ' , ' 
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	WHERE SA.AcademicId = @rAcademicId AND SR.IsPresent=0 
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					) order by AttendanceDate
					  
  SET @lAttendanceDate = LEFT(@lAttendanceDate, LEN(@lAttendanceDate) - 1)
    RETURN @lAttendanceDate 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAttendance].[fGetAbsentDatesDateWise]
(
    @AcademicID BIGINT,
    @AttendanceTypeId SMALLINT,
    @FromDate DATE,
    @ToDate DATE,
	@SubjectId Int,
	@PeriodNo SmallInt
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @AbsentDates NVARCHAR(MAX);

    SELECT @AbsentDates = STUFF(
        (SELECT ',' + CONVERT(VARCHAR(10), AttendanceDate, 103)
         FROM sAttendance.tStudentRegister AS SR
         WHERE SR.AcademicID = @AcademicID
           AND SR.IsPresent = 0
           AND SR.AttendanceDate >= @FromDate
		   AND SR.AttendanceDate <= @ToDate
           AND SR.AttendanceTypeId = @AttendanceTypeId
		   AND (SR.SubjectId = @SubjectId OR @SubjectId = 0)
		   AND (SR.PeriodNo = @PeriodNo OR @PeriodNo = 0)
		   ORDER BY AttendanceDate
         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
        , 1, 1, '');

    RETURN @AbsentDates;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fHolidayForMonthGet](@rForMonth int,@rForYear int,@rBatchId int,@rDivisionId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
  DECLARE @day int,@day1 int,@day2 int,@str varchar(200)='',@lcount int=0,@OrderBy int=0
  
  --Select  COUNT(Id) from sActivity.tEventSchedule where  MONTH(FromDate)=8 and year(FromDate)= and BatchId=100100114 and  IsHoliday=1
	 
	Declare  @TempEventSchedule as table
	(
		Id int IDENTITY,
		 day5 int,
		 day6 int	
	) 
	Insert into @TempEventSchedule
	(
		day5,
		day6
	)
	Select 
		DATEPART(DD,FromDate) AS day5,
		DATEPART(DD,ToDate) AS day6
	From 
		sActivity.tEventSchedule ES
		INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	Where 
		IsHoliday=1 
		AND BatchId =@rBatchId 
		AND @rForMonth=DATEPART(MM,FromDate) 
		AND @rForYear<=DATEPART(YYYY,FromDate)  
		AND @rForYear>=DATEPART(YYYY,Todate)
		AND EA.SourceId = @rDivisionId
		AND EA.SourceTypeId=2005
	 
		
	 
	Select @lcount = MAX(Id) from @TempEventSchedule 
	 	 
Set @OrderBy=@OrderBy+1
	   
	While  @OrderBy <=@lcount
		BEGIN 
	 Select @day1=day5,@day2 = day6 from @TempEventSchedule WHERE ID = @OrderBy
	  while @day1<=@day2
	  BEGIN 
	  
			set @str = @str + convert(nvarchar,@day1) + ','  
			set @day1=@day1 + 1 
			
		END
		 
		Set @OrderBy = @OrderBy+1 		 
	END
	if isnull(@str,'')=''
	begin
		select @str=''
	end
	else
	begin		
		select @str=LEFT(@str,LEN(@str)-1)
	end
	return  @str
	--select @day1=DATEPART(DD,FromDate) 
	--from
	-- 	sActivity.tEventSchedule ES
	--	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	--where 
	--	IsHoliday=1 
	--	AND BatchId =@rBatchId 
	--	AND @rForMonth=DATEPART(MM,FromDate) 
	--	AND @rForYear<=DATEPART(YYYY,FromDate)  
	--	AND @rForYear>=DATEPART(YYYY,Todate)
	--	AND EA.SourceId = @rDivisionId
		
	--select 
	--	@day2=DATEPART(DD,ToDate) 
	--from 
	--	sActivity.tEventSchedule ES
	--	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleID = ES.Id 
	--where 
	--	IsHoliday=1  
	--	AND @rForMonth=DATEPART(MM,FromDate) 
	--	AND @rForYear<=DATEPART(YYYY,FromDate)  
	--	AND @rForYear>=DATEPART(YYYY,Todate)
	--	AND BatchId =@rBatchId
	--	AND EA.SourceId = @rDivisionId
	 
	--While @day1<=@day2
	--BEGIN
	--	select @str = @str + convert(varchar,@day1) + ','
	--	select @day1=@day1 + 1
	--END
	--if isnull(@str,'')=''
	--begin
	--	select @str=''
	--end
	--else
	--begin		
	--	select @str=LEFT(@str,LEN(@str)-1)
	--end
	--return  @lcount
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sAttendance].[fPresentAbsentGet](@rRollNo int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
	Declare @lIsPresent bit
  Select 
		@lIsPresent=ISpresent from 	sAttendance.tStudentRegister SA 
		INNER JOIN sStudent.tAcademic A ON SA.Academicid=A.Id
		Where A.RollNo=@rRollNo
    RETURN ISNULL(@lIsPresent,0) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fPresentCountGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int, @rOrgId smallint , @rClassId int  ,@rDivisionId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	declare @lCount int=0
	declare @ldate date=CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	SELECT @lCount=
		(
 				Select count(A.Id) AS AcademicId FROM sAttendance.tStudentRegister SR 
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id  
					WHERE  
					  SR.AttendanceDate =@ldate
					AND SR.IsPresent = 1	  
					AND ((SR.AttendanceTypeId=1)) 
					AND (A.BatchId=@rBatchId)       
					AND A.DivisionId=Dm.Id
			        
		) 
		From sSetup.tDivisionMaster  DM 
		Where OrgId=@rOrgId 
		And ((Dm.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dm.ClassId=@rClassId) OR (@rClassId=0))

			 
 
	RETURN @lCount	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fSubjectTeacherGet](@rDivisionId int,@rSubjectId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lName nvarchar(200)=''
  
	Select @lName=@lName + COALESCE( Em.FirstName + ' ' +Em.LastName + '/ ' ,'') 
	FROM sHrm.tEmployeeMaster EM 
	 
	INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.EmployeeId= EM.Id 
	
	WHERE TSD.DivisionId = @rDivisionId  AND TSD.SubjectId =@rSubjectId AND  ISNULL(EM.IsOtherUser,0) = 0
	
	if isnull(@lName,'')=''
	begin
		select @lName=''
	end	
	else
	begin		
		select @lName=LEFT(@lName,LEN(@lName)-1)
	end
	return  @lName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fWeekHOffGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rClassId bigint,@rDivisionId int, @rStatus nvarchar(10),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
IF ISNULL(@rStatus,'') = ''
BEGIN
	DECLARE @lWeekOff nvarchar(20)
	Declare @WeekNumber int,@StudentSecondWeekOffRule int,@StudentFirstWeekOffRule int
	DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
	
	SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
	
	IF exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001)
	BEGIN
		 Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rClassId AND SourceTypeId=2001
		 Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rClassId AND SourceTypeId=2001  
	END 
	Else
	BEGIN
		 Select @lWeekDay1 = StudentFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
		 Select @lWeekDay2 = StudentSecondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	END
	   
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
	  
	if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001)
	BEGIN 
		 Select @StudentFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001
		 Select @StudentSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001
	       
	END
	Else
	BEGIN
		 Select @StudentFirstWeekOffRule = StudentFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
		 Select @StudentSecondWeekOffRule = StudentSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	    
	END
	
	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId AND EA.SourceTypeId = 2005 WHERE ES.BatchId = @rBatchId AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	BEGIN
		 SET @rStatus = 'H'	
	END
	
	-- Student First Week Off Rule
	if @StudentFirstWeekOffRule = 1 
	BEGIN
		if(@lWeekOff = @lWeekDay1)
		BEGIN
			Set @rStatus = 'W'
		END		
	END
	Else if @StudentFirstWeekOffRule = 2 
	BEGIN				     
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 4
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 5
	BEGIN
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 6
	BEGIN
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 7
	BEGIN
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 8
	BEGIN
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 9
	BEGIN
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	--Add StudentFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @StudentFirstWeekOffRule = 10
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	-- Student Second Week Off Rule   
	if @StudentSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @rStatus = 'W'
		END			
	END
	Else if @StudentSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN			 
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 3
	BEGIN
		
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 4
	BEGIN
	
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 5
	BEGIN
	
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 6
	BEGIN
	
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 7
	BEGIN
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 8
	BEGIN
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 9
	BEGIN
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	--Add StudentSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @StudentSecondWeekOffRule = 10
	BEGIN
	
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	END
	RETURN @rStatus	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sAttendance].[fWeekHOffHolidayGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDivisionId bigint,@rStatus nvarchar(10),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
if isnull(@rStatus,'') = ''
BEGIN
	DECLARE @lDate nvarchar(20)  
	DECLARE @lWeekOff nvarchar(100)
	
	
   SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
 
	
  
	IF ISDATE (@lDate)=1
	BEGIN
	 
	 DECLARE @tbl TABLE(tid int identity(1,1),id int)
	 INSERT INTO @tbl
	SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS dgid FROM
	(
		SELECT CAST('<XMLRoot><RowData>' + REPLACE(weekoffs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
		FROM sSetup.tOrganizationMaster where Id = @rOrgid
	) t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
	 
	 
	SET @lWeekOff = [sAssessment].[fGetWeekdayNumber](@lDate)
     IF  EXISTS(SELECT 1 from @tbl where @lWeekOff in (id)) 
		 BEGIN
				SET @rStatus = 'W'
				RETURN @rStatus	
		END	 
		
	
	 IF   EXISTS(SELECT  1
		 from sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId
			WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDivisionId) OR (@rDivisionId=0)) AND 
			(@lDate BETWEEN ES.FromDate AND ES.ToDate)
		 
			 AND ES.IsHoliday=1)
	 BEGIN
		SET @rStatus = 'H'	
		RETURN @rStatus		
	 END

	 END
	END	
	
	RETURN @rStatus	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sBiometric].[fBiometricTempMonthTransGet]  (
    @rOrgId int ,
	@rDeptId int , 
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rEmployeeId bigint
)

RETURNS @TempMonthTrans TABLE   
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
 )  
AS
Begin


  INSERT INTO @TempMonthTrans
SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt),01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 ELSE D01 END ,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S  
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 ELSE D02 END ,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 ELSE D03 END ,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S 
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 ELSE D04 END,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 ELSE D05 END ,D05_IN,D05_OUT,D05_O,D01_L,D05_T,D05_E,D05_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN D06 = 'W' OR D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN D06 = 'H' OR D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 ELSE D06 END,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S  
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN D07 = 'W' OR D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN D07 = 'H' OR D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 ELSE D07 END,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN D08 = 'W' OR D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN D08 = 'H' OR D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 ELSE D08 END ,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN D09 = 'W' OR D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN D09 = 'H' OR D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 ELSE D09 END ,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN D10 = 'W' OR D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN D10 = 'H' OR D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 ELSE D10 END ,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN D11 = 'W' OR D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN D11 = 'H' OR D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 ELSE D11 END ,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN D12 = 'W' OR D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN D12 = 'H' OR D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 ELSE D12 END ,	D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN D13 = 'W' OR D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN D13 = 'H' OR D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 ELSE D13 END ,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN D14 = 'W' OR D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN D14 = 'H' OR D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 ELSE D14 END ,	D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN D15 = 'W' OR D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN D15 = 'H' OR D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 ELSE D15 END ,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN D16 = 'W' OR D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN D16 = 'H' OR D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 ELSE D16 END ,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN D17 = 'W' OR D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN D17 = 'H' OR D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 ELSE D17 END ,	D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN D18 = 'W' OR D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN D18 = 'H' OR D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 ELSE D18 END ,	D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN D19 = 'W' OR D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN D19 = 'H' OR D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 ELSE D19 END ,	D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN D20 = 'W' OR D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN D20 = 'H' OR D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 ELSE D20 END ,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN D21 = 'W' OR D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN D21 = 'H' OR D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 ELSE D21 END ,	D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN D22 = 'W' OR D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN D22 = 'H' OR D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 ELSE D22 END ,	D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN D23 = 'W' OR D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN D23 = 'H' OR D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 ELSE D23 END ,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN D24 = 'W' OR D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN D24 = 'H' OR D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 ELSE D24 END ,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 ELSE D25 END ,	D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN D26 = 'W' OR D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN D26 = 'H' OR D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 ELSE D26 END ,	D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN D27 = 'W' OR D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN D27 = 'H' OR D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 ELSE D27 END ,	D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN D28 = 'W' OR D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN D28 = 'H' OR D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 ELSE D28 END ,	D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO @TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN D29 = 'W' OR D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN D29 = 'H' OR D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 ELSE D29 END ,	D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
					  OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO @TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN D30 = 'W' OR D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN D30 = 'H' OR D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 ELSE D30 END ,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO @TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN D31 = 'W' OR D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN D31 = 'H' OR D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 ELSE D31 END ,	D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	--END

	
	return

End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sBiometric].[fcalcHour](@Minuts INT)
RETURNS varchar(10)
AS
BEGIN
     DECLARE @MyOutput     varchar(10)
    DECLARE @HO    INT
    DECLARE @MI        INT
    DECLARE @TIM    VARCHAR(10)

    SET @HO =  (@MINUTS / 60)
    SET @MI =(@MINUTS % 60)
    
    if @Minuts >= 0
    Begin
        IF @HO < 10 
        BEGIN
            IF (@MI) < 10 
                SET @TIM = '0' + CAST(ABS(@HO) AS VARCHAR) +':0' + CAST(@MI AS VARCHAR)
            ELSE
                SET @TIM =  '0' +  CAST(ABS(@HO) AS VARCHAR) + ':' + CAST(@MI AS VARCHAR)
        END
        ELSE
        BEGIN
            IF @MI < 10 
                SET @TIM = CAST(ABS(@HO) AS VARCHAR) + ':0' + CAST(@MI AS VARCHAR)
            ELSE
                SET @TIM = CAST(ABS(@HO) AS VARCHAR) + ':' + CAST(@MI AS VARCHAR)
        END
        SET @MyOutput = @TIM
        RETURN @MyOutput
    End
    Else
    Begin
        IF abs(@HO) < 10 
        BEGIN
            IF abs(@MI) < 10 
                SET @TIM = '0' + CAST(ABS(@HO) AS VARCHAR) +':0' + CAST(abs(@MI) AS VARCHAR)
            ELSE
                SET @TIM =  '0' +  CAST(ABS(@HO) AS VARCHAR) + ':' + CAST(abs(@MI) AS VARCHAR)
        END
        ELSE
        BEGIN
            IF abs(@MI) < 10 
                SET @TIM = CAST(ABS(@HO) AS VARCHAR) + ':0' + CAST(ABS(@MI) AS VARCHAR)
            ELSE
                SET @TIM = CAST(ABS(@HO) AS VARCHAR) + ':' + CAST(ABS(@MI) AS VARCHAR)
        END
        SET @MyOutput = '-' + @TIM
        RETURN @MyOutput

    End


RETURN @MyOutput
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sBiometric].[fcalcMINI](@str as nvarchar(10))
RETURNS INT
AS
BEGIN

Declare @ho nvarchar(10)
    declare @mins nvarchar(10)
    declare @minutes int
DECLARE @MyOutput     INT
    
 --  if len(@str) > 5 
	--	begin
	--	 set @ho = substring(@str, 1, 3)
	--	 set @mins = substring(@str, 5, 2)
	--	end
	--else
	--	begin
	--	 set @ho = substring(@str, 1, 2)
	--	 set @mins = substring(@str, 4, 2)
	--	end	
 --   set @minutes = @mins + (@ho * 60)
    
    set @ho = SUBSTRING( @str,1,CHARINDEX(':',@str)-1) --Left(@OTHour,2)--substring(@str, 1, 2)
    --set @mins = right(@str, 2)
    set @mins = SUBSTRING( @str,CHARINDEX(':',@str)+1,2)
    set @minutes = @mins + (@ho * 60)
    
    SET @MyOutput = @minutes
    RETURN @MyOutput
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeCLTypeGet](@rMonth int,@rYear Int,@rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
Declare @Days int 
 select @Days=sCommon.fGetDaysInMonth(@rMonth,@rYear)
DECLARE @lLeaveType nvarchar(100)
DECLARE @StartDate date=convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'01'
 Declare @ToDate date 	
 
if @Days=31
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'31'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=30
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'30'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=29
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'29'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 

if @Days=28
BEGIN
	Set @ToDate =convert(nvarchar(10),@rYear)+'-'+convert(nvarchar(10),@rMonth)+'-'+'28'

	SELECT @lLeaveType=Stuff (( select ',' + Convert(nvarchar(20),day(L.FromDate))
	FROM 
	sHrm.tLeave L 
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE 
	L.StatusId = 550 
	AND L.EmployeeId = @rEmployeeId 
	AND @StartDate<=L.FromDate 
	AND @ToDate>=L.ToDate	
      FOR XML PATH('')  
     ),1,1,'')	
     
END 
RETURN  ISNULL(@lLeaveType,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeLateCountGet](@rEmployeeId bigint, @rMonth int, @rYear int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lResult int=0
	SELECT @lResult=Count_Late FROM sBiometric.tMonthTrans WHERE EmployeeId=@rEmployeeId AND MONTH(Attn_Dt)=@rMonth AND YEAR(Attn_Dt)=@rYear AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	RETURN  @lResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeLeaveTypeGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lLeaveType nvarchar(200)=''
SELECT @lLeaveType=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
FROM 
sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE 
L.StatusId = 550 
AND L.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN L.FromDate AND L.ToDate
RETURN  ISNULL(@lLeaveType,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeLeaveTypePendingGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lLeaveType nvarchar(200)=''
SELECT @lLeaveType=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
FROM 
sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE 
L.StatusId = 549 
AND L.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN L.FromDate AND L.ToDate
RETURN  ISNULL(@lLeaveType,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeOnLeaveGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult nvarchar(200)=''
SELECT @lResult = L.Id FROM sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE (L.StatusId = 549 OR L.StatusId = 550)
AND L.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN L.FromDate AND L.ToDate
RETURN  ISNULL(@lResult,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sBiometric].[fEmployeeTravelGet](@rDate date, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lEmployeeTravel nvarchar(200)=''
SELECT @lEmployeeTravel = 'Travel'
FROM 
sHrm.tEmployeeTravel ET 
WHERE 
ET.StatusId = 642 
AND ET.EmployeeId = @rEmployeeId 
AND @rDate BETWEEN ET.TravelFromDate AND ET.TravelToDate
RETURN  ISNULL(@lEmployeeTravel,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sBiometric].[fTimeConversion](@rValue nvarchar(10),@rFlag bit)
RETURNS [nvarchar](10) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @Result nvarchar(10)
	IF @rFlag = 0 -- Time to Decimal
		BEGIN
			SET @Result = cast(datepart(hour, @rValue) + datepart(minute, @rValue) / 60.00 as decimal(10, 2))
		END
	ELSE -- Decimal To Time
		BEGIN
			SET @Result = RIGHT('00' + CONVERT(varchar(2),FLOOR(@rValue)),2) + ':' + RIGHT('00' + CONVERT(varchar(2),FLOOR(((@rValue-FLOOR(@rValue))*60))),2)
		END
	RETURN  ISNULL(@Result,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sCertificate].[fBonafideCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdhaarNumber NVARCHAR(20),
        @AdmissionDate DATE,
        @AdmissionStandard NVARCHAR(100),
        @AffiliationType NVARCHAR(50),
        @Batch NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @BirthState NVARCHAR(150),
        @BonafideDate DATE,
        @BonafiedReason NVARCHAR(255),
        @Caste NVARCHAR(100),
        @Category NVARCHAR(50),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @Class NVARCHAR(200),
        @ClassName NVARCHAR(100),
        @Code NVARCHAR(20),
        @ColumnList NVARCHAR(MAX),
        @DateOfBirth DATE,
        @DegreeAwarded NVARCHAR(100),
        @DepartmentName NVARCHAR(100),
        @District NVARCHAR(150),
        @Divisionname NVARCHAR(100),
        @DivisionOrder SMALLINT,
        @DOBInWords NVARCHAR(150),
        @FatherName NVARCHAR(100),
        @FirstName NVARCHAR(100),
        @Gender NVARCHAR(20),
        @LastName NVARCHAR(100),
        @LetterHeadMargin NVARCHAR(50),
        @MiddleName NVARCHAR(100),
        @MotherName NVARCHAR(100),
        @Name NVARCHAR(255),
        @Nationality NVARCHAR(50),
        @Number INT,
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
        @PermanentCity NVARCHAR(50),
        @PermanentContactNo NVARCHAR(20),
        @PermanentCountry NVARCHAR(50),
        @PermanentState NVARCHAR(50),
        @PermanentStreetOne NVARCHAR(150),
        @PermanentStreetThree NVARCHAR(150),
        @PermanentStreetTwo NVARCHAR(150),
        @PermanentZipCode NVARCHAR(20),
        @PresentCity NVARCHAR(50),
        @PresentContactNo NVARCHAR(20),
        @PresentCountry NVARCHAR(50),
        @PresentState NVARCHAR(50),
        @PresentStreetOne NVARCHAR(150),
        @PresentStreetThree NVARCHAR(150),
        @PresentStreetTwo NVARCHAR(150),
        @PresentZipCode NVARCHAR(20),
        @PrincipalSignature NVARCHAR(max),
        @ReceiptNo NVARCHAR(MAX), 	
        @RecordStatusId SMALLINT,
        @RegistrationDetail NVARCHAR(200),
        @ReligionName NVARCHAR(50),
        @ReportOrgTitle NVARCHAR(200),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @StudentPhoto NVARCHAR(MAX),
        @SubCaste NVARCHAR(100),
        @Taluka NVARCHAR(150),
        @LocalName NVARCHAR(100),
        @PENNo BIGINT,
        @SUID NVARCHAR(50),
		@Remark NVARCHAR(MAX), --added by dhananjay for mantis - 38238
		@UIDNumber NVARCHAR(100), --Mantis - 38768
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10),
		@MrMiss NVARCHAR(10),
		@SonDaughter NVARCHAR(10),
		@LeftDate DATE
    -- Fetch the values from the database
    SELECT 
        @AdhaarNumber = ISNULL(AdhaarNumber, ''),
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @AdmissionStandard = ISNULL(AdmissionStandard, ''),
        @AffiliationType = ISNULL(AffiliationType, ''),
        @Batch = ISNULL(Batch, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @BirthState = ISNULL(BirthState, ''),
        @BonafideDate = ISNULL(BonafideDate, ''),
        @BonafiedReason = ISNULL(BonafiedReason, ''),
        @Caste = ISNULL(Caste, ''),
        @Category = ISNULL(Category, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @Class = ISNULL(Class, ''),
        @ClassName = ISNULL(ClassName, ''),
        @Code = ISNULL(Code, ''),
        @ColumnList = ISNULL(ColumnList, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DegreeAwarded = ISNULL(DegreeAwarded, ''),
        @DepartmentName = ISNULL(DepartmentName, ''),
        @District = ISNULL(District, ''),
        @Divisionname = ISNULL(Divisionname, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
        @DOBInWords = ISNULL(DOBInWords, ''),
        @FatherName = ISNULL(FatherName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @Gender = ISNULL(Gender, ''),
        @LastName = ISNULL(LastName, ''),
        @LetterHeadMargin = ISNULL(LetterHeadMargin, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @MotherName = ISNULL(MotherName, ''),
        @Name = ISNULL(Name, ''),
        @Nationality = ISNULL(Nationality, ''),
        @Number = ISNULL(Number, 0),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @PermanentCity = ISNULL(PermanentCity, ''),
        @PermanentContactNo = ISNULL(PermanentContactNo, ''),
        @PermanentCountry = ISNULL(PermanentCountry, ''),
        @PermanentState = ISNULL(PermanentState, ''),
        @PermanentStreetOne = ISNULL(PermanentStreetOne, ''),
        @PermanentStreetThree = ISNULL(PermanentStreetThree, ''),
        @PermanentStreetTwo = ISNULL(PermanentStreetTwo, ''),
        @PermanentZipCode = ISNULL(PermanentZipCode, ''),
        @PresentCity = ISNULL(PresentCity, ''),
        @PresentContactNo = ISNULL(PresentContactNo, ''),
        @PresentCountry = ISNULL(PresentCountry, ''),
        @PresentState = ISNULL(PresentState, ''),
        @PresentStreetOne = ISNULL(PresentStreetOne, ''),
        @PresentStreetThree = ISNULL(PresentStreetThree, ''),
        @PresentStreetTwo = ISNULL(PresentStreetTwo, ''),
        @PresentZipCode = ISNULL(PresentZipCode, ''),
        @PrincipalSignature = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("PrincipalSignature")))', 'NVARCHAR(MAX)'),''),
        @ReceiptNo = ISNULL(ReceiptNo, ''),
        @RecordStatusId = ISNULL(RecordStatusId, 0),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @ReligionName = ISNULL(ReligionName, ''),
        @ReportOrgTitle = ISNULL(ReportOrgTitle, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''),
        @SubCaste = ISNULL(SubCaste, ''),
        @Taluka = ISNULL(Taluka, ''),
        @LocalName = ISNULL(LocalName, ''),
        @PENNo = ISNULL(PENNo, 0),
        @SUID = ISNULL(SUID, ''),
		@Remark = ISNULL(Remark, ''), --added by dhananjay for mantis - 38238
		@UIDNumber = ISNULL(UIDNumber, ''), --Mantis - 38768
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],''),
		@MrMiss = ISNULL([Mr-Miss],''),
		@SonDaughter = ISNULL([Son-Daughter],''),
		@LeftDate = ISNULL(LeftDate, '')
    FROM 
        sCertificate.vPrintTemplateBonafideCertificate 
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[AdhaarNumber]', @AdhaarNumber);
    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[AdmissionStandard]', @AdmissionStandard);
    SET @Template = REPLACE(@Template, '[AffiliationType]', @AffiliationType);
    SET @Template = REPLACE(@Template, '[Batch]', @Batch);
    SET @Template = REPLACE(@Template, '[BirthPlace]', @BirthPlace);
    SET @Template = REPLACE(@Template, '[BirthState]', @BirthState);
    SET @Template = REPLACE(@Template, '[BonafideDate]', CONVERT(NVARCHAR, @BonafideDate, 103));
    SET @Template = REPLACE(@Template, '[BonafiedReason]', @BonafiedReason);
    SET @Template = REPLACE(@Template, '[Caste]', @Caste);
    SET @Template = REPLACE(@Template, '[Category]', @Category);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]', @CertificateHeaderA4);
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[Class]', @Class);
    SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[ColumnList]', @ColumnList);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[DegreeAwarded]', @DegreeAwarded);
    SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);
    SET @Template = REPLACE(@Template, '[District]', @District);
    SET @Template = REPLACE(@Template, '[Divisionname]', @Divisionname);
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[DOBInWords]', @DOBInWords);
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
    SET @Template = REPLACE(@Template, '[Gender]', @Gender);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
    SET @Template = REPLACE(@Template, '[LetterHeadMargin]', @LetterHeadMargin);
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[MotherName]', @MotherName);
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Nationality]', @Nationality);
    SET @Template = REPLACE(@Template, '[Number]', CAST(@Number AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[PermanentCity]', @PermanentCity);
    SET @Template = REPLACE(@Template, '[PermanentContactNo]', @PermanentContactNo);
    SET @Template = REPLACE(@Template, '[PermanentCountry]', @PermanentCountry);
    SET @Template = REPLACE(@Template, '[PermanentState]', @PermanentState);
    SET @Template = REPLACE(@Template, '[PermanentStreetOne]', @PermanentStreetOne);
    SET @Template = REPLACE(@Template, '[PermanentStreetThree]', @PermanentStreetThree);
    SET @Template = REPLACE(@Template, '[PermanentStreetTwo]', @PermanentStreetTwo);
    SET @Template = REPLACE(@Template, '[PermanentZipCode]', @PermanentZipCode);
    SET @Template = REPLACE(@Template, '[PresentCity]', @PresentCity);
    SET @Template = REPLACE(@Template, '[PresentContactNo]', @PresentContactNo);
    SET @Template = REPLACE(@Template, '[PresentCountry]', @PresentCountry);
    SET @Template = REPLACE(@Template, '[PresentState]', @PresentState);
    SET @Template = REPLACE(@Template, '[PresentStreetOne]', @PresentStreetOne);
    SET @Template = REPLACE(@Template, '[PresentStreetThree]', @PresentStreetThree);
    SET @Template = REPLACE(@Template, '[PresentStreetTwo]', @PresentStreetTwo);
    SET @Template = REPLACE(@Template, '[PresentZipCode]', @PresentZipCode);
    SET @Template = REPLACE(@Template, '[PrincipalSignature]', @PrincipalSignature);
    SET @Template = REPLACE(@Template, '[ReceiptNo]', @ReceiptNo);
    SET @Template = REPLACE(@Template, '[RecordStatusId]', CAST(@RecordStatusId AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
    SET @Template = REPLACE(@Template, '[ReligionName]', @ReligionName);
    SET @Template = REPLACE(@Template, '[ReportOrgTitle]', @ReportOrgTitle);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[StudentPhoto]', @StudentPhoto);
    SET @Template = REPLACE(@Template, '[SubCaste]', @SubCaste);
    SET @Template = REPLACE(@Template, '[Taluka]', @Taluka);
    SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);
    SET @Template = REPLACE(@Template, '[PENNo]', CAST(@PENNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SUID]', @SUID);
	SET @Template = REPLACE(@Template ,'[Remark]', @Remark);--added by dhananjay for mantis - 38238
	SET @Template = REPLACE(@Template ,'[UIDNumber]', @UIDNumber);  --Mantis - 38768
	SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
	SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
	SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
	SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);
	SET @Template = REPLACE(@Template ,'[Mr-Miss]', @MrMiss);
	SET @Template = REPLACE(@Template ,'[Son-Daughter]', @SonDaughter);
	SET @Template = REPLACE(@Template, '[LeftDate]', CONVERT(NVARCHAR, @LeftDate, 103));

    RETURN @Template;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCertificate].[fCharacterCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdmissionDate DATE,
        @Batch NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @Caste NVARCHAR(100),
        @CertificateHeaderA4 NVARCHAR(MAX),
		@characterDate DATE,
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @Class NVARCHAR(200),
        @ClassOnly NVARCHAR(100),
        @Code NVARCHAR(20),
        @DateOfBirth DATE,
        @District NVARCHAR(150),
        @DivisionOrder SMALLINT,
        @DOBInWords NVARCHAR(150),
        @FatherName NVARCHAR(100),
        @Name NVARCHAR(255),
        @Number INT,
		@OrgAddress NVARCHAR(202),
        @OrgLogo NVARCHAR(MAX),
        @OrgName NVARCHAR(100),
        @PhoneNo NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
        @ReportOrgTitle NVARCHAR(200),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @StudentPhoto NVARCHAR(MAX),
        @SubCaste NVARCHAR(100),
        @Taluka NVARCHAR(150),
        @LocalName NVARCHAR(100),
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10)

    ---- Fetch the values from the database
    SELECT 
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @Batch = ISNULL(Batch, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @Caste = ISNULL(Caste, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
		@characterDate = ISNULL(characterDate, ''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @Class = ISNULL(Class, ''),
        @ClassOnly = ISNULL(ClassOnly, ''),
        @Code = ISNULL(Code, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @District = ISNULL(District, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
        @DOBInWords = ISNULL(DOBInWords, ''),
        @FatherName = ISNULL(FatherName, ''),
        @Name = ISNULL(Name, ''),
        @Number = ISNULL(Number, 0),
		@OrgAddress = ISNULL(OrgAddress, 0),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgName = ISNULL(OrgName, ''),
        @PhoneNo = ISNULL(PhoneNo, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @ReportOrgTitle = ISNULL(ReportOrgTitle, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''),
        @SubCaste = ISNULL(SubCaste, ''),
        @Taluka = ISNULL(Taluka, ''),
        @LocalName = ISNULL(LocalName, ''),
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],'')

    FROM 
        sCertificate.vPrintTemplateCharacterCertificate
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId

    ---- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[Batch]', @Batch);
    SET @Template = REPLACE(@Template, '[BirthPlace]', @BirthPlace);
    SET @Template = REPLACE(@Template, '[Caste]', @Caste);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]',  @CertificateHeaderA4);
	SET @Template = REPLACE(@Template, '[characterDate]', CONVERT(NVARCHAR, @characterDate, 103));
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[Class]', @Class);
    SET @Template = REPLACE(@Template, '[ClassOnly]', @ClassOnly);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[District]', @District);
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[DOBInWords]', @DOBInWords);
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Number]', CAST(@Number AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[OrgAddress]', @OrgAddress);
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgName]', @OrgName);
    SET @Template = REPLACE(@Template, '[PhoneNo]', @PhoneNo);
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
    SET @Template = REPLACE(@Template, '[ReportOrgTitle]', @ReportOrgTitle);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[StudentPhoto]', @StudentPhoto);
    SET @Template = REPLACE(@Template, '[SubCaste]', @SubCaste);
    SET @Template = REPLACE(@Template, '[Taluka]', @Taluka);
    SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);
	SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
	SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
	SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
	SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);

    RETURN @Template;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCertificate].[fFirstTrialCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdmissionDate DATE,
		@BirthDateInWord NVARCHAR(150),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @Class NVARCHAR(200),
        @ClassName NVARCHAR(100),
        @Code NVARCHAR(20),
        @DateOfBirth DATE,
        @DivisionOrder SMALLINT,
		@Exam NVARCHAR(54),
		@ExamCentre NVARCHAR(100),
		@ExamYear NVARCHAR(20),
        @FatherName NVARCHAR(100),
		@FirstTrialDate DATE,
        @Name NVARCHAR(300),
        @Number INT,
		@OrgAddress NVARCHAR(152),
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
        @PhoneNo NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
		@Remark NVARCHAR(100),
        @ReportOrgTitle NVARCHAR(200),
        @RollNo INT,
		@SeatNo NVARCHAR(50),
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @StudentPhoto NVARCHAR(MAX),
        @SUID NVARCHAR(50),
		@Surname NVARCHAR(100),
		@Trial NVARCHAR(20),
		@LocalName NVARCHAR(100),
		@DepartmentName NVARCHAR(100), --add for mantis : 0040988
		@LastExamName NVARCHAR(150), --add for mantis : 0041177
		@ObtainedMarkInLastExam NVARCHAR(100), --add for mantis : 0041177
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10),
		@MrMiss NVARCHAR(10),
		@SonDaughter NVARCHAR(10),
		@HimHer NVARCHAR(10)
    -- Fetch the values from the database
    SELECT 

        @AdmissionDate = ISNULL(AdmissionDate, ''),
		@BirthDateInWord = ISNULL(BirthDateInWord, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @Class = ISNULL(Class, ''),
        @ClassName = ISNULL(ClassName, ''),
        @Code = ISNULL(Code, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
		@Exam = ISNULL(Exam, ''),
		@ExamCentre = ISNULL(ExamCentre, ''),
		@ExamYear = ISNULL(ExamYear, ''),
        @FatherName = ISNULL(FatherName, ''),
		@FirstTrialDate = ISNULL(FirstTrialDate, ''),
        @Name = ISNULL(Name, ''),
        @Number = ISNULL(Number, 0),
		@OrgAddress = ISNULL(OrgAddress, ''),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @PhoneNo = ISNULL(PhoneNo, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
		@Remark = ISNULL(Remark, ''),
        @ReportOrgTitle = ISNULL(ReportOrgTitle, ''),
        @RollNo = ISNULL(RollNo, 0),
		@SeatNo = ISNULL(SeatNo, ''),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @StudentPhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("StudentPhoto")))', 'NVARCHAR(MAX)'),''),
        @SUID = ISNULL(SUID, ''),
		@Surname  = ISNULL(Surname, ''),
		@Trial = ISNULL(Trial, ''),
		@LocalName = ISNULL(LocalName, ''),
		@DepartmentName = ISNULL(DepartmentName, ''), --add for mantis : 0040988
		@LastExamName = ISNULL(LastExamName, ''), --add for mantis : 0041177
		@ObtainedMarkInLastExam = ISNULL(ObtainedMarkInLastExam, ''), --add for mantis : 0041177
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],''),
		@MrMiss = ISNULL([Mr.-Miss],''),
		@SonDaughter = ISNULL([Son-Daughter],''),
		@HimHer = ISNULL([Him-Her],'')
		
    FROM 
        sCertificate.vPrintTemplateFirstTrialCertificate
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId

    -- Replace placeholders in the template with actual values

    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
	SET @Template = REPLACE(@Template, '[BirthDateInWord]', @BirthDateInWord);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]',  @CertificateHeaderA4);
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[Class]', @Class);
    SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[Exam]', @Exam);
	SET @Template = REPLACE(@Template, '[ExamCentre]', @ExamCentre);
	SET @Template = REPLACE(@Template, '[ExamYear]', @ExamYear);
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
	SET @Template = REPLACE(@Template, '[FirstTrialDate]', CONVERT(NVARCHAR, @FirstTrialDate, 103));
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Number]', CAST(@Number AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[OrgAddress]', @OrgAddress);
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[PhoneNo]', @PhoneNo);
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
	SET @Template = REPLACE(@Template, '[Remark]', @Remark);
    SET @Template = REPLACE(@Template, '[ReportOrgTitle]', @ReportOrgTitle);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[SeatNo]', @SeatNo);
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[StudentPhoto]', @StudentPhoto);
    SET @Template = REPLACE(@Template, '[SUID]', @SUID);
	SET @Template = REPLACE(@Template, '[Surname]', @Surname);
	SET @Template = REPLACE(@Template, '[Trial]', @Trial);
	SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);
	SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);--add for mantis : 0040988
	SET @Template = REPLACE(@Template, '[LastExamName]', @LastExamName);--add for mantis : 0041177
	SET @Template = REPLACE(@Template, '[ObtainedMarkInLastExam]', @ObtainedMarkInLastExam);--add for mantis : 0041177
	SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
	SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
	SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
	SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);
	SET @Template = REPLACE(@Template ,'[Mr.-Miss]', @MrMiss);
	SET @Template = REPLACE(@Template ,'[Son-Daughter]', @SonDaughter);
	SET @Template = REPLACE(@Template ,'[Him-Her]', @HimHer);


    RETURN @Template;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sCertificate].[fLeavingCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)	
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        @AdhaarNumber NVARCHAR(20),
        @AdmissionDate DATE,
        @AdmissionStandard NVARCHAR(100),
		@AnyConcession NVARCHAR(100),
		@BankAccountNumber NVARCHAR(20),
		@BankIFSCCode NVARCHAR(20),
		@BankName NVARCHAR(20),
		@BatchDate DATE,
		@BatchName NVARCHAR(100),
		@BirthCountry NVARCHAR(150),
		@DOBInWord NVARCHAR(150),
        @BirthDistrict NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @BirthState NVARCHAR(150),
		@BirthTaluka NVARCHAR(150),
		@Caste NVARCHAR(100),
        @CasteCategory NVARCHAR(50),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @ClassName NVARCHAR(100),
		@ClassTeacher NVARCHAR(50),
        @Code NVARCHAR(20),
		@CurrentStandard NVARCHAR(100),
		@CurrentStandardInWords NVARCHAR(100),
		@CurrentStandardTitle NVARCHAR(100),
        @DateOfBirth DATE,
        @DivisionName NVARCHAR(100),
        @DivisionOrder SMALLINT,
        @FailOrPass NVARCHAR(200),
        @FatherName NVARCHAR(100),
        @FirstName NVARCHAR(100),
		@GamesPlayed NVARCHAR(200),
		@LastFeesPaid NVARCHAR(100),
        @LastName NVARCHAR(100),
		@LCBookNumber NVARCHAR(20),
		@LCConduct NVARCHAR(200),
		@LCCopy TINYINT,
		@LCDate DATE,
		@LCNumber INT,
		@LCProgress NVARCHAR(200),
		@LCReason NVARCHAR(200),
		@LCRemark NVARCHAR(200),
		@LeftDate DATE,
        @MiddleName NVARCHAR(100),
        @MotherName NVARCHAR(100),
		@MotherTongue NVARCHAR(100),
        @Name NVARCHAR(300),
        @Nationality NVARCHAR(50),
		@NCCScoutDetail NVARCHAR(200),
		@OrgAddress NVARCHAR(152),
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
		@PhoneNo NVARCHAR(50),
		@PresentDaysSum SMALLINT,
		@PreviousSchool NVARCHAR(200),
		@PreviousStandard NVARCHAR(50),
		@PromotedorNot NVARCHAR(100),
		@PromotedToClass NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
        @Religion NVARCHAR(50),
		@Result NVARCHAR(200),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @SubCaste NVARCHAR(100),
		@SubjectNAme NVARCHAR(300),
		@TermsInInstitute NVARCHAR(500),
		@ToCollege NVARCHAR(200),
		@ToCollegeAddress NVARCHAR(200),
		@TotalDaysSum SMALLINT,
		@UIDNumber NVARCHAR(50),
		@University NVARCHAR(200),
		@PrintDate DATE,
        @LocalName NVARCHAR(100),

		@lConfigValue nvarchar(50),  -- Added Krunal Mantis : 0041217
		@lIsDisplayName bit=0,   -- Added Krunal Mantis : 0041217
		--mantis : 0041217
		@rOrgId int,
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10),
		@SUID NVARCHAR(50)
		select @rOrgId = OrgId  from sSetup.tBatchMaster where Id = @BatchId
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 598 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
			SET @lIsDisplayName = 0
		ELSE
			SET @lIsDisplayName = 1	
		---

    -- Fetch the values from the database
    SELECT
	 
        @AdhaarNumber = ISNULL(AdhaarNumber, ''),
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @AdmissionStandard = ISNULL(AdmissionStandard, ''),
		@AnyConcession = ISNULL(AnyConcession, ''),
		@BankAccountNumber = ISNULL(BankAccountNumber, ''),
		@BankIFSCCode = ISNULL(BankIFSCCode, ''),
		@BankName = ISNULL(BankName, ''),
		@BatchDate = ISNULL(BatchDate, ''),
		@BatchName = ISNULL(BatchName, ''),
		@BirthCountry = ISNULL(BirthCountry, ''),
		@DOBInWord = ISNULL(DOBInWord, ''),
        @BirthDistrict = ISNULL(BirthDistrict, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @BirthState = ISNULL(BirthState, ''),
		@BirthTaluka = ISNULL(BirthTaluka, ''),
		@Caste = ISNULL(Caste, ''),
        @CasteCategory = ISNULL(CasteCategory, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @ClassName = ISNULL(ClassName, ''),
		@ClassTeacher = ISNULL(ClassTeacher, ''),
        @Code = ISNULL(Code, ''),
		@CurrentStandard = ISNULL(CurrentStandard, ''),
		@CurrentStandardInWords = ISNULL(CurrentStandardInWords, ''),
		@CurrentStandardTitle = ISNULL(CurrentStandardTitle, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DivisionName = ISNULL(Divisionname, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
		@FailOrPass = ISNULL(FailOrPass, ''),
        @FatherName = ISNULL(FatherName, ''),
        @FirstName = ISNULL(FirstName, ''),
		@GamesPlayed = ISNULL(GamesPlayed, ''),
		@LastFeesPaid = ISNULL(LastFeesPaid, ''),
        @LastName = ISNULL(LastName, ''),
		@LCBookNumber = ISNULL(LCBookNumber, ''),
		@LCConduct = ISNULL(LCConduct, ''),
		@LCCopy = ISNULL(LCCopy, 0),
		@LCDate = ISNULL(LCDate, ''),
		@LCNumber = ISNULL(LCNumber, 0),
		@LCProgress = ISNULL(LCProgress, ''),
		@LCReason = ISNULL(LCReason, ''),
		@LCRemark = ISNULL(LCRemark, ''),
		@LeftDate = ISNULL(LeftDate, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @MotherName = ISNULL(MotherName, ''),
		@MotherTongue = ISNULL(MotherTongue, ''),
       -- @Name = ISNULL(Name, ''),		
        @Nationality = ISNULL(Nationality, ''),
		@NCCScoutDetail = ISNULL(NCCScoutDetail, ''),
		@OrgAddress = ISNULL(OrgAddress, ''),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
		@PhoneNo = ISNULL(PhoneNo, ''),
		@PresentDaysSum = ISNULL(PresentDaysSum, 0),
		@PreviousSchool = ISNULL(PreviousSchool, ''),
		@PreviousStandard = ISNULL(PreviousStandard, ''),
		@PromotedorNot = ISNULL(PromotedorNot, ''),
		@PromotedToClass = ISNULL(PromotedToClass, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @Religion = ISNULL(Religion, ''),
		@Result = ISNULL(Result, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @SubCaste = ISNULL(SubCaste, ''),
		@SubjectNAme = ISNULL(SubjectNAme, ''),
		@TermsInInstitute = ISNULL(TermsInInstitute, ''),
		@ToCollege = ISNULL(ToCollege, ''),
		@ToCollegeAddress = ISNULL(ToCollegeAddress, ''),
		@TotalDaysSum = ISNULL(TotalDaysSum, 0),
		@UIDNumber = ISNULL(UIDNumber, ''),
		@University = ISNULL(University, ''),
		@PrintDate = ISNULL(PrintDate, ''),
        @LocalName = ISNULL(LocalName, ''),
		--mantis : 0041217
		@Name = CASE WHEN @lIsDisplayName=0
					THEN ISNULL(Name, '')  			
				WHEN @lIsDisplayName=1
					THEN ISNULL(DisplayName,Name)			
				END,
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],''),
		@SUID = ISNULL(SUID,'')
    FROM 
        sCertificate.vPrintTemplateLeavingCertificate
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[AdhaarNumber]', @AdhaarNumber);
    SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[AdmissionStandard]', @AdmissionStandard);
	SET @Template = REPLACE(@Template, '[AnyConcession]', @AnyConcession);
	SET @Template = REPLACE(@Template, '[BankAccountNumber]', @BankAccountNumber);
	SET @Template = REPLACE(@Template, '[BankIFSCCode]', @BankIFSCCode);
	SET @Template = REPLACE(@Template, '[BankName]', @BankName);
	SET @Template = REPLACE(@Template, '[BatchDate]', CONVERT(NVARCHAR, @BatchDate, 103));
	SET @Template = REPLACE(@Template, '[BatchName]', @BatchName);
	SET @Template = REPLACE(@Template, '[BirthCountry]', @BirthCountry);
	SET @Template = REPLACE(@Template, '[DOBInWord]', @DOBInWord);
    SET @Template = REPLACE(@Template, '[BirthDistrict]', @BirthDistrict);
    SET @Template = REPLACE(@Template, '[BirthPlace]', @BirthPlace);
    SET @Template = REPLACE(@Template, '[BirthState]', @BirthState);
	SET @Template = REPLACE(@Template, '[BirthTaluka]', @BirthTaluka);
	SET @Template = REPLACE(@Template, '[Caste]', @Caste);
    SET @Template = REPLACE(@Template, '[CasteCategory]', @CasteCategory);
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]',  @CertificateHeaderA4);
    SET @Template = REPLACE(@Template, '[City]', @City);
    SET @Template = REPLACE(@Template, '[CityState]', @CityState);
    SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
	SET @Template = REPLACE(@Template, '[ClassTeacher]', @ClassTeacher);
    SET @Template = REPLACE(@Template, '[Code]', @Code);
	SET @Template = REPLACE(@Template, '[CurrentStandard]', @CurrentStandard);
	SET @Template = REPLACE(@Template, '[CurrentStandardInWords]', @CurrentStandardInWords);
	SET @Template = REPLACE(@Template, '[CurrentStandardTitle]', @CurrentStandardTitle);
    SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
    SET @Template = REPLACE(@Template, '[Divisionname]', @DivisionName);
    SET @Template = REPLACE(@Template, '[DivisionOrder]', CAST(@DivisionOrder AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[FailOrPass]', CAST(@FailOrPass AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
	SET @Template = REPLACE(@Template, '[GamesPlayed]', @GamesPlayed);
	SET @Template = REPLACE(@Template, '[LastFeesPaid]', @LastFeesPaid);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
	SET @Template = REPLACE(@Template, '[LCBookNumber]', @LCBookNumber);
	SET @Template = REPLACE(@Template, '[LCConduct]', @LCConduct);
	SET @Template = REPLACE(@Template, '[LCCopy]', CAST(@LCCopy AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[LCDate]', CONVERT(NVARCHAR, @LCDate, 103));
	SET @Template = REPLACE(@Template, '[LCNumber]', CAST(@LCNumber AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[LCProgress]', @LCProgress);
	SET @Template = REPLACE(@Template, '[LCReason]', @LCReason);
	SET @Template = REPLACE(@Template, '[LCRemark]', @LCRemark);
	SET @Template = REPLACE(@Template, '[LeftDate]', CONVERT(NVARCHAR, @LeftDate, 103));
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[MotherName]', @MotherName);
	SET @Template = REPLACE(@Template, '[MotherTongue]', @MotherTongue);
    SET @Template = REPLACE(@Template, '[Name]', @Name);
    SET @Template = REPLACE(@Template, '[Nationality]', @Nationality);
	SET @Template = REPLACE(@Template, '[NCCScoutDetail]', @NCCScoutDetail);
	SET @Template = REPLACE(@Template, '[OrgAddress]', @OrgAddress);
    SET @Template = REPLACE(@Template, '[OrgLogo]', @OrgLogo);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
	SET @Template = REPLACE(@Template, '[PhoneNo]', @PhoneNo);
	SET @Template = REPLACE(@Template, '[PresentDaysSum]', CAST(@PresentDaysSum AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[PreviousSchool]', @PreviousSchool);
	SET @Template = REPLACE(@Template, '[PreviousStandard]', @PreviousStandard);
	SET @Template = REPLACE(@Template, '[PromotedorNot]', @PromotedorNot);
	SET @Template = REPLACE(@Template, '[PromotedToClass]', @PromotedToClass);
    SET @Template = REPLACE(@Template, '[RegistrationDetail]', @RegistrationDetail);
    SET @Template = REPLACE(@Template, '[Religion]', @Religion);
	SET @Template = REPLACE(@Template, '[Result]', @Result);
    SET @Template = REPLACE(@Template, '[RollNo]', CAST(@RollNo AS NVARCHAR));
    SET @Template = REPLACE(@Template, '[SmallAddress1]', @SmallAddress1);
    SET @Template = REPLACE(@Template, '[SmallAddress2]', @SmallAddress2);
    SET @Template = REPLACE(@Template, '[SubCaste]', @SubCaste);
	SET @Template = REPLACE(@Template, '[SubjectNAme]', @SubjectNAme);
	SET @Template = REPLACE(@Template, '[TermsInInstitute]', @TermsInInstitute);
	SET @Template = REPLACE(@Template, '[ToCollege]', @ToCollege);
	SET @Template = REPLACE(@Template, '[ToCollegeAddress]', @ToCollegeAddress);
	SET @Template = REPLACE(@Template, '[TotalDaysSum]', CAST(@TotalDaysSum AS NVARCHAR));
	SET @Template = REPLACE(@Template, '[UIDNumber]', @UIDNumber);
	SET @Template = REPLACE(@Template, '[University]', @University);
	SET @Template = REPLACE(@Template, '[PrintDate]', CONVERT(NVARCHAR, @PrintDate, 103));
    SET @Template = REPLACE(@Template, '[LocalName]', @LocalName);
	SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
	SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
	SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
	SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);
	SET @Template = REPLACE(@Template ,'[SUID]', @SUID);

    RETURN @Template;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCertificate].[fTransferCertificateTemplate]
(
    @AcademicId BIGINT,
	@BatchId INT,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS

BEGIN
    DECLARE 
        @AdhaarNumber NVARCHAR(20),
        @AdmissionDate DATE,
        @AdmissionStandard NVARCHAR(100),	
		@BankAccountNumber NVARCHAR(20),
		@BankIFSCCode NVARCHAR(20),
		@BankName NVARCHAR(20),
		@BatchDate DATE,
		@BatchName NVARCHAR(100),
		@BirthCountry NVARCHAR(150),
		@DOBInWord NVARCHAR(150),
        @BirthDistrict NVARCHAR(100),
        @BirthPlace NVARCHAR(150),
        @BirthState NVARCHAR(150),
		@BirthTaluka NVARCHAR(150),
		@Caste NVARCHAR(100),
        @CasteCategory NVARCHAR(50),
        @CertificateHeaderA4 NVARCHAR(MAX),
        @City NVARCHAR(100),
        @CityState NVARCHAR(100),
        @ClassName NVARCHAR(100),
		@ClassTeacher NVARCHAR(50),
        @Code NVARCHAR(20),
		@CurrentStandard NVARCHAR(100),
		@CurrentStandardInWords NVARCHAR(100),
		@CurrentStandardTitle NVARCHAR(100),
        @DateOfBirth DATE,
        @DivisionName NVARCHAR(100),
        @DivisionOrder SMALLINT,
        @FatherName NVARCHAR(100),
        @FirstName NVARCHAR(100),
        @LastName NVARCHAR(100),
        @MiddleName NVARCHAR(100),
        @MotherName NVARCHAR(100),
		@MotherTongue NVARCHAR(100),
        @Name NVARCHAR(300),
        @Nationality NVARCHAR(50),
		@NCCScoutDetail NVARCHAR(200),
		@OrgAddress NVARCHAR(152),
        @OrgLogo NVARCHAR(MAX),
        @OrgTitle NVARCHAR(100),
		@PhoneNo NVARCHAR(50),
		@PresentDaysSum SMALLINT,
		@PreviousSchool NVARCHAR(200),
		@PreviousStandard NVARCHAR(50),
		@PromotedorNot NVARCHAR(100),
		@PromotedToClass NVARCHAR(50),
        @RegistrationDetail NVARCHAR(200),
        @Religion NVARCHAR(50),
        @RollNo INT,
        @SmallAddress1 NVARCHAR(200),
        @SmallAddress2 NVARCHAR(200),
        @SubCaste NVARCHAR(100),
		@SubjectNAme NVARCHAR(300),
		@TermsInInstitute NVARCHAR(500),
		@ToCollege NVARCHAR(200),
		@ToCollegeAddress NVARCHAR(200),
		@TotalDaysSum SMALLINT,
		@UIDNumber NVARCHAR(50),
		@University NVARCHAR(200),		
        @LocalName NVARCHAR(100),
		@Number NVARCHAR(50),
		@TCDate DATE,
		@LeftDate DATE,
		@SemesterDuration NVARCHAR(200),
		@ExamName NVARCHAR(200),
		@ExamSeatNo NVARCHAR(50),
		@ExamYear NVARCHAR(50),
		@ExamResult NVARCHAR(50),
		@PromotedClass NVARCHAR(50),
		@TransferConduct NVARCHAR(50),
		@OptionalSubject NVARCHAR(200),
		@Reason NVARCHAR(200),
		@Remark NVARCHAR(200),
		@KumarKumari NVARCHAR(10),
		@HeShe NVARCHAR(10),
		@HisHer NVARCHAR(10),
		@IsWas NVARCHAR(10)

    -- Fetch the values from the database
    SELECT
	 
		@Number = ISNULL(Number,''),
		@TCDate = ISNULL(TCDate,''),
		@LeftDate = ISNULL(LeftDate,''),
		@SemesterDuration = ISNULL(SemesterDuration,''),
		@ExamName = ISNULL(ExamName,''),
		@ExamSeatNo = ISNULL(ExamSeatNo,''),
		@ExamYear = ISNULL(ExamYear,''),
		@ExamResult = ISNULL(ExamResult,''),
		@PromotedClass = ISNULL(PromotedClass,''),
		@TransferConduct = ISNULL(TransferConduct,''),
		@OptionalSubject = ISNULL(OptionalSubject,''),
		@Reason = ISNULL(Reason,''),
		@Remark = ISNULL(Remark,''),		
        @AdhaarNumber = ISNULL(AdhaarNumber, ''),
        @AdmissionDate = ISNULL(AdmissionDate, ''),
        @AdmissionStandard = ISNULL(AdmissionStandard, ''),		
		@BankAccountNumber = ISNULL(BankAccountNumber, ''),
		@BankIFSCCode = ISNULL(BankIFSCCode, ''),
		@BankName = ISNULL(BankName, ''),
		@BatchDate = ISNULL(BatchDate, ''),
		@BatchName = ISNULL(BatchName, ''),
		@BirthCountry = ISNULL(BirthCountry, ''),
		@DOBInWord = ISNULL(DOBInWord, ''),
        @BirthDistrict = ISNULL(BirthDistrict, ''),
        @BirthPlace = ISNULL(BirthPlace, ''),
        @BirthState = ISNULL(BirthState, ''),
		@BirthTaluka = ISNULL(BirthTaluka, ''),
		@Caste = ISNULL(Caste, ''),
        @CasteCategory = ISNULL(CasteCategory, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @City = ISNULL(City, ''),
        @CityState = ISNULL(CityState, ''),
        @ClassName = ISNULL(ClassName, ''),
		@ClassTeacher = ISNULL(ClassTeacher, ''),
        @Code = ISNULL(Code, ''),
		@CurrentStandard = ISNULL(CurrentStandard, ''),
		@CurrentStandardInWords = ISNULL(CurrentStandardInWords, ''),
		@CurrentStandardTitle = ISNULL(CurrentStandardTitle, ''),
        @DateOfBirth = ISNULL(DateOfBirth, ''),
        @DivisionName = ISNULL(Divisionname, ''),
        @DivisionOrder = ISNULL(DivisionOrder, ''),
        @FatherName = ISNULL(FatherName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @LastName = ISNULL(LastName, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @MotherName = ISNULL(MotherName, ''),
		@MotherTongue = ISNULL(MotherTongue, ''),
        @Name = ISNULL(Name, ''),
        @Nationality = ISNULL(Nationality, ''),
		@OrgAddress = ISNULL(OrgAddress, ''),
        @OrgLogo = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("OrgLogo")))', 'NVARCHAR(MAX)'),''),
        @OrgTitle = ISNULL(OrgTitle, ''),
		@PhoneNo = ISNULL(PhoneNo, ''),
		@PresentDaysSum = ISNULL(PresentDaysSum, 0),
		@PreviousSchool = ISNULL(PreviousSchool, ''),
		@PreviousStandard = ISNULL(PreviousStandard, ''),
        @RegistrationDetail = ISNULL(RegistrationDetail, ''),
        @Religion = ISNULL(Religion, ''),
        @RollNo = ISNULL(RollNo, 0),
        @SmallAddress1 = ISNULL(SmallAddress1, ''),
        @SmallAddress2 = ISNULL(SmallAddress2, ''),
        @SubCaste = ISNULL(SubCaste, ''),
		@TotalDaysSum = ISNULL(TotalDaysSum, 0),
		@UIDNumber = ISNULL(UIDNumber, ''),
		@University = ISNULL(University, ''),	
        @LocalName = ISNULL(LocalName, ''),
		@KumarKumari = ISNULL([Kumar-Kumari],''),
		@HeShe = ISNULL([He-She],''),
		@HisHer = ISNULL([His-Her],''),
		@IsWas = ISNULL([is-was],'')
    FROM 
        sCertificate.vPrintTemplateTransferCertificateReport
    WHERE 
        Academicid = @AcademicId AND BatchId = @BatchId       
	
		SET @Template = REPLACE(@Template, '[Number]', @Number);
		SET @Template = REPLACE(@Template, '[TCDate]', CONVERT(NVARCHAR, @TCDate, 103));
		SET @Template = REPLACE(@Template, '[TransferDate]',CONVERT(NVARCHAR, @LeftDate, 103));
		SET @Template = REPLACE(@Template, '[SemesterDuration]', @SemesterDuration);
		SET @Template = REPLACE(@Template, '[ExamName]', @ExamName);
		SET @Template = REPLACE(@Template, '[ExamSeatNo]', @ExamSeatNo);
		SET @Template = REPLACE(@Template, '[ExamYear]', @ExamYear);
		SET @Template = REPLACE(@Template, '[ExamResult]', @ExamResult);
		SET @Template = REPLACE(@Template, '[PromotedClass]', @PromotedClass);
		SET @Template = REPLACE(@Template, '[TransferConduct]', @TransferConduct);
		SET @Template = REPLACE(@Template, '[OptionalSubject]', @OptionalSubject);
		SET @Template = REPLACE(@Template, '[Reason]', @Reason);
		SET @Template = REPLACE(@Template, '[Remark]', @Remark);		
		SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);		
		SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
		SET @Template = REPLACE(@Template, '[LastName]', @LastName);
		SET @Template = REPLACE(@Template, '[FatherName]', @FatherName);
		SET @Template = REPLACE(@Template, '[MotherName]', @MotherName);
		SET @Template = REPLACE(@Template, '[Name]', @Name);
		SET @Template = REPLACE(@Template, '[Code]', @Code);
		SET @Template = REPLACE(@Template, '[ClassName]', @ClassName);
		SET @Template = REPLACE(@Template, '[Divisionname]', @DivisionName);
		SET @Template = REPLACE(@Template, '[DateOfBirth]', CONVERT(NVARCHAR, @DateOfBirth, 103));
		SET @Template = REPLACE(@Template, '[DOBInWord]', @DOBInWord);
		SET @Template = REPLACE(@Template ,'[Kumar-Kumari]', @KumarKumari);
		SET @Template = REPLACE(@Template ,'[He-She]', @HeShe);
		SET @Template = REPLACE(@Template ,'[His-Her]', @HisHer);
		SET @Template = REPLACE(@Template ,'[is-was]', @IsWas);
		
		RETURN @Template
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[Age](@rDate Date)

  RETURNS NVARCHAR(200)

AS

BEGIN
	DECLARE @Age nvarchar(max), @intMonths int, @intYears int, @intTotalYears int

	IF(@rDate <= convert(date,getdate()))
	BEGIN
		select @intTotalYears = convert(int,year(getdate())) - convert(int,Year(@rDate))
		select @intMonths = convert(int,month(getdate())) - convert(int,month(@rDate))
		select @intMonths = (@intTotalYears * 12) + @intMonths
	END
	ELSE
	BEGIN
		select @intTotalYears = 0
		select @intMonths = 0
	END

	select @intYears = @intMonths / 12
	select @intMonths = @intMonths % 12

	select @Age = convert(nvarchar(20),@intYears) + ' Year(s) ' + convert(nvarchar(20),@intMonths) + ' Month(s)'
	
	RETURN (@Age)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCommon].[Base64Decode] ( @Input NVARCHAR(MAX) )
 
RETURNS varbinary(MAX)
BEGIN
 
DECLARE @DecodedOutput varbinary(MAX)
 
--set @DecodedOutput = CAST(CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@Input"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX))
set @DecodedOutput = CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@Input"))', 'VARBINARY(MAX)') 
 
RETURN @DecodedOutput
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[Base64Encode] ( @Input NVARCHAR(MAX) )
RETURNS VARCHAR(MAX)
BEGIN
 
DECLARE @Inputb VARBINARY(MAX)
DECLARE @EncodedOutput VARCHAR(MAX)
 
set @Inputb = CONVERT(varbinary(MAX), @Input)
set @EncodedOutput = CAST(N'' as xml).value('xs:base64Binary(sql:variable("@Inputb"))', 'VARCHAR(max)')
 
RETURN @EncodedOutput
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[ConvertToYYYYMMDD](@rDate nvarchar(20))
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN 
 
	RETURN RIGHT(@rDate,4) + '-' + LEFT(RIGHT(@rDate,7),2) + '-' + LEFT(@rDate,2)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[DateToWord](@rDate Date)

  RETURNS NVARCHAR(200)

AS

BEGIN
	DECLARE @lDay INT = DAY(@rDate)
    DECLARE @lMonth INT = MONTH(@rDate)
    DECLARE @lYear INT = YEAR(@rDate)

	DECLARE @Below20 TABLE (ID int identity(0,1), Word varchar(32), RomanWord varchar(32))
	DECLARE @Below100 TABLE (ID int identity(2,1), Word varchar(32))
	DECLARE @lMonthTab TABLE (ID int identity(1,1),Month varchar(32))
	INSERT @Below20 (Word,RomanWord) VALUES

            ('',''),('One','First'),( 'Two','Second' ), ( 'Three','Third'),

            ( 'Four','Fourth' ), ( 'Five', 'Fifth' ), ( 'Six', 'Sixth' ), ( 'Seven','Seventh' ),

            ( 'Eight','Eighth'), ( 'Nine','Ninth'), ( 'Ten','Tenth'), ( 'Eleven','Eleventh' ),

            ( 'Twelve','Twelth' ), ( 'Thirteen','Thirteenth' ), ( 'Fourteen','Fourteenth'),

            ( 'Fifteen','Fifteenth' ), ('Sixteen','Sixteenth' ), ( 'Seventeen','Seventeenth'),

            ('Eighteen','Eighteenth' ), ( 'Nineteen','Nineteenth' )

	INSERT @Below100 VALUES ('Twenty'), ('Thirty'),('Forty'), ('Fifty'),

               ('Sixty'), ('Seventy'), ('Eighty'), ('Ninety')
   
	INSERT @lMonthTab VALUES ('January'),('February'), ('March'), ('April'), ('May'), ('June'),
                
               ('July'), ('August'), ('September'), ('October'), ('November'), ('December')


	DECLARE @lDayInWord NVARCHAR(50) =
	(
		SELECT CASE

		WHEN @lDay BETWEEN 1 AND 19

		THEN (SELECT RomanWord FROM @Below20 WHERE ID=@lDay)

		WHEN @lDay = 20 THEN 'Twentieth'

		WHEN @lDay > 20 AND @lDay <> 30

		THEN (SELECT Word FROM @Below100 WHERE ID=@lDay/10)+ ' ' +

			(SELECT RomanWord FROM @Below20 WHERE ID=@lDay%10)

		WHEN @lDay = 30 THEN 'Thirtieth'
		ELSE '' END
	)

	DECLARE @lMonthInWord NVARCHAR(50) =
	(
	 SELECT Month FROM @lMonthTab WHERE ID = @lMonth
	)

	DECLARE @Thousand nvarchar(20) = CASE WHEN @lYear/1000 > 0 THEN (SELECT Word FROM @Below20 WHERE ID = @lYear/1000)+ ' Thousand ' ELSE '' END
	DECLARE @Hundred nvarchar(20) = CASE WHEN (@lYear%1000)/100>0 THEN (SELECT Word FROM @Below20 WHERE ID = (@lYear%1000)/100)+ ' Hundred ' ELSE '' END
	DECLARE @Ten nvarchar(20) = CASE
					WHEN (@lYear%100) <= 19 THEN (SELECT Word FROM @Below20 WHERE ID=@lYear%100)
					ELSE (SELECT Word FROM @Below100 WHERE ID=(@lYear%100)/10)+ ' ' + (SELECT Word FROM @Below20 WHERE ID=(@lYear%100)%10)
				  END

	DECLARE @lYearInWord NVARCHAR(50) =
	(
	 @Thousand + @Hundred + @Ten
	)

	DECLARE @DOBInWord NVARCHAR(200) = @lDayInWord + ' ' + @lMonthInWord + ' ' + @lYearInWord



	SELECT @DOBInWord = RTRIM(@DOBInWord)


	RETURN (@DOBInWord)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[f_GetCamelCase] (@str AS NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
	WITH EXECUTE AS CALLER
AS
BEGIN
	DECLARE @finalresult NVARCHAR(MAX);

	IF (@str COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[A-Za-z]%')
	BEGIN
		DECLARE @bitval BIT;
		DECLARE @result NVARCHAR(MAX);
		DECLARE @i INT;
		DECLARE @j CHAR(1);

		SELECT @bitval = 1
			,@i = 1
			,@result = '';

		WHILE (@i <= len(@str))
			SELECT @j = substring(@str, @i, 1)
				,@result = @result + CASE 
					WHEN @bitval = 1
						THEN UPPER(@j)
					ELSE LOWER(@j)
					END
				,@bitval = CASE 
					WHEN @j LIKE '[a-zA-Z]'
						THEN 0
					ELSE 1
					END
				,@i = @i + 1

		SET @finalresult = @result
	END
	ELSE
	BEGIN
		SET @finalresult = @str
	END

	RETURN @finalresult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sCommon].[fConvertDateTimeToDifferentTimeZone](@rDateTime datetime)
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN
		DECLARE @lConfigValue nvarchar(50),@date datetime
		

		DECLARE @lTimeZoneConfigValue nvarchar(max), @lConfigValueId int
		
		Select @lConfigValueId = CV.Id FROM sConfig.tConfigurationSetup CS 
		INNER JOIN sConfig.tConfigurationValue CV ON CS.ConfigurationId = CV.ConfigurationId AND CS.ItemValue = CV.ItemValue
		WHERE CS.ConfigurationId = 234

		--@lConfigValueId = 60 for (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi
		--@lConfigValueId = 61 for (UTC+00:00) Dublin, Edinburgh, Lisbon, London
		--@lConfigValueId = 72 for (UTC+03:00) Nairobi


		----SELECT @lConfigValueId

		----for (UTC+00:00) Dublin, Edinburgh, Lisbon, London
		IF(@rDateTime = '')
		BEGIN
			SELECT @date = @rDateTime
		END
		ELSE IF(@lConfigValueId = 61)
		BEGIN
		    SELECT @date = DATEADD(MINUTE, -330, @rDateTime)
			--SELECT @date = '2023-10-01 00:00:00.000'
		END
		--for (UTC+03:00) Nairobi and (UTC+03:00) Kuwait , Riyadh
		ELSE IF(@lConfigValueId = 72 OR @lConfigValueId = 203)
		BEGIN
			SELECT @date = CONVERT(DATETIME,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, (DATEADD(MINUTE, -330, @rDateTime))), '+03:00'))
		END
		--for (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi
		ELSE
		BEGIN
			SELECT @date = @rDateTime
		END

		RETURN @date

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sCommon].[fCountAbsentStudent](@rDivisionId int, @rBatchId int,@rAttendanceDate date ,@rAttendanceTypeId int=1,@rIsPresent int=0)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lTotalCount int
			SELECT @lTotalCount=COUNT(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SM ON A.Id=SM.AcademicId
			WHERE A.DivisionId=@rDivisionId AND A.BatchId=@rBatchId AND SM.IsPresent=@rIsPresent AND SM.AttendanceDate=@rAttendanceDate
			AND SM.AttendanceTypeId=@rAttendanceTypeId  
	RETURN  @lTotalCount 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sCommon].[fCountDivisionStudent](@rDivisionId int, @rBatchId int)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lTotalCount int
			SELECT @lTotalCount=COUNT(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			WHERE A.DivisionId=@rDivisionId AND A.BatchId=@rBatchId AND SM.StatusId=1
	RETURN  @lTotalCount 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fDateTimeConcate](@rDate [date], @rTime [time](7))
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDateTime DateTime

	SET @lDateTime = CAST(CAST(DATEPART(YY, @rDate) AS NVARCHAR(4)) + '-' + 
					 CAST(DATEPART(MM, @rDate) AS NVARCHAR(2)) + '-' +
					 CAST(DATEPART(DD, @rDate) AS NVARCHAR(2)) + ' ' +
					 CAST(DATEPART(HH, @rTime) AS NVARCHAR(2)) + ':' +
					 CAST(DATEPART(N, @rTime) AS NVARCHAR(2)) + ':00' AS DATETIME)

	RETURN @lDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fExtractDataFromString](@rArray [nvarchar](1000), @rSeperator [nchar](1))
RETURNS @tDataList TABLE (
	[DataValue] [nvarchar](100) NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
	 
	 DECLARE @lSeperatorPosition INT 
	 DECLARE @lArrayValue NVARCHAR(1000) 
	 
	 SET @rArray = @rArray + @rSeperator
	 
	 WHILE PATINDEX('%' + @rSeperator + '%' , @rArray) <> 0
	 BEGIN
		SELECT @lSeperatorPosition =  PATINDEX('%' + @rSeperator + '%' , @rArray)
		SELECT @lArrayValue = LEFT(@rArray, @lSeperatorPosition - 1)
	 
		INSERT @tDataList VALUES(CAST(LTRIM(RTRIM(@lArrayValue)) AS NVARCHAR(100)))
		SELECT @rArray = STUFF(@rArray, 1, @lSeperatorPosition, '')
	 END
	 
	 RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE OR ALTER FUNCTION [sCommon].[fGenderFromRelationIdGet] 
(
	-- Add the parameters for the function here
	@rRelationId [int]
)
RETURNS  NVARCHAR(10) 
AS
BEGIN
	-- Declare the return variable here
	DECLARE @rGender NVARCHAR(10) 
	
	
	IF @rRelationId = 2 OR @rRelationId = 4
	BEGIN
	   SET @rGender = 'Male'	
	   END
	ELSE IF @rRelationId = 3 OR  @rRelationId = 5  
	BEGIN
		SET @rGender = 'Female'
	END
	

	-- Return the result of the function
	RETURN @rGender

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE OR ALTER FUNCTION [sCommon].[fGenderIdFromRelationIdGet] 
(
	-- Add the parameters for the function here
	@rRelationId [int]
)
RETURNS  int 
AS
BEGIN
	-- Declare the return variable here
	DECLARE @rGenderId int 
	
	
	IF @rRelationId = 2 OR @rRelationId = 4
	BEGIN
	   SET @rGenderId = 1
	   END
	ELSE IF @rRelationId = 3 OR  @rRelationId = 5  
	BEGIN
		SET @rGenderId = 2
	END
	

	-- Return the result of the function
	RETURN @rGenderId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetBigIntIdForOrg](@rId bigint,@rOrgId bigint)
RETURNS bigint WITH EXECUTE AS CALLER
AS 
BEGIN 
	DECLARE @lId bigInt
	DECLARE @lNewId bigint
	
	SET @lNewId = (@rOrgId * 1000000000) + @rId	
	RETURN @lNewId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetDate]()
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN
		DECLARE @lConfigValue nvarchar(50),@lTimeoffset nvarchar(200),@date datetime
		
		SELECT  @lConfigValue =ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 234 
		SELECT @lTimeoffset=TimeOffset FROM sSystem.tTimeZone WHERE DisplayTimeZone=@lConfigValue
		
			IF ((@lConfigValue IS NULL) OR  (@lTimeoffset IS NULL))
			SET	@date= GETDATE()
			ELSE IF((@lTimeoffset IS NOT  NULL) AND  (@lConfigValue IS NOT NULL))
            SELECT @date=CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset,GetUTCDate()),@lTimeoffset)) 
			ELSE
			SET	@date= GETDATE()
		RETURN @date

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetDaysInMonth](@rMonth [int], @rYear [int])
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

    RETURN CASE WHEN @rMonth IN (1, 3, 5, 7, 8, 10, 12) THEN 31
                WHEN @rMonth IN (4, 6, 9, 11) THEN 30
                ELSE CASE WHEN (@rYear % 4    = 0 AND
                                @rYear % 100 != 0) OR
                               (@rYear % 400  = 0)
                          THEN 29
                          ELSE 28
                     END
           END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetExactSearch](@rString [varchar](7999))
RETURNS [varchar](7999) WITH EXECUTE AS CALLER
AS 
BEGIN
   
    --DECLARE @newstring varchar(7999)
    --DECLARE @num int
    --DECLARE @code int
   
    --SELECT @newstring = ''
    --SELECT @num = 1

    --WHILE @num < LEN(@rString)+1
    --BEGIN
    --    SET @code = ASCII(SUBSTRING(@rString, @Num, 1))
    --    --- ascii: 48-57 (numbers 0-9)
    --    --- ascii: 65-90 (uppercase letters A-Z)
    --    --- ascii: 97-122 (lowercase letters a-z)
    --    IF (@code between 48 and 57)
    --    BEGIN
    --        SET @newstring = @newstring + SUBSTRING(@rString, @num, 1)
    --    END
       
    --    SET @num = @num + 1
    --END
   
    --RETURN @newstring
    
    DECLARE @result bit 
 --DECLARE @pnumber nvarchar(100)
 --SET @pnumber = 'TZDAH-10-000005'
 SET @result = 1 
 WHILE(  @result = 1)
 BEGIN
 SELECT  @rString =  right(@rString, (LEN(@rString)- charindex('-',@rString))) --from sRegistration.tPatientMaster   
 IF (charindex('-',@rString) > 0)
 BEGIN 
 SET @result = 1
 END
 ELSE
 BEGIN
 SET @result = 0
 END	
 END  
  RETURN @rString 
   
END
--select [sCommon].[fGetExactSearch]('TZDAH-10-000005')

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetFirstDateofMonth](@rMonth int ,@rYear int)
RETURNS [date] WITH EXECUTE AS CALLER
AS 
BEGIN 
	Declare @lLastDate Date
	Set @lLastDate =convert(date, convert(nvarchar(10),@rYear) + '/' + convert(nvarchar(10),@rMonth)+ '/' +'01')
	
	RETURN @lLastDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetIntIdForOrg](@rId int,@rOrgId smallint)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN 
	DECLARE @lId SmallInt
	DECLARE @lNewId int
	
	SET @lNewId = (@rOrgId * 100000) + @rId	
	RETURN @lNewId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetLastDateofMonth](@rDate [datetime])
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN 
	Declare @lLastDate DateTime 
	Set @lLastDate = DateAdd(Month, 1, @rDate - Day(@rDate) + 1) -1
	RETURN @lLastDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sCommon].[fGetMonthName](@rMonth [int])
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN

    RETURN CASE WHEN @rMonth = 1 THEN 'Jan'
                WHEN @rMonth = 2 THEN 'Feb'
                WHEN @rMonth = 3 THEN 'Mar'
                WHEN @rMonth = 4 THEN 'Apr'
                WHEN @rMonth = 5 THEN 'May'
                WHEN @rMonth = 6 THEN 'Jun'
                WHEN @rMonth = 7 THEN 'Jul'
                WHEN @rMonth = 8 THEN 'Aug'
                WHEN @rMonth = 9 THEN 'Sep'
                WHEN @rMonth = 10 THEN 'Oct'
                WHEN @rMonth = 11 THEN 'Nov'
                WHEN @rMonth = 12 THEN 'Dec'
				END
          
        

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetOrgwiseMotherTongueId](@rId int,@rOrgId smallint)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rSql nvarchar(max)   
	DECLARE @rTitle nvarchar(100) 
	IF(@rId<>0)
	BEGIN
		IF EXISTS(SELECT Title FROM sCommon.tMotherTongueMaster WHERE Id=@rId)
		BEGIN
			SELECT @rTitle=Title FROM sCommon.tMotherTongueMaster WHERE Id=@rId
		END
		--IF EXISTS(SELECT Id FROM sCommon.tMotherTongueMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
		--BEGIN
		--	SELECT @rId=Id FROM sCommon.tMotherTongueMaster WHERE Title=@rTitle AND OrgId=@rOrgId
		--END
		--ELSE
		--BEGIN
		--	SET @rId=0
		--END

		SET @rId=0 -- Commented above if else block - as Table scope is OrgGroup and here data was accessed by OrgId
	END
	return  @rId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetOrgwiseNationalityId](@rId int,@rOrgId smallint)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rSql nvarchar(max)   
	DECLARE @rTitle nvarchar(100) 
	IF(@rId<>0)
	BEGIN
		IF EXISTS(SELECT Title FROM scommon.tNationalityMaster WHERE Id=@rId)
		BEGIN
			SELECT @rTitle=Title FROM scommon.tNationalityMaster WHERE Id=@rId
		END
		--IF EXISTS(SELECT Id FROM scommon.tNationalityMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
		--BEGIN
		--	SELECT @rId=Id FROM scommon.tNationalityMaster WHERE Title=@rTitle AND OrgId=@rOrgId
		--END
		--ELSE
		--BEGIN
		--	SET @rId=0
		--END
		SET @rId=0 -- Commented above if else block - as Table scope is OrgGroup and here data was accessed by OrgId
	END
	return  @rId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetOrgwiseReligionId](@rId int,@rOrgId smallint)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rSql nvarchar(max)   
	DECLARE @rTitle nvarchar(100) 
	IF(@rId<>0)
	BEGIN
		IF EXISTS(SELECT Title FROM sCommon.tReligionMaster WHERE Id=@rId)
		BEGIN
			SELECT @rTitle=Title FROM sCommon.tReligionMaster WHERE Id=@rId
		END
		--IF EXISTS(SELECT Id FROM sCommon.tReligionMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
		--BEGIN
		--	SELECT @rId=Id FROM sCommon.tReligionMaster WHERE Title=@rTitle AND OrgId=@rOrgId
		--END
		--ELSE
		--BEGIN
		--	SET @rId=0
		--END
		SET @rId=0 -- Commented above if else block - as Table scope is OrgGroup and here data was accessed by OrgId

		--SET @rSql = 'SELECT @rTitle=Title FROM '+@rTableName+' WHERE Id=@rId'
		--EXECUTE sp_executesql @rSql, N'@rId int,@rTitle nvarchar(100) OUTPUT',
		--							@rId=@rId,@rTitle=@rTitle OUTPUT
		
		--SET @rSql = 'SELECT @rId=Id FROM '+@rTableName+' WHERE Title=@rTitle AND OrgId=@rOrgId'
		--EXECUTE sp_executesql @rSql, N'@rTitle nvarchar(100),@rOrgId smallint,@rId int OUTPUT',
		--							@rTitle=@rTitle,@rOrgId=@rOrgId,@rId=@rId OUTPUT
	END
	return  @rId 
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER FUNCTION [sCommon].[fGetUserNameforDailyStatus](@rDivisionId int,@rSearchDate datetime,@rAttendanceTypeId int)
RETURNS varchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lUserName varchar(100)

	SELECT @lUserName = ISNULL((SELECT TOP 1 U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = 
			(Select Top 1 ISNULL((SR1.UpdatedUserId),(SR1.CreatedUserId))
			from sAttendance.tStudentRegister SR1
			INNER JOIN sStudent.tAcademic A1 ON  SR1.AcademicId = A1.Id
			Where SR1.AttendanceDate = @rSearchDate 
            AND SR1.AttendanceTypeId = @rAttendanceTypeId
			AND A1.DivisionId = @rDivisionId
			ORDER BY SR1.CreatedDateTime DESC)
			),'')
 
	RETURN  @lUserName 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sCommon].[fGetYearMonthNumber](@rYear [int],@rMonth [int] )
RETURNS [bigint] WITH EXECUTE AS CALLER
AS 
BEGIN


return cast(cast(@rYear as nvarchar) + '' + replicate('0', 2 - len(@rMonth)) + cast (@rMonth as nvarchar) as bigint)

    
  

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fHtmlTagsRemove](@lHtmlString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @Start INT,
        @End INT,
        @Length INT

    WHILE CharIndex('<', @lHtmlString) > 0 And CharIndex('>', @lHtmlString, CharIndex('<', @lHtmlString)) > 0
     BEGIN
        SELECT @Start = CharIndex('<', @lHtmlString),
			   @End = CharIndex('>', @lHtmlString, CharIndex('<', @lHtmlString))
			   
        SELECT @Length = (@End - @Start) + 1
        IF @Length > 0
         BEGIN
            SELECT @lHtmlString = Stuff(@lHtmlString, @Start, @Length, '')
         END
     END
	 SELECT @lHtmlString = sCommon.fReplace(@lHtmlString, '&nbsp;', '') 
    RETURN @lHtmlString
   
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fInitCap] ( @InputString varchar(4000) ) 
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @Index          INT
DECLARE @Char           CHAR(1)
DECLARE @PrevChar       CHAR(1)
DECLARE @OutputString   VARCHAR(255)

SET @OutputString = LOWER(@InputString)
SET @Index = 1

WHILE @Index <= LEN(@InputString)
BEGIN
    SET @Char     = SUBSTRING(@InputString, @Index, 1)
    SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
                         ELSE SUBSTRING(@InputString, @Index - 1, 1)
                    END

    IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
    BEGIN
        IF @PrevChar != '''' OR UPPER(@Char) != 'S'
            SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
    END

    SET @Index = @Index + 1
END

RETURN @OutputString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER FUNCTION [sCommon].[fMaxAdmissionInquiryNumberWithPrefixGet]
 (
	@rPrefixFunctionalityId smallint,	 
	@rOrgId smallint,
	@rOrgGroupId int,
	@rOrgGroupBatchId int=0,
	@rBatchId int=0
)
RETURNS [nvarchar](20)
	 
	WITH EXECUTE AS CALLER
AS
			 
BEGIN 
--BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF @rPrefixFunctionalityId=2013 -- Admission Inquiry
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
		IF @lSourceTypeId IS NOT NULL
		BEGIN
			IF @lSourceTypeId = 2021 -- Organization
			BEGIN
				SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
			END

			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (MAX(Number)) FROM sAdmission.tAdmissionInquiry AI
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
				WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF(@lConfigValue='Batch')
			BEGIN
				SELECT @lOutCode = MAX(Number) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF (@lConfigValue = 'Continuous')
			BEGIN
				SELECT @lOutCode =MAX(Number) FROM sAdmission.tAdmissionInquiry  
				WHERE OrgGroupId = @rOrgGroupId AND Number LIKE @lPrefix+'%'
			END

			IF CHARINDEX(@lPrefix,@lOutCode) > 0
			BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			ELSE
			BEGIN
				SELECT @lOutCode = 1
				IF @lNumberLength != 0
				BEGIN
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
				END
				SELECT @lOutCode = @lPrefix + @lOutCode
			END
		END
		ELSE 
		BEGIN
			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (max(AI.InquiryNumber)+1) FROM sAdmission.tAdmissionInquiry AI
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
				WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId 
			END
			ELSE IF(@lConfigValue='Batch')
			BEGIN
				SELECT @lOutCode = (max(AI.InquiryNumber)+1) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId
			END
			ELSE IF (@lConfigValue = 'Continuous')
			BEGIN
				SELECT @lOutCode =(max(AI.InquiryNumber)+1) FROM sAdmission.tAdmissionInquiry AI 
				WHERE OrgGroupId = @rOrgGroupId 
			END
		END
	END
	
	--END TRY
	--BEGIN CATCH
	--	SET @lOutCode = ''
	--END CATCH
	
	RETURN @lOutCode
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fNextAutoNumberGet]()
RETURNS [nvarchar](20) WITH EXECUTE AS CALLER
AS 
BEGIN
      DECLARE @lNextNumber Nvarchar(20)
      
      BEGIN
	       EXECUTE sCommon.pPrefixSetupNextNumberGet @rPrefixFunctionalityId = 9, @rNumber  = @lNextNumber OUTPUT
		   --SET @rNumber = @lNextNumber
      END
      RETURN @lNextNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fNextNumberGet]()
RETURNS [nvarchar](20) WITH EXECUTE AS CALLER
AS 
BEGIN
      DECLARE @lNextNumber Nvarchar(20)
      
      BEGIN
	       EXECUTE sCommon.pPrefixSetupNextNumberGet @rPrefixFunctionalityId = 9, @rNumber  = @lNextNumber OUTPUT
		   --SET @rNumber = @lNextNumber
      END
      RETURN @lNextNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCommon].[fnSplit](@sInputList [nvarchar](max), @sDelimiter [nvarchar](100) = ',')
RETURNS @List TABLE (
	[item] [nvarchar](1000) NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @sItem NVARCHAR(max)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sCommon].[fnSplitRowID](@sInputList [nvarchar](max), @sDelimiter [nvarchar](100) = ',')
RETURNS @List TABLE (RowID int IDENTITY(1,1),[item] [nvarchar](1000) NULL
) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
 
 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fNumberStringGet](@rPrefix [nvarchar](20), @rPrecision [tinyint], @rNextNumber [int])
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
		
	DECLARE @lNumberString NVARCHAR(100)	
	
	SET @lNumberString = UPPER(@rPrefix)
					   + RIGHT(CAST(YEAR(GETDATE()) AS NVARCHAR(4)), 2) + '-'
					   + (CASE WHEN @rPrecision > (LEN(@rPrefix) + LEN(@rNextNumber) + 3) 
							   THEN CAST(REPLICATE('0', (@rPrecision - (LEN(@rPrefix) + LEN(@rNextNumber) + 3))) AS NVARCHAR(100)) 
						  ELSE '' END)
					   + CAST(@rNextNumber AS NVARCHAR(100))
			    
	RETURN @lNumberString
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fReplace](@rString [nvarchar](max), @rFindString [nvarchar](100), @rReplaceString [nvarchar](100))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN
	RETURN REPLACE(@rString, @rFindString, @rReplaceString) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fReplaceFirstWordOfLine](@rString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN
	RETURN LTRIM(STUFF(@rString,1,CHARINDEX(' ',@rString),'')) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fReportDateGet](@rDate [datetime])
RETURNS [nvarchar](10) WITH EXECUTE AS CALLER
AS 
BEGIN

      DECLARE @lDateFormat Nvarchar(20)
      DECLARE @lDate Nvarchar(20)
      
      IF (@rDate IS NULL)
            BEGIN
                  SET @lDate = NULL 
            END
      ELSE
            BEGIN
                  SELECT @lDateFormat = ShortDatePattern From sConfig.tCultureMaster
                  
                        SET @lDate =      CASE @lDateFormat
                        --                   WHEN 'M/d/yyyy' THEN '' -- No name
                        --             WHEN 'M/d/yy' THEN ' Thousand '
                        --             WHEN 'MM/dd/yy' THEN ' Billion '
                                             WHEN 'MM/dd/yyyy' THEN CONVERT(NVARCHAR(10), @rDate, 101)
                                             WHEN 'dd/MM/yyyy' THEN CONVERT(NVARCHAR(10), @rDate, 103) 
                                             ELSE
                                             CONVERT(NVARCHAR(10), @rDate, 101)
                                             END
      END

      --DECLARE @lDate Nvarchar(20)
      --SET @lDate = CONVERT(NVARCHAR(10), @rDate, 103)
      RETURN @lDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fSearchStringGet](@rSearchString [nvarchar](100))
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
	SET @rSearchString = sCommon.fReplace(@rSearchString, '*', '%')
	IF SUBSTRING(@rSearchString, 1, 1) <> '%'
	AND SUBSTRING(@rSearchString, LEN(@rSearchString), 1) <> '%'
	AND @rSearchString <> ''
		BEGIN
			SET @rSearchString = @rSearchString + '%'
		END
		
	RETURN @rSearchString
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fTimeGet](@rTime [datetime])
RETURNS [nvarchar](10) WITH EXECUTE AS CALLER
AS 
BEGIN

      DECLARE @lTimeFormat Nvarchar(20)
      DECLARE @lTime Nvarchar(20)
      
      IF (@rTime IS NULL)
            BEGIN
                  SET @lTime = NULL 
            END
      ELSE
            BEGIN
                  SELECT @lTimeFormat = ShortTimePattern From sConfig.tCultureMaster
                  
                        SET @lTime =      CASE @lTimeFormat
                        --                   WHEN 'M/d/yyyy' THEN '' -- No name
                        --             WHEN 'M/d/yy' THEN ' Thousand '
                        --             WHEN 'MM/dd/yy' THEN ' Billion '
                                             WHEN 'HH:mm' THEN CONVERT(NVARCHAR(10), @rTime, 114)
                                             WHEN 'h:mm:ss tt' THEN CONVERT(NVARCHAR(10), @rTime, 108) 
                                             ELSE
                                             CONVERT(NVARCHAR(10), @rTime, 108)
                                             END
      END

      --DECLARE @lDate Nvarchar(20)
      --SET @lDate = CONVERT(NVARCHAR(10), @rDate, 103)
      RETURN @lTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fXMLTagsReplace](@lString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN


   
     --SET  @lString =   sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(@lString, '<', '&#60;''') , '>', '&#62;'), '"', '&#39;'), '&', '&#38;'), '''', '&#34;')
    SET  @lString =   sCommon.fReplace(sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace(@lString, '&', '&#38;'),
                                                                 '>', '&#62;'), 
                                                                 '"', '&#34;'), 
                                                                 '<', '&#60;'),
                                                                 '''', '&#39;')
    
    RETURN @lString
   
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fXMLTagsReplaceReverse](@lString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN


   
     --SET  @lString =   sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(sCommon.fReplace(@lString, '<', '&#60;''') , '>', '&#62;'), '"', '&#39;'), '&', '&#38;'), '''', '&#34;')
    SET  @lString =   sCommon.fReplace(sCommon.fReplace(sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace(@lString,'&amp;','&'),
                                                                  '&gt;','>'), 
                                                                  '&quot;', '"'), 
                                                                  '&lt;','<'),
                                                                  '&#39;', ''''),
                                                                  '&#40;', ';')
    
    RETURN @lString
   
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[GetLastDateofMonth](@rDate [datetime])
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN 
	Declare @lLastDate DateTime 
	Set @lLastDate = DateAdd(Month, 1, @rDate - Day(@rDate) + 1) -1
	RETURN @lLastDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommunication].[fMultiPhotoCategoryScopeGet](@rId int,@rScopeSourceTypeId smallint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rPhotoCategoryScope nvarchar(2000)

	IF @rScopeSourceTypeId=2021
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2017
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2016
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN   sSetup.tClassMaster CM ON CM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2005
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2014
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  HM.Title 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId 
	END 
	
	IF @rScopeSourceTypeId=2029
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  HM.Title 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN sActivity.tHouseMaster HM ON HM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId
	END

	IF @rScopeSourceTypeId=2003
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  (SA.Code+' - '+CONVERT(NVARCHAR(10),SA.RollNo)+' - '+SA.Name) 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		--INNER JOIN sStudent.tStudentMaster OM ON OM.Id = PC.ScopeSourceId
		INNER JOIN  sStudent.vStudentAcademic SA ON PC.ScopeSourceId=SA.StudentId 
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId AND SA.IsActiveBatch=1 AND SA.StatusId=1
	END
	IF @rScopeSourceTypeId=95
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  EC.EmployeeName 
		FROM
		sCommunication.tMultiPhotoCategoryMaster PM
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id =PC.MultiPhotoCategoryId
		INNER JOIN sHrm.vEmployeeCommunication EC ON PC.ScopeSourceId =EC.EmployeeId 
		WHERE PM.Id=@rId AND PC.ScopeSourceTypeId = @rScopeSourceTypeId
	END

	RETURN ISNULL(@rPhotoCategoryScope,'') 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommunication].[fPhotoCategoryScopeGet](@rId int,@rScopeSourceTypeId smallint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rPhotoCategoryScope nvarchar(2000)

	IF @rScopeSourceTypeId=2021
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2017
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2016
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN   sSetup.tClassMaster CM ON CM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2005
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  DisplayTitle 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId 
	END
	
	IF @rScopeSourceTypeId=2014
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  HM.Title 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId 
	END 
	
	IF @rScopeSourceTypeId=2029
	BEGIN
		SELECT 
			  @rPhotoCategoryScope=COALESCE(@rPhotoCategoryScope+', ','') +  HM.Title 
		FROM
		sCommunication.tPhotoCategoryMaster PM
		INNER JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id =PC.PhotoCategoryId
		INNER JOIN sActivity.tHouseMaster HM ON HM.Id = PC.ScopeSourceId
		WHERE PM.Id=@rId AND PM.ScopeSourceTypeId = @rScopeSourceTypeId
	END
	
	RETURN ISNULL(@rPhotoCategoryScope,'') 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sConfig].[fDisplayFieldAdmissionFormGet](@rOrgId int)

RETURNS  @List TABLE (
		 IsBirth_Place bit,
		 IsFather_Name bit,
		 IsBirth_Taluka bit,
		 IsBirth_District bit,
		 IsBirth_State bit,
		 IsBirth_Country bit,
		 IsPrevious_School bit,
		 IsStudent_Photo bit,
		 IsACI_StreetOne bit,
		IsACI_StreetTwo bit,
		IsACI_StreetThree bit,
		IsACI_City bit,
		IsACI_State bit,
		IsACI_Country bit,
		IsACI_ZipCode bit,
		IsACI_ContactEmail bit,
		IsOtherDetails_Religion bit,
		IsOtherDetails_Family_Caste bit,
		IsOtherDetails_Nationality bit,
		IsOtherDetails_Mother_Tongue bit,
		IsOtherDetails_Aadhar_Number bit,
		IsOtherDetails_Other_Information bit,
		IsOtherDetails_Live_With bit,
		IsOtherDetails_Hostel_Required bit,

		IsTransportDetails_Transport_Required bit,
		IsTransportDetails_Qualification bit,
		IsTransportDetails_Occupation bit,
		IsTransportDetails_Email bit,
		IsTransportDetails_Yearly_Income bit,
		IsTransportDetails_Organization bit,
		IsTransportDetails_Designation bit,
		IsTransportDetails_OfficePhone bit,
		IsTransportDetails_Father_ExStudent bit,
		IsTransportDetails_Office_Address bit,
		IsTransportDetails_Photo bit,

		IsMotherInformation_Full_Name bit,
		IsMotherInformation_Mobile_No bit,
		IsMotherInformation_Qualification bit,
		IsMotherInformation_Occupation bit,
		IsMotherInformation_Email bit,
		IsMotherInformation_Yearly_Income bit,
		IsMotherInformation_Organization bit,
		IsMotherInformation_Designation bit,
		IsMotherInformation_OfficePhone bit,
		IsMotherInformation_Mother_ExStudent bit,
		IsMotherInformation_Office_Address bit,
		IsMotherInformation_Photo bit,
		IsMotherInformation_Class bit,
		IsMotherInformation_Academic_Year bit,
		IsMotherInformation_Institute_Name bit,
		IsMotherInformation_Institute_City bit,
		IsMotherInformation_Institute_Affiliaton bit,	
		IsMotherInformation_Medium_of_Study bit,

		IsReference_Detail bit,
		IsReference_Name bit,
		IsReference_Relation bit,
		IsReference_ContactNo bit,
		 OrgId smallint 
		 )  

WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rIsBirth_Place bit 
	DECLARE @rIsFather_Name bit 
    DECLARE @rIsBirth_Taluka bit
    DECLARE @rIsBirth_District bit 
    DECLARE @rIsBirth_State bit
    DECLARE @rIsBirth_Country bit
    DECLARE @rIsPrevious_School bit
    DECLARE @rIsStudent_Photo bit
    
	DECLARE @rIsACI_StreetOne bit
	DECLARE @rIsACI_StreetTwo bit
	DECLARE @rIsACI_StreetThree bit
	DECLARE @rIsACI_City bit
	DECLARE @rIsACI_State bit
	DECLARE @rIsACI_Country bit
	DECLARE @rIsACI_ZipCode bit
	DECLARE @rIsACI_ContactEmail bit
	DECLARE @rIsOtherDetails_Religion bit
	DECLARE @rIsOtherDetails_Family_Caste bit
	DECLARE @rIsOtherDetails_Nationality bit
	DECLARE @rIsOtherDetails_Mother_Tongue bit
	DECLARE @rIsOtherDetails_Aadhar_Number bit
	DECLARE @rIsOtherDetails_Other_Information bit
	DECLARE @rIsOtherDetails_Live_With bit
	DECLARE @rIsOtherDetails_Hostel_Required bit

	DECLARE @rIsTransportDetails_Transport_Required bit
	DECLARE @rIsTransportDetails_Qualification bit
	DECLARE @rIsTransportDetails_Occupation bit
	DECLARE @rIsTransportDetails_Email bit
	DECLARE @rIsTransportDetails_Yearly_Income bit
	DECLARE @rIsTransportDetails_Organization bit
	DECLARE @rIsTransportDetails_Designation bit
	DECLARE @rIsTransportDetails_OfficePhone bit
	DECLARE @rIsTransportDetails_Father_ExStudent bit
	DECLARE @rIsTransportDetails_Office_Address bit
	DECLARE @rIsTransportDetails_Photo bit

	DECLARE @rIsMotherInformation_Full_Name bit
	DECLARE @rIsMotherInformation_Mobile_No bit
	DECLARE @rIsMotherInformation_Qualification bit
	DECLARE @rIsMotherInformation_Occupation bit
	DECLARE @rIsMotherInformation_Email bit
	DECLARE @rIsMotherInformation_Yearly_Income bit
	DECLARE @rIsMotherInformation_Organization bit
	DECLARE @rIsMotherInformation_Designation bit
	DECLARE @rIsMotherInformation_OfficePhone bit
	DECLARE @rIsMotherInformation_Mother_ExStudent bit
	DECLARE @rIsMotherInformation_Office_Address bit
	DECLARE @rIsMotherInformation_Photo bit
	DECLARE @rIsMotherInformation_Class bit
	DECLARE @rIsMotherInformation_Academic_Year bit
	DECLARE @rIsMotherInformation_Institute_Name bit
	DECLARE @rIsMotherInformation_Institute_City bit
	DECLARE @rIsMotherInformation_Institute_Affiliaton bit
	DECLARE @rIsMotherInformation_Medium_of_Study bit

	DECLARE @rIsReference_Detail bit
	DECLARE @rIsReference_Name bit
	DECLARE @rIsReference_Relation bit
	DECLARE @rIsReference_ContactNo bit
	
	
	SELECT @rIsBirth_Place=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 301
	SELECT @rIsFather_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 302
	SELECT @rIsBirth_Taluka =DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 303
	SELECT @rIsBirth_District=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 304
	SELECT @rIsBirth_State=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 305
	SELECT @rIsBirth_Country=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 306
	SELECT @rIsPrevious_School=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 307
	SELECT @rIsStudent_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 308
	
	SELECT @rIsACI_StreetOne=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 309
	SELECT @rIsACI_StreetTwo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 310
	SELECT @rIsACI_StreetThree=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 311
	SELECT @rIsACI_City=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 312
	SELECT @rIsACI_State=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 313
	SELECT @rIsACI_Country=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 314
	SELECT @rIsACI_ZipCode=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 315
	SELECT @rIsACI_ContactEmail=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 316
	
	SELECT @rIsOtherDetails_Religion=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 317
	SELECT @rIsOtherDetails_Family_Caste=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 318
	SELECT @rIsOtherDetails_Nationality=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 319
	SELECT @rIsOtherDetails_Mother_Tongue=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 320
	SELECT @rIsOtherDetails_Aadhar_Number=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 321
	SELECT @rIsOtherDetails_Other_Information=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 322
	SELECT @rIsOtherDetails_Live_With=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 323
	SELECT @rIsOtherDetails_Hostel_Required=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 324
	
	
	SELECT @rIsTransportDetails_Transport_Required=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 325
	SELECT @rIsTransportDetails_Qualification=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 326
	SELECT @rIsTransportDetails_Occupation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 327
	SELECT @rIsTransportDetails_Email=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 328
	SELECT @rIsTransportDetails_Yearly_Income=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 329
	SELECT @rIsTransportDetails_Organization=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 330
	SELECT @rIsTransportDetails_Designation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 331 
	SELECT @rIsTransportDetails_OfficePhone=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 332 
	SELECT @rIsTransportDetails_Father_ExStudent=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 333 
	SELECT @rIsTransportDetails_Office_Address=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 334 
	SELECT @rIsTransportDetails_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId =335  
	
	SELECT @rIsMotherInformation_Full_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 336
	SELECT @rIsMotherInformation_Mobile_No=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 337
	SELECT @rIsMotherInformation_Qualification=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 338
	SELECT @rIsMotherInformation_Occupation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 339
	SELECT @rIsMotherInformation_Email=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 340
	SELECT @rIsMotherInformation_Yearly_Income=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 341
	SELECT @rIsMotherInformation_Organization=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 342
	SELECT @rIsMotherInformation_Designation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 343
	SELECT @rIsMotherInformation_OfficePhone=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 344
	SELECT @rIsMotherInformation_Mother_ExStudent=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 345
	SELECT @rIsMotherInformation_Office_Address=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 346
	SELECT @rIsMotherInformation_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 347
	SELECT @rIsMotherInformation_Class=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 348
	SELECT @rIsMotherInformation_Academic_Year=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 349
	SELECT @rIsMotherInformation_Institute_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 350
	SELECT @rIsMotherInformation_Institute_City=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 351
	SELECT @rIsMotherInformation_Institute_Affiliaton=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 352 
	SELECT @rIsMotherInformation_Medium_of_Study=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 353
	
	
	SELECT @rIsReference_Detail=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 354
	SELECT @rIsReference_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 355
	SELECT @rIsReference_Relation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 356
	SELECT @rIsReference_ContactNo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 357
	

	
	INSERT INTO @List 
	SELECT 
   (CASE WHEN @rIsBirth_Place Is Null THEN  0 ELSE 1 END) AS IsBirth_Place ,
   (CASE WHEN @rIsFather_Name Is Null THEN 0 ELSE 1 END)AS IsFather_Name,
   (CASE WHEN @rIsBirth_Taluka Is Null THEN 0 ELSE 1 END)AS IsBirth_Taluka,
   (CASE WHEN @rIsBirth_State Is Null THEN 0  ELSE 1 END)AS IsBirth_State,
   (CASE WHEN @rIsBirth_Country Is Null THEN 0  ELSE 1 END)AS IsBirth_Country,
   (CASE WHEN @rIsBirth_State Is Null THEN 0  ELSE 1 END)AS IsBirth_State,
   (CASE WHEN @rIsPrevious_School Is Null THEN 0  ELSE 1 END)AS IsPrevious_School,
   (CASE WHEN @rIsStudent_Photo Is Null THEN 0  ELSE 1 END)AS IsStudent_Photo,
   
   (CASE WHEN @rIsACI_StreetOne Is Null THEN 0  ELSE 1 END)AS IsACI_StreetOne ,
   (CASE WHEN @rIsACI_StreetTwo Is Null THEN 0  ELSE 1 END)AS IsACI_StreetTwo ,
   (CASE WHEN @rIsACI_StreetThree Is Null THEN 0  ELSE 1 END)AS IsACI_StreetThree ,
   (CASE WHEN @rIsACI_City Is Null THEN 0  ELSE 1 END)AS IsACI_City ,
   (CASE WHEN @rIsACI_State  Is Null THEN 0  ELSE 1 END)AS IsACI_State ,
   (CASE WHEN @rIsACI_Country  Is Null THEN 0  ELSE 1 END)AS IsACI_Country ,
   (CASE WHEN @rIsACI_ZipCode  Is Null THEN 0  ELSE 1 END)AS IsACI_ZipCode ,
   (CASE WHEN @rIsACI_ContactEmail  Is Null THEN 0  ELSE 1 END)AS IsACI_ContactEmail ,
   
   (CASE WHEN @rIsOtherDetails_Religion  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Religion ,
   (CASE WHEN @rIsOtherDetails_Family_Caste  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Family_Caste ,
   (CASE WHEN @rIsOtherDetails_Nationality  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Nationality ,
   (CASE WHEN @rIsOtherDetails_Mother_Tongue  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Mother_Tongue ,
   (CASE WHEN @rIsOtherDetails_Aadhar_Number  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Aadhar_Number ,
   (CASE WHEN @rIsOtherDetails_Other_Information  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Other_Information ,
   (CASE WHEN @rIsOtherDetails_Live_With  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Live_With ,
   (CASE WHEN @rIsOtherDetails_Hostel_Required  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Hostel_Required ,
   
   (CASE WHEN @rIsTransportDetails_Transport_Required  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Transport_Required ,
   (CASE WHEN @rIsTransportDetails_Qualification  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Qualification ,
   (CASE WHEN @rIsTransportDetails_Occupation  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Occupation ,
   (CASE WHEN @rIsTransportDetails_Email  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Email ,
   (CASE WHEN @rIsTransportDetails_Yearly_Income  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Yearly_Income ,
   (CASE WHEN @rIsTransportDetails_Organization  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Organization ,
   (CASE WHEN @rIsTransportDetails_Designation  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Designation ,
   (CASE WHEN @rIsTransportDetails_OfficePhone  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_OfficePhone ,
   (CASE WHEN @rIsTransportDetails_Father_ExStudent  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Father_ExStudent ,
   (CASE WHEN @rIsTransportDetails_Office_Address  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Office_Address ,
   (CASE WHEN @rIsTransportDetails_Photo Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Photo  ,
   
   (CASE WHEN @rIsMotherInformation_Full_Name  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Full_Name ,
   (CASE WHEN @rIsMotherInformation_Mobile_No  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Mobile_No ,
   (CASE WHEN @rIsMotherInformation_Qualification  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Qualification ,
   (CASE WHEN @rIsMotherInformation_Occupation  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Occupation ,
   (CASE WHEN @rIsMotherInformation_Email  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Email ,
   (CASE WHEN @rIsMotherInformation_Yearly_Income  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Yearly_Income ,
   (CASE WHEN @rIsMotherInformation_Organization  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Organization ,
   (CASE WHEN @rIsMotherInformation_Designation  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Designation ,
   (CASE WHEN @rIsMotherInformation_OfficePhone  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_OfficePhone ,
   (CASE WHEN @rIsMotherInformation_Mother_ExStudent  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Mother_ExStudent ,
   (CASE WHEN @rIsMotherInformation_Office_Address  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Office_Address ,
   (CASE WHEN @rIsMotherInformation_Photo  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Photo ,
   (CASE WHEN @rIsMotherInformation_Class  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Class ,
   (CASE WHEN @rIsMotherInformation_Academic_Year  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Academic_Year ,
   (CASE WHEN @rIsMotherInformation_Institute_Name  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_Name ,
   (CASE WHEN @rIsMotherInformation_Institute_City  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_City ,
   (CASE WHEN @rIsMotherInformation_Institute_Affiliaton  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_Affiliaton ,
   (CASE WHEN @rIsMotherInformation_Medium_of_Study  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Medium_of_Study ,
   
   (CASE WHEN @rIsReference_Detail  Is Null THEN 0  ELSE 1 END)AS IsReference_Detail ,
   (CASE WHEN @rIsReference_Name  Is Null THEN 0  ELSE 1 END)AS IsReference_Name ,
   (CASE WHEN @rIsReference_Relation  Is Null THEN 0  ELSE 1 END)AS IsReference_Relation ,
   (CASE WHEN @rIsReference_ContactNo  Is Null THEN 0  ELSE 1 END)AS IsReference_ContactNo ,
   
   @rOrgId AS OrgId		  
    
   RETURN  
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sConfig].[fDisplayFieldGet](@rOrgId int)
RETURNS  @List TABLE (
		-- DisplayFieldId smallint,
		 IsDisplayFamilyDetail bit,
		 IsDisplaySiblingDetail bit,
		 IsDisplayPassportDetail bit,
		 IsDisplayBankDetail bit,
		 IsDisplayCBSEREGDetail bit,
		 IsDisplayCollegeDetail bit,
		 IsDisplayGOVREGNoDetail bit,
		 IsDisplayHealthDetail bit,
		 IsDisplayTransportDetail bit,
		 IsDisplayHostelDetail bit,
		 IsDisplayClubDetail bit,
		 IsDisplaySSCResultDDetail bit,
		 IsDisplayHSCResultDetail bit,
		 IsDisplayJeeDetail bit,
		 IsDisplayDiplomaDetail bit,
		 IsDisplayClassTeacherDetail bit,
		 IsDisplayAdmissionDetail bit,
		 OrgId smallint 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rDisplayFieldId smallint 
    declare @rIsDisplayFamilyDetail bit
    declare @rIsDisplaySiblingDetail bit 
    declare @rIsDisplayPassportDetail bit
    declare @rIsDisplayBankDetail bit 
    declare @rIsDisplayCBSEREGDetail bit 
    declare @rIsDisplayCollegeDetail bit 
    declare @rIsDisplayGOVREGNoDetail bit 
    declare @rIsDisplayHealthDetail bit 
    declare @rIsDisplayTransportDetail bit 
    declare @rIsDisplayHostelDetail bit 
    declare @rIsDisplayClubDetail bit 
    declare @rIsDisplaySSCResultDDetail bit 
    declare @rIsDisplayHSCResultDetail bit 
    declare @rIsDisplayJeeDetail bit 
    declare @rIsDisplayDiplomaDetail bit 
    declare @rIsDisplayClassTeacherDetail bit
	declare @rIsDisplayAdmissionDetail bit

	select @rIsDisplayFamilyDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 101
	select @rIsDisplaySiblingDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 102
	select @rIsDisplayPassportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 103
	select @rIsDisplayBankDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 104
	select @rIsDisplayCBSEREGDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 105
	select @rIsDisplayCollegeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 106
	select @rIsDisplayGOVREGNoDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 107
	select @rIsDisplayHealthDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 108
	select @rIsDisplayTransportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 109
	select @rIsDisplayHostelDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 110
	select @rIsDisplayClubDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 111
	select @rIsDisplaySSCResultDDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 112
	select @rIsDisplayHSCResultDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 113
	select @rIsDisplayJeeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 114
	select @rIsDisplayDiplomaDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 115
	select @rIsDisplayClassTeacherDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 117
	select @rIsDisplayAdmissionDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1225
		 
	 	
	INSERT INTO @List 
	SELECT 
			
			
		   (CASE WHEN @rIsDisplayFamilyDetail Is Null THEN  0 ELSE 1 END) AS IsDisplayFamilyDetail,
		   (CASE WHEN @rIsDisplaySiblingDetail Is Null THEN 0 ELSE 1 END)AS IsDisplaySiblingDetail,
		   (CASE WHEN @rIsDisplayPassportDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayPassportDetail,
		   (CASE WHEN @rIsDisplayBankDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayBankDetail,
		   (CASE WHEN @rIsDisplayCBSEREGDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayCBSEREGDetail,
		   (CASE WHEN @rIsDisplayCollegeDetail Is Null THEN 0  ELSE 1 END)AS IsIsDisplayCollegeDetail,
		   (CASE WHEN @rIsDisplayGOVREGNoDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayGOVREGNoDetail,
		   (CASE WHEN @rIsDisplayHealthDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHealthDetail,
		   (CASE WHEN @rIsDisplayTransportDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayTransportDetail,
		   (CASE WHEN @rIsDisplayHostelDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHostelDetail,
		   (CASE WHEN @rIsDisplayClubDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClubDetail,
		   (CASE WHEN @rIsDisplaySSCResultDDetail Is Null THEN 0  ELSE 1 END)AS IsDisplaySSCResultDDetail,
		   (CASE WHEN @rIsDisplayHSCResultDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHSCResultDetail,
		   (CASE WHEN @rIsDisplayJeeDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayJeeDetail,
		   (CASE WHEN @rIsDisplayDiplomaDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayDiplomaDetail,
		   (CASE WHEN @rIsDisplayClassTeacherDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClassTeacherDetail,
		   (CASE WHEN @rIsDisplayAdmissionDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayAdmissionDetail,
		   @rOrgId AS OrgId
		  
	 
    RETURN  
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sConfig].[fDisplayFieldLeavingGet](@rOrgId int)

RETURNS  @List TABLE (
		 IsAttendance bit,
		 IsFee bit,
		 IsExam bit,
		 IsOther bit,
		 OrgId smallint 
		 )  

WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rIsAttendance bit 
	DECLARE @rIsFee bit 
    DECLARE @rIsExam bit
    DECLARE @rIsOther bit 
     
	SELECT @rIsAttendance=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 213
	SELECT @rIsFee=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 214
	SELECT @rIsExam =DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 215
	SELECT @rIsOther=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 216
	 	
	INSERT INTO @List 
	SELECT 
   (CASE WHEN @rIsAttendance Is Null THEN  0 ELSE 1 END) AS IsAttendance,
   (CASE WHEN @rIsFee Is Null THEN 0 ELSE 1 END)AS IsFee,
   (CASE WHEN @rIsExam Is Null THEN 0 ELSE 1 END)AS IsExam,
   (CASE WHEN @rIsOther Is Null THEN 0  ELSE 1 END)AS IsOther,
   @rOrgId AS OrgId		  
    
   RETURN  
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sConfig].[fDisplayFieldLessionGet](@rOrgId int)
RETURNS  @List TABLE (
		 IsObjective bit,
		 IsSummary bit,
		 IsLearningExperience bit,
		 IsEssentialMaterial bit,
		 IsToolsTechniques bit,
		 IsIndicativeHomework bit,
		 IsAssessmentQuestion bit,
		 IsTeacherExample bit,
		 IsGuidedPractice bit,
		 IsIndependentPractice bit,
		 IsSubTopicSelect bit,
		 IsSubTopicText bit,
		 IsSession bit,
		 IsTrainingMethod bit,
		 IsPeriodCount bit,
		 OrgId smallint,
		 IsRemark bit,
		 IsAttachment bit
		 
		 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rIsObjective bit 
	declare @rIsSummary bit 
    declare @rIsLearningExperience bit
    declare @rIsEssentialMaterial bit 
    declare @rIsToolsTechniques bit
    declare @rIsIndicativeHomework bit 
    declare @rIsAssessmentQuestion bit 
    declare @rIsTeacherExample bit 
    declare @rIsGuidedPractice bit 
    declare @rIsIndependentPractice bit
    declare @rIsSubTopicSelect bit
    declare @rIsSubTopicText bit
	declare @rIsSession bit
	declare @rIsTrainingMethod bit
	declare @rIsPeriodCount bit
	declare @rIsRemark bit
	declare @rIsAttachment bit
   
	select @rIsObjective=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 201
	select @rIsSummary=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 203
	select @rIsLearningExperience =DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 202
	select @rIsEssentialMaterial=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 204
	select @rIsToolsTechniques=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 205
	select @rIsIndicativeHomework=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 206
	select @rIsAssessmentQuestion=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 207
	select @rIsTeacherExample=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 208
	select @rIsGuidedPractice=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 209
	select @rIsIndependentPractice=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 210
	select @rIsSubTopicSelect=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 211
	select @rIsSubTopicText=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 212
	select @rIsSession=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1219
	select @rIsTrainingMethod=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1220
	select @rIsPeriodCount=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1221
	select @rIsRemark = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1223
	select @rIsAttachment = DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 1224
	 	
	INSERT INTO @List 
	SELECT 
		(CASE WHEN @rIsObjective Is Null THEN  0 ELSE 1 END) AS IsObjective,
		(CASE WHEN @rIsSummary Is Null THEN 0 ELSE 1 END)AS IsSummary,
		(CASE WHEN @rIsLearningExperience Is Null THEN 0 ELSE 1 END)AS IsLearningExperience,
		(CASE WHEN @rIsEssentialMaterial Is Null THEN 0  ELSE 1 END)AS IsEssentialMaterial,
		(CASE WHEN @rIsToolsTechniques Is Null THEN 0  ELSE 1 END)AS IsToolsTechniques,
		(CASE WHEN @rIsIndicativeHomework Is Null THEN 0  ELSE 1 END)AS IsIndicativeHomework,
		(CASE WHEN @rIsAssessmentQuestion Is Null THEN 0  ELSE 1 END)AS IsAssessmentQuestion ,
		(CASE WHEN @rIsTeacherExample Is Null THEN 0 ELSE  1 END)AS  IsTeacherExample,
		(CASE WHEN @rIsGuidedPractice Is Null THEN 0  ELSE 1 END)AS IsGuidedPractice,
		(CASE WHEN @rIsIndependentPractice Is Null THEN 0 ELSE  1 END)AS IsIndependentPractice,
		(CASE WHEN @rIsSubTopicSelect Is Null THEN 0 ELSE  1 END)AS IsSubTopicSelect,
		(CASE WHEN @rIsSubTopicText Is Null THEN 0 ELSE  1 END)AS IsSubTopicText,
		(CASE WHEN @rIsSession Is Null THEN 0 ELSE  1 END)AS IsSession,
		(CASE WHEN @rIsTrainingMethod Is Null THEN 0 ELSE  1 END)AS IsTrainingMethod,
		(CASE WHEN @rIsPeriodCount Is Null THEN 0 ELSE  1 END)AS IsPeriodCount,
		@rOrgId AS OrgId,
		(CASE WHEN @rIsRemark Is Null THEN 0 ELSE  1 END)AS IsRemark,		  
		(CASE WHEN @rIsAttachment Is Null THEN 0 ELSE  1 END)AS IsAttachment
    RETURN  
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sEExam].[fCheckIsHTMLGet](@rTestId int)
RETURNS bit WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lIsHTML bit
DECLARE @lCount int

	SELECT @lCount = COUNT(*) 
	FROM 
	sEExam.tQuestionMaster QM 
	INNER JOIN sEExam.tQuestionOption QO ON QM.Id = QO.QuestionId 
	INNER JOIN sEExam.tTestQuestion TQ ON TQ.QuestionId = QO.QuestionId
	WHERE 
	TQ.TestId = @rTestId 
	AND 
	(
	QO.ChoiceDescription LIKE '%<span>%' 
	OR QO.ChoiceDescription LIKE '%<%' 
	OR QO.ChoiceDescription LIKE '%>%'
	OR QM.QuestionDescription LIKE '%<span>%' 
	OR QM.QuestionDescription LIKE '%<%' 
	OR QM.QuestionDescription LIKE '%>%' 
	)
    
    IF(@lCount > 0)
		SET @lIsHTML = 1
	ELSE
		SET @lIsHTML = 0
    
    RETURN ISNULL(@lIsHTML,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sEExam].[fPortalXMLTagsReplaceReverse](@lString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN
    SET  @lString =   REPLACE(REPLACE
                                     (REPLACE
                                     (REPLACE
                                     (REPLACE(@lString,'#amp;','&'),
                                                                  '#gt;','>'), 
                                                                  '#quot;', '"'), 
                                                                  '#lt;','<'),
                                                                  '#39;', '''')
    RETURN @lString
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fChargeReceiptNumberGet](@rReceiptBookId int,@rOrgGroupBatchId int)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

      DECLARE @lChargeReceiptNumber int
	  Declare @lResult  int
     select @lChargeReceiptNumber= max(ReceiptNumber) from sFee.tChargeReceipt where ChargeReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId
	IF(@lChargeReceiptNumber IS NULL)  
	BEGIN
		SET @lResult = 1
	END
	ELSE
	BEGIN
		 SET @lResult= @lChargeReceiptNumber + 1
	END    

   return  @lResult 
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fCheckEntryPaymentTransactionGet](@rReceiptBookId int, @rGatewayConfigurationId int)
RETURNS BIT WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lResult BIT = 1
	
	IF EXISTS (
			   SELECT 1 FROM sOp.tPaymentTransaction PT
			   INNER JOIN sFee.tOnlineFee tOF ON tOF.Id = PT.TransactionSourceId AND PT.TransactionSourceTypeId = 2024
			   INNER JOIN sOp.tGatewayProductReceiptBookMapping GPRBM ON GPRBM.ReceiptBookId = tOF.ReceiptBookId
			   INNER JOIN sOp.tGatewayProduct GP ON GP.Id = GPRBM.GatewayProductId
			   WHERE tOF.ReceiptBookId = @rReceiptBookId AND GP.GatewayConfigurationId = @rGatewayConfigurationId
			   )
	BEGIN
		SET @lResult = 0
	END
	RETURN  @lResult 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fConvertDigit](@decNumber decimal)
returns varchar(6)
as
Begin
declare
@strWords varchar(6)
Select @strWords = Case @decNumber
When '1' then 'One'
When '2' then 'Two'
When '3' then 'Three'
When '4' then 'Four'
When '5' then 'Five'
When '6' then 'Six'
When '7' then 'Seven'
When '8' then 'Eight'
When '9' then 'Nine'
Else ''
end
return @strWords
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fConvertTens](@decNumber varchar(2))
returns varchar(30)
as
Begin
declare @strWords varchar(30)
--Is value between 10 and 19?
If Left(@decNumber, 1) = 1
begin
Select @strWords = Case @decNumber
When '10' then 'Ten'
When '11' then 'Eleven'
When '12' then 'Twelve'
When '13' then 'Thirteen'
When '14' then 'Fourteen'
When '15' then 'Fifteen'
When '16' then 'Sixteen'
When '17' then 'Seventeen'
When '18' then 'Eighteen'
When '19' then 'Nineteen'
end
end
else -- otherwise it's between 20 and 99.
begin
Select @strWords = Case Left(@decNumber, 1)
When '0' then ''
When '2' then 'Twenty '
When '3' then 'Thirty '
When '4' then 'Forty '
When '5' then 'Fifty '
When '6' then 'Sixty '
When '7' then 'Seventy '
When '8' then 'Eighty '
When '9' then 'Ninety '
end
Select @strWords = @strWords + sFee.fConvertDigit(Right(@decNumber, 1))
end
--Convert ones place digit.

return @strWords
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fDatewiseFromToReceiptNumberGet](@rReceiptBookId int,@rBatchId int,@rReceiptDate date)
RETURNS nvarchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @lFromNumber nvarchar(50)
    DECLARE @lToNumber nvarchar(50)
	DECLARE @lResult  nvarchar(100)
    SELECT @lFromNumber = MIN(ReceiptNumber) FROM sFee.tReceipt WHERE ReceiptBookId=@rReceiptBookId AND BatchId = @rBatchId AND ReceiptDate = @rReceiptDate
    SELECT @lToNumber = MAX(ReceiptNumber) FROM sFee.tReceipt WHERE ReceiptBookId=@rReceiptBookId AND BatchId = @rBatchId AND ReceiptDate = @rReceiptDate
    SET @lResult = @lFromNumber +' to '+ @lToNumber
    RETURN  @lResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fDepositHeadNameGet](@rDepositHeadId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rDepositName nvarchar(max)=''

Select @rDepositName=@rDepositName + isnull(DM.Title,'') 

FROM  sFee.tDepositHeadMaster DM
          WHERE 
           (DM.Id=@rDepositHeadId)
      RETURN  isnull(@rDepositName,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeActualAmountSumGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalFeeAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, 
	@rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,
	@lAdmissionCategoryId=AdmissionCategoryId 
	FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalFeeAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00))
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
			 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			    --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
					((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.Id = @rAcademicId
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId

		WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN @rTotalFeeAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeActualAmountSumGet_OGOLD] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalFeeAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalFeeAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId

		WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN @rTotalFeeAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--ALTER FUNCTION [sFee].[fFeeAllocationRemarkGet](@rAcademicId bigint,@rRemarkId int)
CREATE OR ALTER FUNCTION [sFee].[fFeeAllocationRemarkGet](@rAcademicId bigint)
RETURNS nvarchar(4000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeAllocationRemark  nvarchar(4000)

(SELECT 
			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.DiscountRemark
			 FROM
		 sFee.tFeeAllocation F			  
		 WHERE F.SourceId = @rAcademicId 
		  )

--IF(@rRemarkId =1)
--BEGIN
--(SELECT 
--			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.DiscountRemark
--			 FROM
--			 sFee.tFeeAllocation F			  
--			 WHERE F.SourceId = @rAcademicId 
--			  )
--	END
--	ELSE IF(@rRemarkId=2)
--	BEGIN
--	(SELECT 
--			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.Remark
--			 FROM
--			 sFee.tFeeAllocation F			  
--			 WHERE F.SourceId = @rAcademicId 
--			  )
--	END
--	ELSE IF(@rRemarkId=3)
--	BEGIN
--	(SELECT 
--			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.AdditionalRemark
--			 FROM
--			 sFee.tFeeAllocation F			  
--			 WHERE F.SourceId = @rAcademicId 
--			  )
--	END
--	ELSE IF(@rRemarkId=4)
--	BEGIN
--	 (SELECT 
--			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.NotApplicableRemark
--			 FROM
--			 sFee.tFeeAllocation F			  
--			 WHERE F.SourceId = @rAcademicId 
--			  )
--	END
  RETURN ISNULL(@rFeeAllocationRemark,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fFeeAmountReceiptBookWiseSumGet] (@rAcademicId bigint,@rReceiptBookId int, @rType nvarchar(20))
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = CASE When @rType = 'TotalAmount' then SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00))
								ELSE SUM(ISNULL(R.PaidAmount,0.00)) END
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeAmountSumGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalFeeAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId = OrgGroupBatchId
		,@rOrgId = OrgId
		,@rBatchId = BatchId
		,@lClassId = ClassId
		,@lDivisionId = DivisionId
		,@lAdmissionCategoryId = AdmissionCategoryId
	FROM sStudent.vStudentAcademic
	WHERE AcademicId = @rAcademicId

    (
    SELECT 
		@rTotalFeeAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) 
								-ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00))
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN --sStudent.vStudentAcademic SA1 
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			    --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
					((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.Id = @rAcademicId
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN --sStudent.vStudentAcademic SA1
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.Id=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
		WHERE
		        --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND  -- Removed as changed View to Academic Table for Optimization by Foram
				 ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.Id = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN @rTotalFeeAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeAmountSumGet_OGOLD] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalFeeAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalFeeAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId

		WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN @rTotalFeeAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeAndFeeHeadNameGet](@rReceiptId bigint, @rFeeHeadId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(200)
DECLARE @rLastFee nvarchar(200)
DECLARE @rResult nvarchar(200)

SELECT TOP 1 
			 @rFirstFee =F.Title
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		     @rLastFee = F.Title
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sFee].[fFeeHeadMonthDetailGet](@rReceiptId bigint, @rFeeHeadId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(20)
DECLARE @rLastFee nvarchar(20)
DECLARE @rResult nvarchar(20)

SELECT TOP 1 
		@rFirstFee = F.Code
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		@rLastFee = F.Code
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeHeadMonthNameGet](@rReceiptId BIGINT, @rFeeHeadId INT)
RETURNS NVARCHAR(200) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rResult NVARCHAR(200)

    ;WITH FeeMonths AS
    (
        SELECT 
            FirstFee = [sCommon].[fGetMonthName](Month(S.StartDate)),
            LastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
        FROM 
            sFee.tReceiptDetail D
        INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
        INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
        WHERE 
            D.ReceiptId = @rReceiptId 
            AND F.FeeHeadId = @rFeeHeadId
            AND F.Number <> 100
        ORDER BY F.OrderIndex
        OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
    )
    SELECT 
        @rResult = 
            CASE 
                WHEN FirstFee = LastFee THEN FirstFee
                ELSE FirstFee + ' To ' + LastFee
            END
    FROM FeeMonths

    RETURN @rResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeHeadMonthNameGet_OGOLD](@rReceiptId bigint, @rFeeHeadId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(20)
DECLARE @rLastFee nvarchar(20)
DECLARE @rResult nvarchar(20)

SELECT TOP 1 
		@rFirstFee =[sCommon].[fGetMonthName](Month(S.StartDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		@rLastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.FeeHeadId=@rFeeHeadId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeMonthNameGet](@rReceiptId BIGINT, @rFeeId INT)
RETURNS NVARCHAR(200) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rResult NVARCHAR(200)

    ;WITH FeeMonths AS
    (
        SELECT 
            FirstFee = [sCommon].[fGetMonthName](Month(S.StartDate)),
            LastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
        FROM 
            sFee.tReceiptDetail D
        INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
        INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
        WHERE 
            D.ReceiptId = @rReceiptId 
            AND F.Id = @rFeeId
            AND F.Number <> 100
        ORDER BY F.OrderIndex
        OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
    )
    SELECT 
        @rResult = 
            CASE 
                WHEN FirstFee = LastFee THEN FirstFee
                ELSE FirstFee + ' To ' + LastFee
            END
    FROM FeeMonths

    RETURN @rResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sFee].[fFeeMonthNameGet_OGOLD](@rReceiptId bigint, @rFeeId int)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFirstFee nvarchar(20)
DECLARE @rLastFee nvarchar(20)
DECLARE @rResult nvarchar(20)

SELECT TOP 1 
		@rFirstFee =[sCommon].[fGetMonthName](Month(S.StartDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.Id=@rFeeId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex

SELECT TOP 1 
		@rLastFee = [sCommon].[fGetMonthName](Month(S.EndDate))
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId AND F.Id=@rFeeId
			 AND F.Number <> 100	
			 ORDER BY F.OrderIndex DESC			 
			 
			 IF(@rFirstFee=@rLastFee)
			 BEGIN
				SET @rResult = @rFirstFee
			 END
			 ELSE
			 BEGIN
				SET @rResult = @rFirstFee	+ ' To ' +	@rLastFee
			 END
			 
			 RETURN @rResult
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeReceiptDiscountSumGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalDicountAmount decimal(12,0)--,@rBatchId int, @rOrgId int
    --SELECT @rOrgId=OrgId,@rBatchId=BatchId FROM sStudent.tAcademic WHERE Id = @rAcademicId -- Commented for optmization By Foram
    
    (
    SELECT 
		@rTotalDicountAmount = SUM(ISNULL(FA.DiscountAmount,0.00))
    FROM 
			 sStudent.tAcademic A
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=A.Id AND FA.SourceTypeId = 2001
	WHERE	
		A.Id = @rAcademicId
		--AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))	-- Commented for optmization By Foram
		--AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))  -- Commented for optmization By Foram
	)
			
	RETURN ISNULL(@rTotalDicountAmount,0) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fFeeReceiptDiscountSumGet_OGOLD] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalDicountAmount decimal(12,0),@rBatchId int, @rOrgId int
    SELECT @rOrgId=OrgId,@rBatchId=BatchId FROM sStudent.tAcademic WHERE Id = @rAcademicId
    
    (
    SELECT 
		@rTotalDicountAmount = SUM(ISNULL(FA.DiscountAmount,0.00))
    FROM 
			 sStudent.tAcademic A
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=A.Id AND FA.SourceTypeId = 2001
		WHERE	
			A.Id = @rAcademicId
			AND ((A.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0)) 
			)
			
	RETURN ISNULL(@rTotalDicountAmount,0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId int, @rReceiptId bigint)
RETURNS  @List TABLE (
		PendingAmount decimal(12,2),
		CollectionGroupId int,
		StartDate date,
		EndDate date,
		CollectionGroupName nvarchar(100),
		OrderIndex smallint,
		ReceiptId bigint,
		SourceId bigint,
		SourceTypeId smallint
)  
WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	DECLARE @lSourceId bigint, @lSourceTypeId int, @lBatchId int
	--DECLARE @lConfigValue nvarchar(50)

	SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId FROM sFee.tReceipt WHERE Id = @rReceiptId
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId, @lBatchId=BatchId FROM sStudent.vStudentAcademic WHERE AcademicId=@lSourceId	
	SELECT @lOrgGorupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	-- Start mantisid - 0032734 
	DECLARE @lReceiptStartDate Date
	SELECT @lReceiptStartDate = CGM1.StartDate
								FROM
									sFee.tReceipt R 
									INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id	
									INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
									INNER JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FSR.CollectionGroupId 
								WHERE						
									(R.ReceiptBookId = 0	OR 0 = 0)	
									AND R.SourceId= @lSourceId
									AND ((R.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
									AND R.IsObsolete = 0 	
									AND R.Id = @rReceiptId		 
								GROUP BY FeeSetupId,R.Id,CGM1.StartDate

	-- End mantisid - 0032734 
	
	INSERT INTO @List 
	SELECT TOP 1 *, @lSourceId AS SourceId, @lSourceTypeId AS SourceTypeId FROM
	(
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount,
			CollectionGroupId,
			StartDate,
			EndDate,
			CollectionGroupName,
			OrderIndex,
			ReceiptId
		FROM
		(SELECT	
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			FS.CollectionGroupId,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Title AS CollectionGroupName,
			CGM.OrderIndex,
			R.ReceiptId
		 FROM 
			sFee.tFeeMaster FM
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @lBatchId
					AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lSourceId) AND ((FO.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
				WHERE
					FS1.ClassId=@lClassId 
					AND FS1.BatchId =@lBatchId 
					AND FS1.AdmissionCategoryId=@lAdmissionCategoryId 
					AND IsOptional=1
			) FS ON FS.FeeId=FM.Id
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
			LEFT JOIN
			(
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,
					RD.FeeSetupId,
					R.Id AS ReceiptId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
				WHERE						
					(R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					AND R.SourceId= @lSourceId
					AND ((R.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))
					AND R.IsObsolete = 0 	
					AND R.Id = @rReceiptId		 
				GROUP BY FeeSetupId,R.Id
			) R ON R.FeeSetupId = FS.Id 
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lSourceId) AND ((FA.SourceTypeId=@lSourceTypeId) OR (@lSourceTypeId=0))			
			WHERE 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0))
				AND(FS.BatchId=@lBatchId)
				--AND (@lConfigValue = 'True' AND (CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)))
				AND CGM.IsObsolete = 0
				AND  @lReceiptStartDate <= CGM.StartDate -- mantisid - 0032734 
		) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,OrderIndex,ReceiptId
	) AS PendingFee
	ORDER BY PendingFee.StartDate,PendingFee.OrderIndex
		
	RETURN  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fnGetStockDepositeAdd](@StockIssueReturnId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lResult  VARCHAR(MAX)=''

	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SIRB.ReturnQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM 
	sProcurement.tStockIssueReturn SIR
	INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
	INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.Id = SIB.StockIssueDetailId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE 
	SIR.Id = @StockIssueReturnId
	)

	IF(@lResult = '')
	BEGIN
		SET @lResult = ''
	END
	ELSE
	BEGIN
		SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
	END
 
	RETURN @lResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE OR ALTER FUNCTION [sFee].[fnGetStockDepositeAddItemName](@StockIssueReturnId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lResult  VARCHAR(MAX)=''

	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + ', '
 
	FROM 
	sProcurement.tStockIssueReturn SIR
	INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
	INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.Id = SIB.StockIssueDetailId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE 
	SIR.Id = @StockIssueReturnId
	)

	IF(@lResult = '')
	BEGIN
		SET @lResult = ''
	END
	ELSE
	BEGIN
		SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
	END
 
	RETURN @lResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fnGetStockDepositeAdjustment](@StockIssueId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lResult  VARCHAR(MAX)=''
 
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SID.IssuedQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM sProcurement.tStockIssue SI 
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.StockIssueId = SI.Id
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE SI.Id = @StockIssueId
	)
 
 IF(@lResult = '')
 BEGIN
	SET @lResult = ''
 END
 ELSE
 BEGIN
	SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
 END
   
RETURN @lResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER FUNCTION [sFee].[fnGetStockDepositeAdjustmentItemName](@StockIssueId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lResult  VARCHAR(MAX)=''
 
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') 
			    + ', '
 
	FROM sProcurement.tStockIssue SI 
	INNER JOIN 
sProcurement.tStockIssueDetail SID ON SID.StockIssueId = SI.Id
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE SI.Id = @StockIssueId
	)
 
 IF(@lResult = '')
 BEGIN
	SET @lResult = ''
 END
 ELSE
 BEGIN
	SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
 END
   
RETURN @lResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fnGetSumByReceiptBookWise]
(
    @rAcademicId Bigint,
    @rBatchId INT,
    @rReceiptBookId INT
  --  @rSourceId INT
)
RETURNS DECIMAL(12, 2)
AS
BEGIN
    DECLARE @SumAmount DECIMAL(12, 2);
    
    SELECT @SumAmount = SUM(ISNULL(PDP.Amount, 0))
    FROM sFee.tPostDatePayment PDP

    where BatchId = @rBatchId
      AND ReceiptBookId = @rReceiptBookId
      AND SourceId = @rAcademicId
	  AND SourceTypeId = 2001

	  

    RETURN @SumAmount;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fNumToWords] (@decNumber decimal(12, 2))
returns varchar(300)
As
Begin
Declare
@strNumber varchar(100),
@strRupees varchar(200),
@strPaise varchar(100),
@strWords varchar(300),
@intIndex integer,
@intAndFlag integer

Select @strNumber = Cast(@decNumber as varchar(100))
Select @intIndex = CharIndex('.', @strNumber)
if(@decNumber>99999999.99)
BEGIN
RETURN ''
END
If @intIndex > 0
begin
Select @strPaise = sFee.fConvertTens(Right(@strNumber, Len(@strNumber) - @intIndex))
Select @strNumber = SubString(@strNumber, 1, Len(@strNumber) - 3)
If Len(@strPaise) > 0 Select @strPaise = @strPaise + ' paise'
end
Select @strRupees = ''
Select @intIndex=len(@strNumber)
Select @intAndFlag=2
while(@intIndex>0)
begin
if(@intIndex=8)
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(left(@decNumber,1))+' Crore '
Select @strNumber=substring(@strNumber,2,len(@strNumber))
Select @intIndex=@intIndex-1

end
else if(@intIndex=7)
begin
if(substring(@strNumber,1,1)='0')
begin
if substring(@strNumber,2,1)<>'0'
begin
if (@strRupees<>NULL and substring(@strNumber,3,1)='0'
and substring(@strNumber,4,1)='0' and substring(@strNumber,5,1)='0'
and substring(@strNumber,6,1)='0' and substring(@strNumber,7,1)='0'
and @intAndFlag=2 and @strPaise=NULL)
begin
Select @strRupees=@strRupees+' ' +sFee.fConvertDigit(substring(@strNumber,2,1))+' Lakh '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,2,1))+' Lakh '
end

Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
else
begin
Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
end
else
begin
if(substring(@strNumber,3,1)='0' and substring(@strNumber,4,1)='0' and
substring(@strNumber,5,1)='0' and substring(@strNumber,6,1)='0' and
substring(@strNumber,7,1)='0' and @intAndFlag=2 and @strPaise='')
begin
Select @strRupees=@strRupees+' ' + sFee.fConvertTens(substring(@strNumber,1,2))+' Lakhs '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertTens(substring(@strNumber,1,2))+' Lakhs '
end
Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
end
else if(@intIndex=6)
begin
if(substring(@strNumber,2,1)<>'0' or substring(@strNumber,3,1)<>'0'
and substring(@strNumber,4,1)='0' and substring(@strNumber,5,1)='0' and
substring(@strNumber,6,1)='0' and @intAndFlag=2 and @strPaise='')
begin

if len(@strRupees) <= 0
begin
if convert(int,substring(@strNumber,1,1)) = 1
begin
Select @strRupees=@strRupees+'' + sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakh '
Select @intAndFlag=2
end
else
begin
Select @strRupees=@strRupees+'' + sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakhs '
Select @intAndFlag=2
end
end
else
begin
if convert(int,substring(@strNumber,1,1)) = 1
begin
Select @strRupees=@strRupees+' ' + sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakh '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+' ' + sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakhs '
Select @intAndFlag=1
end
end
end
else
begin
if convert(int,substring(@strNumber,1,1)) = 1
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakh '
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,1,1))+' Lakhs '
end
end
Select @strNumber=substring(@strNumber,2,len(@strNumber))
Select @intIndex=@intIndex-1
end
else if(@intIndex=5)
begin
if(substring(@strNumber,1,1)='0')
begin
if substring(@strNumber,2,1)<>'0'
begin
if(substring(@strNumber,3,1)='0' and substring(@strNumber,4,1)='0'
and substring(@strNumber,5,1)='0' and @intAndFlag=2 and @strPaise='')
begin
Select @strRupees=@strRupees+' ' +sFee.fConvertDigit(substring(@strNumber,2,1))+' Thousand '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,2,1))+' Thousand '
end
Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
else
begin
Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
end
else
begin
if(substring(@strNumber,3,1)='0' and substring(@strNumber,4,1)='0'
and substring(@strNumber,5,1)='0' and @intAndFlag=2 and @strPaise='')
begin
--Select @strRupees=@strRupees+'andjo'+sFee.fConvertTens(substring(@strNumber,1,2))+' Thousand '
Select @strRupees=@strRupees+sFee.fConvertTens(substring(@strNumber,1,2))+' Thousand '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertTens(substring(@strNumber,1,2))+' Thousand '
end
Select @strNumber=substring(@strNumber,3,len(@strNumber))
Select @intIndex=@intIndex-2
end
end
else if(@intIndex=4)
begin
if ( (substring(@strNumber,3,1)<>'0' or substring(@strNumber,4,1)<>'0') and
substring(@strNumber,2,1)='0' and @intAndFlag=2 and @strPaise='')
begin
Select @strRupees=@strRupees+' ' + sFee.fConvertDigit(substring(@strNumber,1,1))+' Thousand '
Select @intAndFlag=1
end
else
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,1,1))+' Thousand '
end
Select @strNumber=substring(@strNumber,2,len(@strNumber))
Select @intIndex=@intIndex-1
end
else if(@intIndex=3)
begin
if substring(@strNumber,1,1)<>'0'
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(substring(@strNumber,1,1))+' Hundred '
Select @strNumber=substring(@strNumber,2,len(@strNumber))

if( (substring(@strNumber,1,1)<>'0' or substring(@strNumber,2,1)<>'0') and
@intAndFlag=2 )
begin
Select @strRupees=@strRupees+' and '
Select @intAndFlag=1
end
Select @intIndex=@intIndex-1
end
else
begin
Select @strNumber=substring(@strNumber,2,len(@strNumber))
Select @intIndex=@intIndex-1
end
end
else if(@intIndex=2)
begin
if substring(@strNumber,1,1)<>'0'
begin
Select @strRupees=@strRupees+sFee.fConvertTens(substring(@strNumber,1,2))
Select @intIndex=@intIndex-2
end
else
begin
Select @intIndex=@intIndex-1
end
end
else if(@intIndex=1)
begin
if(@strNumber<>'0')
begin
Select @strRupees=@strRupees+sFee.fConvertDigit(@strNumber)
end
Select @intIndex=@intIndex-1

end
continue
end
--if len(@strRupees)>0 Select @strRupees=@strRupees+ ' rupees '
IF(len(@strPaise)<>0)
BEGIN
if len(@strRupees)>0 Select @strRupees=@strRupees + ' '
END
Select @strWords = IsNull(@strRupees, '') + IsNull(@strPaise, '')
--select @strWords = @strWords + ' only'
Return @strWords
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPaidFeeAmountAcademicIdwiseGet] (@rAcademicId bigint)
RETURNS decimal(12,2) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalPaidAmount decimal(12,2),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalPaidAmount = SUM(ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rTotalPaidAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPaidFeeAmountReceiptBookwiseGet] (@rAcademicId bigint,@rReceiptBookId int)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalPaidAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalPaidAmount = SUM(ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rTotalPaidAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountAcademicIdwiseGet] (@rAcademicId bigint)
RETURNS decimal(12,2) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,2),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountAsOnDatewiseGet] (@rAcademicId bigint, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int, @rUptoDate Date)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rReceiptDetail nvarchar(2000)
    DECLARE @lClassId int 
    DECLARE @lDivisionId int 
    DECLARE @lAdmissionCategoryId int
    
    SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId 
	FROM sStudent.vStudentAcademic
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
    
    (
    SELECT 
		@rReceiptDetail = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				--AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				--AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				--AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				--AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			--	AND Month(FS.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				--AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (FS.StartDate <= @rUptoDate)
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
	RETURN ISNULL(LEFT(@rReceiptDetail,LEN(@rReceiptDetail)-3),0) 
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountForAlertGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountGet] (@rAcademicId bigint, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int, @rMonthId int, @rUptoDate Date,@rReceiptBookId int,@rFeeId nvarchar(max)='')
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rReceiptDetail nvarchar(2000)
    DECLARE @lClassId int 
    DECLARE @lDivisionId int 
    DECLARE @lAdmissionCategoryId int
    
    SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId 
	FROM sStudent.vStudentAcademic
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
    
    (
    SELECT 
		@rReceiptDetail = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND Month(FS.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (FS.StartDate <= @rUptoDate)
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
	RETURN ISNULL(LEFT(@rReceiptDetail,LEN(@rReceiptDetail)-3),0) 
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountReceiptBookwiseGet] (
	@rAcademicId BIGINT
	,@rReceiptBookId INT
	)
RETURNS DECIMAL(12, 0)
	WITH EXECUTE AS CALLER
AS
BEGIN
	DECLARE @rReceiptAmount DECIMAL(12, 0)
		,@lClassId INT
		,@lDivisionId INT
		,@lAdmissionCategoryId INT
		,@rBatchId INT
		,@rOrgId INT
		,@rOrgGroupBatchId INT

	SELECT @rOrgGroupBatchId = OrgGroupBatchId
		,@rOrgId = OrgId
		,@rBatchId = BatchId
		,@lClassId = ClassId
		,@lDivisionId = DivisionId
		,@lAdmissionCategoryId = AdmissionCategoryId
	FROM sStudent.vStudentAcademic
	WHERE AcademicId = @rAcademicId 
	
	(SELECT @rReceiptAmount 
	= SUM(ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) 
	- ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00)) 
	
	FROM sStudent.vStudentAcademic SA INNER JOIN (
			SELECT FS1.FeeId
				,FS1.Id
				,ISNULL(FS1.IsOptional, 0) AS IsOptional
				,ISNULL(FS1.IsVariable, 0) AS IsVariable
				,ISNULL(FS1.Amount, 0) AS Amount
				,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
				,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
				,FS1.BatchId
				,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
				,SA1.Id AS AcademicId
				,FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN --sStudent.vStudentAcademic SA1 
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND (
					(SA1.ClassId = @lClassId)
					OR (@lClassId = 0)
					)
				AND (
					(SA1.DivisionId = @lDivisionId)
					OR (@lDivisionId = 0)
					)
				AND (
					(SA1.AdmissionCategoryId = @lAdmissionCategoryId)
					OR (@lAdmissionCategoryId = 0)
					)
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE --SA1.OrgGroupBatchId = @rOrgGroupBatchId AND -- Removed as changed View to Academic Table for Optimization by Foram
				(
					(FS1.ClassId = @lClassId)
					OR (@lClassId = 0)
					)
				AND (
					(SA1.OrgId = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (
					(FS1.AdmissionCategoryId = @lAdmissionCategoryId)
					OR (@lAdmissionCategoryId = 0)
					)
				AND (FS1.IsOptional = 0)
				AND (
					(FS1.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND (
					(SA1.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND SA1.Id = @rAcademicId
				AND (
					FS1.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			
			UNION ALL
			
			SELECT FS1.FeeId
				,FS1.Id
				,ISNULL(FS1.IsOptional, 0) AS IsOptional
				,ISNULL(FS1.IsVariable, 0) AS IsVariable
				,ISNULL(FS1.Amount, 0) AS Amount
				,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
				,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
				,FS1.BatchId
				,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
				,SA1.Id AS AcademicId
				,FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN --sStudent.vStudentAcademic SA1
				sStudent.tAcademic SA1 -- Changed View to Academic Table for Optimization by Foram
				ON SA1.Id = FO.SourceId
				AND SA1.BatchId = FS1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND (
					(SA1.ClassId = @lClassId)
					OR (@lClassId = 0)
					)
				AND (
					(SA1.DivisionId = @lDivisionId)
					OR (@lDivisionId = 0)
					)
				AND (
					(SA1.AdmissionCategoryId = @lAdmissionCategoryId)
					OR (@lAdmissionCategoryId = 0)
					)
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
				AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND SA1.BatchId = BM.Id -- Added as changed View to Academic Table for Optimization by Foram
			WHERE 
			--SA1.OrgGroupBatchId = @rOrgGroupBatchId AND  -- Removed as changed View to Academic Table for Optimization by Foram
				 (
					(FS1.ClassId = @lClassId)
					OR (@lClassId = 0)
					)
				AND (
					(SA1.OrgId = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (
					(FS1.AdmissionCategoryId = @lAdmissionCategoryId)
					OR (@lAdmissionCategoryId = 0)
					)
				AND (FS1.IsOptional = 1)
				AND (
					(FS1.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND (
					(SA1.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND SA1.Id = @rAcademicId
				AND (
					FS1.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			) FS ON FS.AcademicId = SA.AcademicId 
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.AcademicId AND SA.AcademicId = @rAcademicId 
			LEFT JOIN (
			SELECT ISNULL(SUM(RD.Amount), 0) AS PaidAmount
				,RD.FeeSetupId
				,R.SourceId
			FROM sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = R.SourceId
				AND (SA1.ClassId = @lClassId OR @lClassId = 0)
				AND ((SA1.DivisionId = @lDivisionId) OR (@lDivisionId = 0))
				AND (SA1.DivisionId = @lDivisionId OR @lDivisionId = 0)
			WHERE (R.SourceTypeId = 2001)
				AND (
					(SA1.OrgId = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (R.IsObsolete = 0)
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (
					(R.BatchId = @rBatchId)
					OR (@rBatchId = 0)
					)
				AND SA1.AcademicId = @rAcademicId
				AND (
					R.ReceiptBookId = @rReceiptBookId
					OR @rReceiptBookId = 0
					)
			GROUP BY FeeSetupId
				,R.SourceId
			) R ON R.FeeSetupId = FS.Id
			AND SA.AcademicId = R.SourceId WHERE SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(SA.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) > 0))

	RETURN @rReceiptAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fPendingFeeAmountReceiptBookwiseGet_OGOLD] (@rAcademicId bigint,@rReceiptBookId int)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

   CREATE OR ALTER FUNCTION [sFee].[fPendingFeeNamesGet](@rAcademicId bigint,@rReceiptBookId bigint
,@Fee TempPendingFee readonly
)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.FeeCode
			 FROM
			 @Fee F	
			 --Added by dhananjay for mantis : 42028
			 INNER JOIN sFee.tFeeSetup FS ON F.FeeSetupId = FS.Id  
			 INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId  
			 --Added by dhananjay for mantis : 42028
			 WHERE AcademicId = @rAcademicId  
			 AND F.ReceiptBookId = @rReceiptBookId
			 Order By FM.OrderIndex
		
    RETURN ISNULL(@rFeeDetail,'') 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sFee].[fReceiptFeeDetailGet](@rReceiptId bigint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeDetail nvarchar(2000)
SELECT 
			@rFeeDetail=COALESCE(@rFeeDetail+',','') +  F.Code
			 FROM 
			 sFee.tReceiptDetail D
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE D.ReceiptId = @rReceiptId 
			 ORDER BY F.OrderIndex ASC		
			
    RETURN ISNULL(@rFeeDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fReceiptMonthDetailGet](@rReceiptId bigint,@rIsStartEnd bit=0)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rMinDate Date
DECLARE @rMaxDate Date
		
		IF(@rIsStartEnd=0)
		BEGIN
			SELECT @rMinDate =	  min(S.StartDate),@rMaxDate =	  max(S.StartDate)		 
			FROM sFee.tReceiptDetail D
			INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			WHERE D.ReceiptId = @rReceiptId
			AND F.Number <> 100			
		END
		ELSE
		BEGIN
			SELECT @rMinDate =	  min(S.StartDate),@rMaxDate =	  max(S.EndDate)		 
			FROM sFee.tReceiptDetail D
			INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			WHERE D.ReceiptId = @rReceiptId
			AND F.Number <> 100		
		END
		
		RETURN DATENAME(month, @rMinDate)	+ ' Fees To ' +	DATENAME(month, @rMaxDate) + ' Fees '		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fReceiptNumber_ReceiptDateGet](@rSourceId bigint,@rOrgId int,@rClassId int,@rDivisionId int,@rOrgGroupBatchId int,@rBatchId int,@rUserId bigint,@rCommonBatch nvarchar(100),@rUptoDate date)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @rDetail nvarchar(2000)
           (SELECT @rDetail = COALESCE(@rDetail+',<br>','') + CONVERT(nvarchar(9), R.ReceiptNumber) +' - '+CONVERT(nvarchar(10), R.ReceiptDate, 103)
		    FROM
					sFee.tReceipt R 
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA.ClassId=@rClassId OR @rClassId=0) 
				AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND R.SourceId = @rSourceId
				)
	RETURN ISNULL(@rDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fReceiptNumberDateGet](@rAcademicId bigint,@rMonthId int,@rReceiptBookId int)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rReceiptDetail nvarchar(2000)
(SELECT 

			@rReceiptDetail= COALESCE(@rReceiptDetail+'<br>','') + Convert(nvarchar(20),R.ReceiptNumber) + '<br>' + Convert(nvarchar(20),R.ReceiptDate,103) + '<br>' + Convert(nvarchar(20),R.ReceiptAmount) 
			 FROM
			 (SELECT DISTINCT
			  R.ReceiptNumber,R.ReceiptDate,R.ReceiptAmount
			 FROM sFee.tReceipt R
			 INNER JOIN sFee.tReceiptDetail D ON R.Id = D.ReceiptId			 
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = F.FeeHeadId
			 
			 WHERE R.SourceId  = @rAcademicId AND Month(S.StartDate) = @rMonthId 
			  AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			  AND FH.Number <> 100
			  	
			 ) R
			 
			 		)  ORDER BY R.ReceiptDate, R.ReceiptNumber
			
    RETURN ISNULL(@rReceiptDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fReceiptNumberGet](@rReceiptBookId int,@rOrgGroupBatchId int, @rPayTypeId tinyint, @rFeeReceiptBasedOn nvarchar(50))
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

    --DECLARE @rReceiptBookId int

    DECLARE @lReceiptNumber int
	DECLARE @lResult  int

	IF(@rFeeReceiptBasedOn = 'ReceiptBookWise')
	BEGIN
      SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId
	END
	ELSE IF(@rFeeReceiptBasedOn = 'PayTypeWise')
	BEGIN
	  SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND PayTypeId = @rPayTypeId
	END
	-- #Start Mantis Id : 0036287
	ELSE IF(@rFeeReceiptBasedOn = 'Continuous Batch')
	BEGIN
	  SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId
	END
	-- #End Mantis Id : 0036287
	ELSE
	BEGIN
		SELECT @lReceiptNumber= max(ReceiptNumber) from sFee.tReceipt WITH (NOLOCK) where ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId
	END

	IF(@lReceiptNumber IS NULL)  
	BEGIN
		SET @lResult = 1
	END
	ELSE
	BEGIN
		 SET @lResult= @lReceiptNumber + 1
	END    

   return  @lResult 
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFee].[fStudentFeeSetupReceiptAmountGet](@rAcademicId bigint,@rFeeSetupId int)
RETURNS decimal(12,2) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeAmount decimal(12,2)
(SELECT 
			@rFeeAmount = SUM(D.Amount)
			 FROM
			 sFee.tReceipt R
			 INNER JOIN 			 
			 sFee.tReceiptDetail D ON R.Id = D.ReceiptId
			 INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = s.Id
			 --INNER JOIN sFee.tFeeMaster F ON S.FeeId = F.Id
			 WHERE R.SourceId  = @rAcademicId AND D.FeeSetupId = @rFeeSetupId  )
			 		
			
    RETURN ISNULL(@rFeeAmount,0) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fStudentWiseBusRoute](@rStudentId bigint, @rOrgGroupBatchId int)
RETURNS @BusRouteTable TABLE (
    BusRoute nvarchar(max),
    PickupPoint nvarchar(max)
)
WITH EXECUTE AS CALLER
AS 
BEGIN	 
    INSERT INTO @BusRouteTable (BusRoute, PickupPoint)
    SELECT 
        ISNULL(BRM.Title, '') AS BusRoute,
        ISNULL(BRDM.Title, '') AS PickupPoint
    FROM 
        sTransport.tAssignRoute AR
        INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.id = BRDM.BusRouteId
        --INNER JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id = AR.DropDestinationId
    WHERE 
        AR.SourceId = @rStudentId AND AR.SourceTypeId = 2003
        AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
   
    RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[fTransportBusRouteGet](@rStudentId bigint, @rOrgGroupBatchId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
DECLARE @lBusRoute nvarchar(max)=''

			SELECT 
				@lBusRoute= (ISNULL(BRM.Title,'') + ' - ' +  ISNULL(BRDM.Title,''))
            FROM 
				sTransport.tAssignRoute AR
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM On BRM.id=BRDM.BusRouteId
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId
            WHERE 
				AR.SourceId = @rStudentId
				AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
   
    RETURN  ISNULL(@lBusRoute,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFee].[GetStudentPendingFeeTesting](@rAcademicId BIGINT,@rReceiptBookId int = 0)
RETURNS DECIMAL(12, 0)
	WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @rReceiptAmount DECIMAL(12, 0)
SELECT @rReceiptAmount = SUM(FSAmount) + SUM(VariableAmount) + SUM(AdditionalAmount) - SUM(DiscountAmount) - SUM(NotApplicableAmount) - SUM(PaidAmount)
FROM
(    
    SELECT 
        SA.AcademicId,
        CASE WHEN FS.IsOptional = 0 THEN FS.Amount 
             WHEN FS.IsOptional = 1 AND FO.SourceId IS NOT NULL THEN FS.Amount
             ELSE 0.00 END AS FSAmount,
        ISNULL(FA.VariableAmount, 0) AS VariableAmount,
        ISNULL(FA.AdditionalAmount, 0) AS AdditionalAmount,
        ISNULL(FA.DiscountAmount, 0) AS DiscountAmount,
        ISNULL(FA.NotApplicableAmount, 0) AS NotApplicableAmount,
        ISNULL(R.PaidAmount, 0) AS PaidAmount
    FROM 
        sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeSetup FS ON SA.ClassId = FS.ClassId AND SA.BatchId = FS.BatchId AND FS.AdmissionCategoryId = SA.AdmissionCategoryId
        LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS.Id AND SA.AcademicId = FO.SourceId AND FO.SourceTypeId = 2001
        LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.AcademicId AND FA.SourceTypeId = 2001
        LEFT JOIN (
            SELECT 
                ISNULL(SUM(RD.Amount), 0) AS PaidAmount,
                RD.FeeSetupId,
                R.SourceId
            FROM
                sFee.tReceipt R 
                INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
            WHERE 
                R.SourceId = @rAcademicId
                AND R.SourceTypeId = 2001
                AND R.IsObsolete = 0
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId <= 0)
            GROUP BY 
                RD.FeeSetupId, R.SourceId
        ) R ON R.SourceId = SA.AcademicId AND R.FeeSetupId = FS.Id
    WHERE  SA.AcademicId = @rAcademicId
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId <= 0)
) AS FeeSummary
GROUP BY AcademicId;

RETURN Isnull(@rReceiptAmount,0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fCurrencyCodeGet](@rCurrencyType [tinyint])
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
		RETURN ('Rs.')
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fCurrencyTitleGet](@rCurrencyType [tinyint])
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
		RETURN ('Rupees')
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 154

IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rs.'

		RETURN (@lCurrencyCode)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorCodeGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
 THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 156
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyMinorTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 155
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Paisa'
		RETURN (@lCurrencyCode)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId int)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lCurrencyCode VARCHAR(100)
SELECT  
@lCurrencyCode = (CASE WHEN CS.Id IS NULL
  THEN CM.ItemValue  
 ELSE CS.ItemValue END)
 FROM 
sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
ON CM.Id = CS.ConfigurationId AND CS.SourceTypeId = 2010 AND CS.SourceId = @rOrgGroupId
WHERE CM.Id = 153
IF (@lCurrencyCode IS NULL)
SET @lCurrencyCode = 'Rupees'
		RETURN (@lCurrencyCode)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fNumberToWords](@rNumber [decimal](38, 0), @rCurrencyType [tinyint] = 0,@rOrgGroupId [smallint] = 0)
RETURNS [varchar](8000) WITH EXECUTE AS CALLER
AS 
BEGIN

--SET NOCOUNT ON
--DECLARE @rNumber DECIMAL(38, 0)
--SET @rNumber = 7654321098

DECLARE @lInputNumber VARCHAR(38)
DECLARE @lNumberTable TABLE (cNumber CHAR(2), cWord VARCHAR(10))
DECLARE @lOutputString VARCHAR(8000)
DECLARE @lLength INT
DECLARE @lCounter INT
DECLARE @lCount INT
DECLARE @lPosition INT
DECLARE @lChunk CHAR(3) -- for chunks of 3 numbers
DECLARE @lTensones CHAR(2)
DECLARE @lHundreds CHAR(1)
DECLARE @lTens CHAR(1)
DECLARE @lOnes CHAR(1)

IF @rNumber = 0 RETURN 'Zero'
--IF @rNumber = 0 SELECT 'Zero'

-- initialize the variables
SELECT @lInputNumber = CONVERT(NVARCHAR(38), @rNumber)
     , @lOutputString = ''
     , @lCounter = 1
SELECT @lLength   = LEN(@lInputNumber)
     , @lPosition = LEN(@lInputNumber) - 2
     , @lCount    = LEN(@lInputNumber) / 3

-- make sure there is an extra loop added for the remaining numbers
IF LEN(@lInputNumber) % 3 <> 0 SET @lCount = @lCount + 1

-- insert data for the numbers and words
INSERT INTO @lNumberTable   SELECT '00', ''
    UNION ALL SELECT '01', 'One'      UNION ALL SELECT '02', 'Two'
    UNION ALL SELECT '03', 'Three'    UNION ALL SELECT '04', 'Four'
    UNION ALL SELECT '05', 'Five'     UNION ALL SELECT '06', 'Six'
    UNION ALL SELECT '07', 'Seven'    UNION ALL SELECT '08', 'Eight'
    UNION ALL SELECT '09', 'Nine'     UNION ALL SELECT '10', 'Ten'
    UNION ALL SELECT '11', 'Eleven'   UNION ALL SELECT '12', 'Twelve'
    UNION ALL SELECT '13', 'Thirteen' UNION ALL SELECT '14', 'Fourteen'
    UNION ALL SELECT '15', 'Fifteen'  UNION ALL SELECT '16', 'Sixteen'
    UNION ALL SELECT '17', 'Seventeen' UNION ALL SELECT '18', 'Eighteen'
    UNION ALL SELECT '19', 'Nineteen' UNION ALL SELECT '20', 'Twenty'
    UNION ALL SELECT '30', 'Thirty'   UNION ALL SELECT '40', 'Forty'
    UNION ALL SELECT '50', 'Fifty'    UNION ALL SELECT '60', 'Sixty'
    UNION ALL SELECT '70', 'Seventy'  UNION ALL SELECT '80', 'Eighty'
    UNION ALL SELECT '90', 'Ninety'   

WHILE @lCounter <= @lCount BEGIN

	-- get chunks of 3 numbers at a time, padded with leading zeros
	SET @lChunk = RIGHT('000' + SUBSTRING(@lInputNumber, @lPosition, 3), 3)
 
	--SELECT @lInputNumber, @lPosition, @lChunk
 
	IF @lChunk <> '000' BEGIN
		SELECT @lTensones = SUBSTRING(@lChunk, 2, 2)
		     , @lHundreds = SUBSTRING(@lChunk, 1, 1)
		     , @lTens = SUBSTRING(@lChunk, 2, 1)
		     , @lOnes = SUBSTRING(@lChunk, 3, 1)

		-- If twenty or less, use the word directly from @lNumberTable
		IF CONVERT(INT, @lTensones) <= 20 OR @lOnes = '0' BEGIN
			SET @lOutputString = (SELECT cWord 
                                      FROM @lNumberTable 
                                      WHERE @lTensones = cNumber)
                   + CASE @lCounter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' Thousand ' WHEN 3 THEN ' Million '
                       WHEN 4 THEN ' Billion '  WHEN 5 THEN ' Trillion '
                       WHEN 6 THEN ' Quadrillion ' WHEN 7 THEN ' Quintillion '
                       WHEN 8 THEN ' Sextillion '  WHEN 9 THEN ' Septillion '
                       WHEN 10 THEN ' Octillion '  WHEN 11 THEN ' Nonillion '
                       WHEN 12 THEN ' Decillion '  WHEN 13 THEN ' Undecillion '
                       ELSE '' END
                               + @lOutputString
		    END
		 ELSE BEGIN -- break down the ones and the tens separately

             SET @lOutputString = ' ' 
                            + (SELECT cWord 
                                    FROM @lNumberTable 
                                    WHERE @lTens + '0' = cNumber)
					         + '-'
                             + (SELECT cWord 
                                    FROM @lNumberTable 
                                    WHERE '0'+ @lOnes = cNumber)
                   + CASE @lCounter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' Thousand ' WHEN 3 THEN ' Million '
                       WHEN 4 THEN ' Billion '  WHEN 5 THEN ' Trillion '
                       WHEN 6 THEN ' Quadrillion ' WHEN 7 THEN ' Quintillion '
                       WHEN 8 THEN ' Sextillion '  WHEN 9 THEN ' Septillion '
                       WHEN 10 THEN ' Octillion '  WHEN 11 THEN ' Nonillion '
                       WHEN 12 THEN ' Decillion '   WHEN 13 THEN ' Undecillion '
                       ELSE '' END
                            + @lOutputString
		END

		-- now get the hundreds
		IF @lHundreds <> '0' BEGIN
			SET @lOutputString  = (SELECT cWord 
                                      FROM @lNumberTable 
                                      WHERE '0' + @lHundreds = cNumber)
					            + ' Hundred ' 
                                + @lOutputString
		END
	END

	SELECT @lCounter = @lCounter + 1
	     , @lPosition = @lPosition - 3

END

-- Remove any double spaces
SET @lOutputString = LTRIM(RTRIM(REPLACE(@lOutputString, '  ', ' ')))
SET @lOutputString = UPPER(LEFT(@lOutputString, 1)) + SUBSTRING(@lOutputString, 2, 8000)

IF @rCurrencyType <> 0
	BEGIN
		SET @lOutputString = sFinanceCommon.fDefaultCurrencyTitleGet(@rOrgGroupId) + ' ' + @lOutputString -- return the result
	END
	
	RETURN @lOutputString
--SELECT @lOutputString -- return the result
END

--select dbo.udf_NumberToWords (1234567890) + CHAR(10)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fNumberToWordsGet]
(
    @rNumber DECIMAL(38, 0),
    @rCurrencyType TINYINT = 0,
    @rOrgGroupId SMALLINT = 0,
	@rDefaultCurrencyTitle nvarchar(200)
)
RETURNS VARCHAR(8000)
WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @lInputNumber VARCHAR(38),
            @lOutputString VARCHAR(8000) = '',
            @lLength INT,
            @lCounter INT = 1,
            @lCount INT,
            @lPosition INT,
            @lChunk CHAR(3),
            @lTensones CHAR(2),
            @lHundreds CHAR(1),
            @lTens CHAR(1),
            @lOnes CHAR(1);

    DECLARE @lNumberTable TABLE (cNumber CHAR(2) PRIMARY KEY, cWord VARCHAR(10));

    IF @rNumber = 0 RETURN 'Zero';

    -- Initialize
    SELECT @lInputNumber = CONVERT(VARCHAR(38), @rNumber),
           @lLength = LEN(@lInputNumber),
           @lPosition = LEN(@lInputNumber) - 2,
           @lCount = (@lLength + 2) / 3;

    -- Insert number-to-word mapping
    INSERT INTO @lNumberTable (cNumber, cWord)
    VALUES
        ('00', ''), ('01', 'One'), ('02', 'Two'), ('03', 'Three'), ('04', 'Four'),
        ('05', 'Five'), ('06', 'Six'), ('07', 'Seven'), ('08', 'Eight'), ('09', 'Nine'),
        ('10', 'Ten'), ('11', 'Eleven'), ('12', 'Twelve'), ('13', 'Thirteen'), ('14', 'Fourteen'),
        ('15', 'Fifteen'), ('16', 'Sixteen'), ('17', 'Seventeen'), ('18', 'Eighteen'), ('19', 'Nineteen'),
        ('20', 'Twenty'), ('30', 'Thirty'), ('40', 'Forty'), ('50', 'Fifty'),
        ('60', 'Sixty'), ('70', 'Seventy'), ('80', 'Eighty'), ('90', 'Ninety');

    -- Loop through each 3-digit group
    WHILE @lCounter <= @lCount
    BEGIN
        SET @lChunk = RIGHT('000' + SUBSTRING(@lInputNumber, @lPosition, 3), 3);

        IF @lChunk <> '000'
        BEGIN
            SELECT
                @lHundreds = SUBSTRING(@lChunk, 1, 1),
                @lTens = SUBSTRING(@lChunk, 2, 1),
                @lOnes = SUBSTRING(@lChunk, 3, 1),
                @lTensones = SUBSTRING(@lChunk, 2, 2);

            DECLARE @lGroupWord VARCHAR(100) = '';

            -- Hundreds place
            IF @lHundreds <> '0'
                SET @lGroupWord = (SELECT cWord FROM @lNumberTable WHERE cNumber = '0' + @lHundreds) + ' Hundred ';

            -- Tens and Ones place
            IF CONVERT(INT, @lTensones) <= 20 OR @lOnes = '0'
                SET @lGroupWord += (SELECT cWord FROM @lNumberTable WHERE cNumber = @lTensones);
            ELSE
                SET @lGroupWord += (SELECT cWord FROM @lNumberTable WHERE cNumber = @lTens + '0')
                                  + '-' +
                                  (SELECT cWord FROM @lNumberTable WHERE cNumber = '0' + @lOnes);

            -- Add unit (Thousand, Million, etc.)
            SET @lGroupWord += CASE @lCounter
                                 WHEN 2 THEN ' Thousand'
                                 WHEN 3 THEN ' Million'
                                 WHEN 4 THEN ' Billion'
                                 WHEN 5 THEN ' Trillion'
                                 WHEN 6 THEN ' Quadrillion'
                                 WHEN 7 THEN ' Quintillion'
                                 WHEN 8 THEN ' Sextillion'
                                 WHEN 9 THEN ' Septillion'
                                 WHEN 10 THEN ' Octillion'
                                 WHEN 11 THEN ' Nonillion'
                                 WHEN 12 THEN ' Decillion'
                                 WHEN 13 THEN ' Undecillion'
							   ELSE ''
                               END;

            -- Prepend group word
            SET @lOutputString = LTRIM(RTRIM(@lGroupWord)) + ' ' + @lOutputString;
        END

        -- Next chunk
        SET @lCounter += 1;
        SET @lPosition -= 3;
    END

    -- Cleanup double spaces
    SET @lOutputString = LTRIM(RTRIM(REPLACE(@lOutputString, '  ', ' ')));
    SET @lOutputString = UPPER(LEFT(@lOutputString, 1)) + SUBSTRING(@lOutputString, 2, LEN(@lOutputString));

    -- Add currency if needed
    IF @rCurrencyType <> 0
	BEGIN
        SET @lOutputString = @rDefaultCurrencyTitle + ' ' + @lOutputString;
	END

    RETURN @lOutputString;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fNumberToWordsWithDecimal](@rAmount [decimal](38, 8), @rCurrencyType [tinyint] = 0, @rScale [tinyint] = 2,@rOrgGroupId [smallint] = 0)
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
/*
DECLARE @rAmount DECIMAL(38, 8)
DECLARE @rCurrencyType dTinyInt --// 0 = Without Currency Type, 1 = Accounting, 2 = Foreign, 3 = Reporting
DECLARE @rScale  TINYINT

SET @rAmount = 0
SET @rCurrencyType = 0
SET @rScale = 0
*/		
BEGIN
	DECLARE @lIntPart		 NVARCHAR(1000)
	DECLARE @lDecimalPart		 NVARCHAR(100)
	DECLARE @lAmountChar  NVARCHAR(38)
	DECLARE @lDecimalPartAmount SMALLINT
	DECLARE @lWords NVARCHAR(4000)

	SET @lAmountChar = @rAmount
	SELECT @lWords = + '' + sFinanceCommon.fDefaultCurrencyTitleGet(@rOrgGroupId) +' '+ [sFee].[fNumToWords](FLOOR(@rAmount)) 
	
	
	IF CHARINDEX('.', @lAmountChar) > 0
		BEGIN
			SET @lDecimalPartAmount = SUBSTRING(SUBSTRING(@lAmountChar, CHARINDEX('.', @lAmountChar) + 1, LEN(@lAmountChar)), 1, @rScale)
			IF @lDecimalPartAmount > 0 
				BEGIN
					
						SET @lWords = @lWords
								    + ' and'
						
						IF @rCurrencyType <> 0
						BEGIN
							SET @lWords = @lWords + ' ' + sFinanceCommon.fDefaultCurrencyTitleGet(@rOrgGroupId)
						END		   
						
						SET @lWords = @lWords
								    + ' ' + sFinanceCommon.fNumberToWords(@lDecimalPartAmount, @rCurrencyType,@rOrgGroupId)
				END

		END
					 
	--SELECT @lWords, CHARINDEX('.', @lAmountChar), @lAmountChar
	RETURN @lWords 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fNumberToWordsWithDecimalGet]
(@rAmount [decimal](38, 8), @rCurrencyType [tinyint] = 0, @rScale [tinyint] = 2,@rOrgGroupId [smallint] = 0, @rDefaultCurrencyTitle nvarchar(200))
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
/*
DECLARE @rAmount DECIMAL(38, 8)
DECLARE @rCurrencyType dTinyInt --// 0 = Without Currency Type, 1 = Accounting, 2 = Foreign, 3 = Reporting
DECLARE @rScale  TINYINT

SET @rAmount = 0
SET @rCurrencyType = 0
SET @rScale = 0
*/		
BEGIN
	DECLARE @lIntPart NVARCHAR(1000),
	 @lDecimalPart NVARCHAR(100),
	 @lAmountChar NVARCHAR(38),
	 @lDecimalPartAmount SMALLINT,
	 @lWords NVARCHAR(4000),
	 @lCHARINDEX int = 0

	SET @lAmountChar = @rAmount

	SELECT @lWords = + '' + @rDefaultCurrencyTitle +' '+ [sFee].[fNumberToWordsGet](FLOOR(@rAmount)) 
	
	SET @lDecimalPartAmount = CAST(ROUND((@rAmount - FLOOR(@rAmount)) * POWER(10, @rScale), 0) AS INT)
	IF @lDecimalPartAmount > 0 
	BEGIN	
		SET @lWords = @lWords + ' and'
						
		IF @rCurrencyType <> 0
		BEGIN
			SET @lWords = @lWords + ' ' + @rDefaultCurrencyTitle
		END		   
						
		SET @lWords = @lWords + ' ' + [sFinanceCommon].[fNumberToWordsGet](@lDecimalPartAmount, @rCurrencyType,@rOrgGroupId,@rDefaultCurrencyTitle)
	END

	RETURN @lWords 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fRoundOff](@rAmount [decimal](22, 6), @rCurrencyType [tinyint])
RETURNS [decimal](22, 6) WITH EXECUTE AS CALLER
AS 
BEGIN
	
--	SELECT * FROM sConfig.tSetting WHERE Id = ''
	DECLARE @lItemId SmallInt
	DECLARE @lItemValue Nvarchar(20) 
	DECLARE @lModulo Decimal(22,6)
	
	SET @lItemId = (CASE WHEN @rCurrencyType = 1 THEN 1
						 WHEN @rCurrencyType = 2 THEN 2
						 WHEN @rCurrencyType = 3 THEN 3
					END)
					
	SELECT @lItemValue = ItemValue FROM  sConfig.tConfigurationMaster WHERE Id = @rCurrencyType
	
	SET @lItemValue = (CASE WHEN @rCurrencyType = 1 THEN @lItemValue
						 WHEN @rCurrencyType = 2 THEN @lItemValue
						 WHEN @rCurrencyType = 3 THEN '0.01'
					END)
						
	IF @lItemValue = '0.01'
			SET @rAmount =  ROUND(@rAmount, 2)
	ELSE IF @lItemValue = '0.10'
			SET @rAmount =  ROUND(@rAmount, 1)
	ELSE IF @lItemValue = '0.50'
		BEGIN
		SET @rAmount = @rAmount
		SET @lModulo = (@rAmount % 1)
			
		SET @rAmount = (CASE WHEN @lModulo > 1 
							 THEN (@rAmount - @lModulo)
						ELSE 
						(CASE WHEN @lModulo >= .75 
						   THEN (@rAmount - @lModulo) + 1
						ELSE 
						(CASE WHEN @lModulo > .50 
						   THEN (@rAmount - @lModulo) + .50
						ELSE 
						(CASE WHEN @lModulo >= .25
						   THEN (@rAmount - @lModulo) + .50
						ELSE @rAmount - @lModulo END) END) END) END)
		END		
	ELSE IF @lItemValue = '1.00'
			SET @rAmount =  ROUND(@rAmount, 0)
	ELSE IF @lItemValue = '10.00'
			SET @rAmount =  ROUND(@rAmount, -1)
	ELSE IF @lItemValue = '100.00'
			SET @rAmount =  ROUND(@rAmount, -2)
    ELSE IF @lItemValue = '1000.00'
			SET @rAmount =  ROUND(@rAmount, -3)
	ELSE IF @lItemValue = '50.00'
		BEGIN
			SET @rAmount = FLOOR(@rAmount)
			SET @lModulo = (@rAmount % 100)
				
			SET @rAmount = (CASE WHEN @lModulo > 100 
								 THEN (@rAmount - @lModulo)
							ELSE 
							(CASE WHEN @lModulo >= 75 
							   THEN (@rAmount - @lModulo) + 100
							ELSE 
							(CASE WHEN @lModulo > 50 
							   THEN (@rAmount - @lModulo) + 50
							ELSE 
							(CASE WHEN @lModulo >= 25
							   THEN (@rAmount - @lModulo) + 50
							ELSE @rAmount - @lModulo END) END) END) END)
		END
	RETURN @rAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fRoundOffForeignAmount](@rAmount [decimal](22, 6))
RETURNS [decimal](22, 6) WITH EXECUTE AS CALLER
AS 
BEGIN
	SET @rAmount = FLOOR(@rAmount)
	SET @rAmount = (CASE 
						WHEN ((@rAmount % 100) < 25)
								 THEN (@rAmount - (@rAmount % 100))
					
					ELSE
						(CASE
							WHEN ((@rAmount % 100) >= 25 AND (@rAmount % 100) < 75)
						       THEN (@rAmount - (@rAmount % 100) + 50)
					ELSE
						(CASE
							WHEN ((@rAmount % 100) >= 75)
						       THEN (@rAmount - (@rAmount % 100) + 100)
					END)
					END)
					
					
							
END)	
	RETURN @rAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fAssignRoomAssetGet](@rHostelId int,@rRoomId int,@rStudentId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList=@rAssestList + isnull(AT.Code,'') + ' ' + ':' + ' ' + isnull(RM.AssetNumber,'') + ','

FROM sHostel.tAssignRoomAsset AR 
          INNER JOIN sHostel.tRoomAssetMaster RM ON RM.Id=Ar.RoomAssetId  AND (AR.SourceId = @rStudentId OR ISNULL(@rStudentId,0) = 0) AND AR.SourceTypeId=2003
          INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE 
          ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
   
      RETURN  isnull(@rAssestList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fAssignRoomAssetNumberGet](@rHostelId int,@rRoomId int,@rStudentId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList=@rAssestList +  isnull(RM.AssetNumber,'') + ','

FROM sHostel.tAssignRoomAsset AR 
          INNER JOIN sHostel.tRoomAssetMaster RM ON RM.Id=Ar.RoomAssetId  AND (AR.SourceId = @rStudentId OR ISNULL(@rStudentId,0) = 0) AND AR.SourceTypeId=2003
          INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE 
          ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
   
      RETURN  isnull(@rAssestList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fAssignRoomEmployeeAssetGet](@rHostelId int,@rRoomId int,@rStudentId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList=@rAssestList + isnull(AT.Code,'') + ' ' + ':' + ' ' + isnull(RM.AssetNumber,'') + ','

FROM sHostel.tAssignRoomAsset AR 
          INNER JOIN sHostel.tRoomAssetMaster RM ON RM.Id=Ar.RoomAssetId  AND (AR.SourceId = @rStudentId OR ISNULL(@rStudentId,0) = 0) AND AR.SourceTypeId=95
          INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE 
          ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
   
      RETURN  isnull(@rAssestList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fAssignRoomStudentGet](@rOrgGroupBatchId int,@rSourceId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
DECLARE @rStatusName nvarchar(max)=''
	IF EXISTS(SELECT 1 from sHostel.tAssignRoom AR WHERE OrgGroupBatchId=@rOrgGroupBatchId  AND AR.SourceId = @rSourceId AND AR.SourceTypeId=2003 )
		BEGIN
		SET @rStatusName='Transferred'
		END
		ElSE
		BEGin
	  SET @rStatusName='Pending'
	  END
      RETURN  isnull(@rStatusName,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fDepositHeadNameGet](@rHostelId int,@rHostelDepositHeadId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rDepositName nvarchar(max)=''

Select @rDepositName=@rDepositName + isnull(DM.Title,'') 

FROM sHostel.tHostelDepositHeadMaster DM 
          WHERE 
          DM.HostelId=@rHostelId
          AND (DM.Id=@rHostelDepositHeadId)
      RETURN  isnull(@rDepositName,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fHostelWardenGet](@rHostelId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rWardenList nvarchar(max)=''

Select @rWardenList=@rWardenList + ISNULL(EM.FirstName,'')+' '+ISNULL(EM.LastName,'') +' '+','

FROM sHostel.tHostelWarden HW 
INNER JOIN sHrm.tEmployeeMaster EM ON HW.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
          WHERE 
          ((HW.HostelId=@rHostelId)OR (@rHostelId=0))
          
   --     IF (RIGHT(@rWardenList, 1) = ',')
   --set @rWardenList = LEFT(@rWardenList, LEN(@rWardenList) - 1)
   
      RETURN  isnull(@rWardenList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHostel].[fRemainAssignRoomAssetGet](@rHostelId int,@rRoomId int,@rAssetTypeId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rAssestList nvarchar(max)=''

Select @rAssestList= @rAssestList+isnull(RM.AssetNumber,'') + ','
FROM sHostel.tRoomAssetMaster RM 
          LEFT JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId
          WHERE ((RM.HostelId=@rHostelId)OR (@rHostelId=0))
          AND ((RM.RoomId=@rRoomId)OR ( @rRoomId =0))
          AND RM.Id NoT IN(SELECT RoomAssetId FROM sHostel.tAssignRoomAsset 
          WHERE ((HostelId=@rHostelId)OR (ISNULL(@rHostelId,0)=0))  AND ((RoomId=@rRoomId)OR (ISNULL(@rRoomId,0)=0))) 
          AND RM.AssetTypeId=@rAssetTypeId
           group by RM.AssetNumber
        IF (RIGHT(@rAssestList, 1) = ',')
   set @rAssestList = LEFT(@rAssestList, LEN(@rAssestList) - 1)
  
      RETURN  isnull(@rAssestList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHostel].[fWardenGet](@rHostelId BIGINT)
RETURNS nvarchar(200) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lName nvarchar(200)=''
  
	Select @lName=@lName + COALESCE( EMW.FirstName + ' ' +EMW.LastName + '/ ' ,'') 
	FROM  
	-- sHostel.tAssignRoom AR 
	--INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
	--INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
	--INNER JOIN 
	sHostel.tHostelwarden  HW 
	--ON HW.HostelId=HM.Id
    LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
	WHERE HW.HostelId = @rHostelId  
	
	if isnull(@lName,'')=''
	begin
		select @lName=''
	end	
	else
	begin		
		select @lName=LEFT(@lName,LEN(@lName)-1)
	end
	return  @lName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHrm].[fAttendanceJoiningDateGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lWeekOff nvarchar(20)
	Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
	DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
	DECLARE @lCOUNT int 
	DECLARE @lEmployeeFirstWeekOffDayId int
	DECLARE @lEmployeeSEcondWeekOffDayId int
	DECLARE @lEmployeeFirstWeekOffRuleId int
	DECLARE @lEmployeeSecondWeekOffRuleId int



	SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate)+1

	SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



	IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 	
	ELSE
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95	
	END

	IF @EmpFirstWeekOffRule = 1 
	BEGIN		
		IF(@lWeekOff = @lWeekDay1)
		BEGIN	
				
			Set @rStatus = 'W'
			RETURN @rStatus	
		END 					
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
				SET @rStatus = 'P'
		END
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 						
				SET @rStatus = 'A'
		END		
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
					WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
					AND SourceTypeId in (2004, 3)
					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
		END
	END
				
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END	 
	END
	Else if @EmpFirstWeekOffRule = 3 
	BEGIN
		IF @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END 
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 5 
	BEGIN   
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			        SET @rStatus = 'H'	
			RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 6 
	BEGIN	   
		IF @WeekNumber = 1 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END			 
		END 
	END
	
	Else if @EmpFirstWeekOffRule = 7 
	BEGIN  
		IF @WeekNumber = 2 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 8 
	BEGIN  
		IF @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END 
		END
	END
	Else if @EmpFirstWeekOffRule = 9 
	BEGIN
		IF @WeekNumber = 4 
		BEGIN			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END	 
		END		 
	END	
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4

		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @rStatus = 'W'
			RETURN @rStatus	
		END
		if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @rStatus = 'P'
		END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 
			SET @rStatus = 'A'
		END	
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND SourceTypeId in (2004, 3)
		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
			SET @rStatus = 'H'	
			RETURN @rStatus	
		END
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'		
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 5
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 6
	BEGIN
		IF @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 7
	BEGIN
		IF @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
					
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	
	Else if @EmpSecondWeekOffRule = 8
	BEGIN
		IF @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END	 
		END
	END
	
	Else if @EmpSecondWeekOffRule = 9
	BEGIN
		IF @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END 
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
		Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA' 
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
		SET @rStatus = ''
	RETURN @rStatus
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHrm].[fAttendanceWithApproveLeaveGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
DECLARE @lCOUNT int 
DECLARE @lEmployeeFirstWeekOffDayId int
DECLARE @lEmployeeSEcondWeekOffDayId int
DECLARE @lEmployeeFirstWeekOffRuleId int
DECLARE @lEmployeeSecondWeekOffRuleId int



SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1

SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
	SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 
	
	ELSE
	
	BEGIN
	SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
		
	END


if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				
				if(@rStatus !='W')	
				BEGIN	
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
				END

					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END
					END
				
			 END
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				
							
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					BEGIN
						if(@rStatus !='W')	
						BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
						END
						BEGIN
							SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
						END
							
						IF(@rStatus IS NULL)
						BEGIN
							IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
							BEGIN 
								SET @rStatus = 'P'
								RETURN @rStatus
							END
							IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
							BEGIN 						
								SET @rStatus = 'A'
								RETURN @rStatus
							END
						END
						ELSE
						BEGIN
							RETURN @rStatus
						END																
					 END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
					RETURN @rStatus		
		        END
		     END
		END
	END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
				
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		 END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 5
	BEGIN
		   
		if @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 6
	BEGIN
		   
		if @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 7
	BEGIN
		   
		if @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 8
	BEGIN
		   
		if @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 9
	BEGIN
		   
		if @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
				
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		 END
	END
	  if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
				if(@rStatus !='W')	
				BEGIN	
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
				END

					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END			
			END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				if(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							if(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							ELSE
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END

							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
			
			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							ELSE
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 5
	BEGIN
		 
		if @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 6
	BEGIN
		 
		if @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 7
	BEGIN
		 
		if @WeekNumber =2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 8
	BEGIN
		 
		if  @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	else if @EmpSecondWeekOffRule = 9
	BEGIN
		 
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				IF(@rStatus !='W')	
				BEGIN
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
				END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							IF(@rStatus !='W')	
							BEGIN
								SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							BEGIN
								SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							END
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	 else if @EmpSecondWeekOffRule = 10
		BEGIN
		 
			if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
			BEGIN
				if(@lWeekOff = @lWeekDay2)
				BEGIN
					--Set @rStatus = 'W'
					if(@rDateOfJoining  > @rAttendanceDate)
					BEGIN 
						 Set @rStatus = 'NA'
					END
					ELSE
					BEGIN
						 Set @rStatus = 'W'
					END			
					IF(@rStatus !='W')	
					BEGIN
						if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
						BEGIN 
							SET @rStatus = 'P'
						END
						 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
						BEGIN 
							SET @rStatus = 'A'
						END
					END
						IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
						 BEGIN
								IF(@rStatus !='W')	
								BEGIN
									SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
								END
								BEGIN
									SET @rStatus = (Select Distinct  'W-'+LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
								END
								IF(@rStatus IS NULL)
								BEGIN
									IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
									BEGIN 
										SET @rStatus = 'P'
										RETURN @rStatus
									END
									IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
									BEGIN 						
										SET @rStatus = 'A'
										RETURN @rStatus
									END
								END
								ELSE
								BEGIN
									RETURN @rStatus
								END																
						 END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
							INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
							AND SourceTypeId in (2004, 3)
							AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					BEGIN
						SET @rStatus = 'H'	
						RETURN @rStatus	
					END
				END
			END
		
		END
IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
BEGIN
	SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
	IF(@rStatus IS NULL)
	BEGIN
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @rStatus = 'P'
			RETURN @rStatus
		END
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 						
			SET @rStatus = 'A'
			RETURN @rStatus
		END
	END
	ELSE
	BEGIN
		RETURN @rStatus
	END																
END
--It Take only department assign Holiday maitisid--27362 Nimesh
--IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
--WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
--AND SourceTypeId in (2004, 3,95)
--AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
--BEGIN
--	SET @rStatus = 'H'	
--	RETURN @rStatus		
--END

--It Take assign Holiday acording to SourcetypeId
IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
WHERE ES.BatchId = @rBatchId
	AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
	-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
	--AND SourceTypeId in (95)
	AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
BEGIN
	SET @rStatus = 'H'	
	RETURN @rStatus	
END



 if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
	
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'			
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
	 SET @rStatus = ''
	RETURN @rStatus
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHrm].[fAttendanceWithApproveLeaveGet2](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
DECLARE @lCOUNT int 
DECLARE @lEmployeeFirstWeekOffDayId int
DECLARE @lEmployeeSEcondWeekOffDayId int
DECLARE @lEmployeeFirstWeekOffRuleId int
DECLARE @lEmployeeSecondWeekOffRuleId int



SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1

SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
	SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 
	
	ELSE
	
	BEGIN
	SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
		
	END


if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				RETURN @rStatus	
			 END 					
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
					
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END
					END
				
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END				

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
			   RETURN @rStatus		
		        END
		     END
			 
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	
	  if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END				
			END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
			
			
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct case when l.LeavePeriodId=1 then LTM.Code else 'HD-'+LTM.Code end from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId=550 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
 
 if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
	
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'			
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
	 SET @rStatus = ''
	RETURN @rStatus
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sHrm].[fAttendanceWithEMPLeaveGet] (
	@rEmployeeId BIGINT
	,@rForYear SMALLINT
	,@rForMonth SMALLINT
	,@rDay SMALLINT
	,@rBatchId INT
	,@rDepartmentId INT
	,@rOrgId INT
	,@rAttendanceDate NVARCHAR(20)
	,@rDateOfJoining DATE
	,@rDateOfLeaving DATE
	,@rStatus NVARCHAR(10)
	)
RETURNS [nvarchar] (50)
	WITH EXECUTE AS CALLER
AS
BEGIN
	--this function is created for mantisid -- 29177 
	-- if Holiday is weekoff then display weekoff instead of Holiday in old function it is not working
	--SELECT @rDepartmentId = ODM.Id FROM sHrm.tEmployeeMaster EM
	--				   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
	--				   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	--				   WHERE EM.Id = @rEmployeeId
	DECLARE @lWeekOff NVARCHAR(20)
	DECLARE @WeekNumber INT
		,@EmpSecondWeekOffRule INT
		,@EmpFirstWeekOffRule INT
	DECLARE @lDate DATETIME
		,@lWeekDay1 NVARCHAR(20)
		,@lWeekDay2 NVARCHAR(20)
	DECLARE @lCOUNT INT
	DECLARE @lEmployeeFirstWeekOffDayId INT
	DECLARE @lEmployeeSEcondWeekOffDayId INT
	DECLARE @lEmployeeFirstWeekOffRuleId INT
	DECLARE @lEmployeeSecondWeekOffRuleId INT

	SET @lDate = CONVERT(NVARCHAR(10), @rForYear) + '-' + CONVERT(NVARCHAR(10), @rForMonth) + '-' + CONVERT(NVARCHAR(10), @rDay)
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	SET @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
	SET @lEmployeeFirstWeekOffDayId = (
			SELECT EmployeeFirstWeekOffDayId
			FROM sSetup.tOrganizationMaster
			WHERE Id = @rOrgId
			)
	SET @lEmployeeSEcondWeekOffDayId = (
			SELECT EmployeeSEcondWeekOffDayId
			FROM sSetup.tOrganizationMaster
			WHERE Id = @rOrgId
			)
	SET @lEmployeeFirstWeekOffRuleId = (
			SELECT EmployeeFirstWeekOffRuleId
			FROM sSetup.tOrganizationMaster
			WHERE Id = @rOrgId
			)
	SET @lEmployeeSecondWeekOffRuleId = (
			SELECT EmployeeSecondWeekOffRuleId
			FROM sSetup.tOrganizationMaster
			WHERE Id = @rOrgId
			)

	IF (
			(
				@lEmployeeFirstWeekOffDayId != 0
				AND @lEmployeeFirstWeekOffRuleId != 0
				)
			OR (
				@lEmployeeSEcondWeekOffDayId != 0
				AND @lEmployeeSecondWeekOffRuleId != 0
				)
			)
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId
			,@lWeekDay2 = EmployeeSEcondWeekOffDayId
			,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId
			,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId
		FROM sSetup.tOrganizationMaster
		WHERE Id = @rOrgId
	END
	ELSE
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId
			,@lWeekDay2 = SecondWeekOff
			,@EmpFirstWeekOffRule = FristWeekOffRuleId
			,@EmpSecondWeekOffRule = SEcondWeekOffRuleId
		FROM sActivity.tWeekOffSetting
		WHERE SourceId = @rEmployeeId
			AND SourceTypeId = 95
	END

	--this function is created for mantisid -- 29177 
	-- if Holiday is weekoff then display weekoff instead of Holiday in old function it is not working 
	IF EXISTS (
			SELECT 1
			FROM sActivity.tEventSchedule ES
			INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EA.SourceId
			WHERE ES.BatchId = @rBatchId
				AND (
					(SourceId = @rDepartmentId)
					OR (@rDepartmentId = 0)
					)
				AND SourceTypeId = 2004
				AND (
					@lDate BETWEEN ES.FromDate
						AND ES.ToDate
					)
				AND ES.IsHoliday = 1
			)
	BEGIN
		SET @rStatus = 'H'
			--RETURN @rStatus		
	END

	-- add two times 'H' because it is not working if we set Holiday Employee wise
	IF EXISTS (
			SELECT 1
			FROM sActivity.tEventSchedule ES
			INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EA.SourceId
			WHERE ES.BatchId = @rBatchId
				AND SourceId = @rEmployeeId -- Add SourceId for Mantis Id : 0038655	
				AND SourceTypeId IN (
					95
					,3
					)
				AND (
					@lDate BETWEEN ES.FromDate
						AND ES.ToDate
					)
				AND ES.IsHoliday = 1
			)
	BEGIN
		SET @rStatus = 'H'
			--RETURN @rStatus		
	END

	IF @EmpFirstWeekOffRule = 1
	BEGIN
		IF (@lWeekOff = @lWeekDay1)
		BEGIN
			IF (@rDateOfJoining > @rAttendanceDate)
			BEGIN
				SET @rStatus = 'NA'
			END
			ELSE
			BEGIN
				SET @rStatus = 'W'
			END

			RETURN @rStatus
		END

		-- #Start Comment for Mantis Id : 0038655
		--IF (@rStatus <> 'H')
		--BEGIN
		--	IF EXISTS (
		--			SELECT 1
		--			FROM sHrm.tEmployeeAttendanceRegister
		--			WHERE EmployeeId = @rEmployeeId
		--				AND AttendanceDate = @lDate
		--				AND BatchId = @rBatchId
		--				AND IsPresent = 1
		--			)
		--	BEGIN
		--		SET @rStatus = 'P'
		--	END

		--	IF EXISTS (
		--			SELECT 1
		--			FROM sHrm.tEmployeeAttendanceRegister
		--			WHERE EmployeeId = @rEmployeeId
		--				AND AttendanceDate = @lDate
		--				AND BatchId = @rBatchId
		--				AND IsPresent = 0
		--			)
		--	BEGIN
		--		SET @rStatus = 'A'
		--	END

		--	IF EXISTS (
		--			SELECT 1
		--			FROM sHrm.tLeave
		--			WHERE @rAttendanceDate BETWEEN FromDate
		--					AND ToDate
		--				AND OrgId = @rOrgId
		--				AND EmployeeId = @rEmployeeId
		--				AND BatchId = @rBatchId
		--			)
		--	BEGIN
		--		SET @rStatus = (
		--				SELECT DISTINCT LTM.Code
		--				FROM sHrm.tLeaveTypeMaster LTM
		--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
		--					AND l.StatusId != 551
		--				WHERE (
		--						@lDate BETWEEN L.FromDate
		--							AND L.ToDate
		--						)
		--					AND L.OrgId = @rOrgid
		--					AND L.EmployeeId = @rEmployeeId
		--					AND L.BatchId = @rBatchid
		--				)

		--		IF (@rStatus IS NULL)
		--		BEGIN
		--			IF EXISTS (
		--					SELECT 1
		--					FROM sHrm.tEmployeeAttendanceRegister
		--					WHERE EmployeeId = @rEmployeeId
		--						AND AttendanceDate = @lDate
		--						AND BatchId = @rBatchId
		--						AND IsPresent = 1
		--					)
		--			BEGIN
		--				SET @rStatus = 'P'

		--				RETURN @rStatus
		--			END

		--			IF EXISTS (
		--					SELECT 1
		--					FROM sHrm.tEmployeeAttendanceRegister
		--					WHERE EmployeeId = @rEmployeeId
		--						AND AttendanceDate = @lDate
		--						AND BatchId = @rBatchId
		--						AND IsPresent = 0
		--					)
		--			BEGIN
		--				SET @rStatus = 'A'

		--				RETURN @rStatus
		--			END
		--		END
		--		ELSE
		--		BEGIN
		--			RETURN @rStatus
		--		END
		--	END
		--END
		-- #End Comment for Mantis Id : 0038655
				--IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				--	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
				--	WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				--	AND SourceTypeId in (2004, 3,95)
				--	AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				-- BEGIN
				--	 SET @rStatus = 'H'	
				--	 RETURN @rStatus		
				-- END
	END
	ELSE IF @EmpFirstWeekOffRule = 2
	BEGIN
		IF @WeekNumber = 2
			OR @WeekNumber = 4
		BEGIN
			IF (@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END

				-- #Start Comment for Mantis Id : 0038655	
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--AND SourceTypeId in (2004, 3,95)
						--AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--    BEGIN
						--      SET @rStatus = 'H'	
						--RETURN @rStatus		
						--    END
			END
		END
	END
	ELSE IF @EmpFirstWeekOffRule = 4
	BEGIN
		IF @WeekNumber = 1
			OR @WeekNumber = 3
			OR @WeekNumber = 5
		BEGIN
			IF (@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END


				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3,95)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END
			--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	ELSE IF @EmpFirstWeekOffRule = 10
	BEGIN
		IF @WeekNumber = 1
			OR @WeekNumber = 2
			OR @WeekNumber = 3
			OR @WeekNumber = 4
		BEGIN
			IF (@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END

				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3,95)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END

	IF @EmpSecondWeekOffRule = 1
	BEGIN
		IF (@lWeekOff = @lWeekDay2)
		BEGIN
			--Set @rStatus = 'W'
			IF (@rDateOfJoining > @rAttendanceDate)
			BEGIN
				SET @rStatus = 'NA'
			END
			ELSE
			BEGIN
				SET @rStatus = 'W'
			END
		END
	END
	ELSE IF @EmpSecondWeekOffRule = 2
	BEGIN
		IF @WeekNumber = 2
			OR @WeekNumber = 4
		BEGIN
			IF (@lWeekOff = @lWeekDay2)
			BEGIN
				SET @rStatus = 'W'

				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3,95)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END
	ELSE IF @EmpSecondWeekOffRule = 3
	BEGIN
		IF @WeekNumber = 1
			OR @WeekNumber = 3
		BEGIN
			IF (@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END

				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END
	ELSE IF @EmpSecondWeekOffRule = 4
	BEGIN
		IF @WeekNumber = 1
			OR @WeekNumber = 3
			OR @WeekNumber = 5
		BEGIN
			IF (@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END

				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END
			--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	ELSE IF @EmpSecondWeekOffRule = 10
	BEGIN
		IF @WeekNumber = 1
			OR @WeekNumber = 2
			OR @WeekNumber = 3
			OR @WeekNumber = 4
		BEGIN
			IF (@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				IF (@rDateOfJoining > @rAttendanceDate)
				BEGIN
					SET @rStatus = 'NA'
				END
				ELSE
				BEGIN
					SET @rStatus = 'W'
				END

				-- #Start Comment for Mantis Id : 0038655
				--IF (@rStatus <> 'H')
				--BEGIN
				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 1
				--			)
				--	BEGIN
				--		SET @rStatus = 'P'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tEmployeeAttendanceRegister
				--			WHERE EmployeeId = @rEmployeeId
				--				AND AttendanceDate = @lDate
				--				AND BatchId = @rBatchId
				--				AND IsPresent = 0
				--			)
				--	BEGIN
				--		SET @rStatus = 'A'
				--	END

				--	IF EXISTS (
				--			SELECT 1
				--			FROM sHrm.tLeave
				--			WHERE @rAttendanceDate BETWEEN FromDate
				--					AND ToDate
				--				AND OrgId = @rOrgId
				--				AND EmployeeId = @rEmployeeId
				--				AND BatchId = @rBatchId
				--			)
				--	BEGIN
				--		SET @rStatus = (
				--				SELECT DISTINCT LTM.Code
				--				FROM sHrm.tLeaveTypeMaster LTM
				--				INNER JOIN sHrm.tLeave l ON LTM.Id = l.LeaveTypeId
				--					AND l.StatusId != 551
				--				WHERE (
				--						@lDate BETWEEN L.FromDate
				--							AND L.ToDate
				--						)
				--					AND L.OrgId = @rOrgid
				--					AND L.EmployeeId = @rEmployeeId
				--					AND L.BatchId = @rBatchid
				--				)

				--		IF (@rStatus IS NULL)
				--		BEGIN
				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 1
				--					)
				--			BEGIN
				--				SET @rStatus = 'P'

				--				RETURN @rStatus
				--			END

				--			IF EXISTS (
				--					SELECT 1
				--					FROM sHrm.tEmployeeAttendanceRegister
				--					WHERE EmployeeId = @rEmployeeId
				--						AND AttendanceDate = @lDate
				--						AND BatchId = @rBatchId
				--						AND IsPresent = 0
				--					)
				--			BEGIN
				--				SET @rStatus = 'A'

				--				RETURN @rStatus
				--			END
				--		END
				--		ELSE
				--		BEGIN
				--			RETURN @rStatus
				--		END
				--	END
				--END
				-- #End Comment for Mantis Id : 0038655
						--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						--		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						--		AND SourceTypeId in (2004, 3)
						--		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
						--BEGIN
						--	SET @rStatus = 'H'	
						--	RETURN @rStatus	
						--END
			END
		END
	END

	IF (
			@rDateOfJoining IS NOT NULL
			AND @rDateOfLeaving IS NOT NULL
			)
		SET @ldate = @rAttendanceDate

	IF ISDATE(@ldate) = 1
	BEGIN
		IF (@rDateOfJoining > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'

			RETURN @rStatus
		END

		IF (@rDateOfLeaving <> '')
		BEGIN
			IF (@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus = 'L'

				RETURN @rStatus
			END
		END
	END

	IF (@rStatus IS NULL)
		SET @rStatus = ''

	RETURN @rStatus
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sHrm].[fAttendanceWithLeaveGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
DECLARE @lCOUNT int 
DECLARE @lEmployeeFirstWeekOffDayId int
DECLARE @lEmployeeSEcondWeekOffDayId int
DECLARE @lEmployeeFirstWeekOffRuleId int
DECLARE @lEmployeeSecondWeekOffRuleId int



SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1

SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
	SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 
	
	ELSE
	
	BEGIN
	SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
		
	END


if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				RETURN @rStatus	
			 END 					
					if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @rStatus = 'A'
					END
					
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @rStatus = 'H'	
						 RETURN @rStatus		
					 END
					END
				
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END				

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
			   RETURN @rStatus		
		        END
		     END
			 
			 
		END
		 
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				--Set @rStatus = 'W'	
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
			 
		END
		 
	END
	
	  if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END				
			END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3,95)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END	
			
			
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
				
			END
			 
		END
		 
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				--Set @rStatus = 'W'
				if(@rDateOfJoining  > @rAttendanceDate)
				BEGIN 
					 Set @rStatus = 'NA'
				END
				ELSE
				BEGIN
					 Set @rStatus = 'W'
				END			
				
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @rStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @rStatus = 'A'
					END
					IF EXISTS(SELECT 1 from  sHrm.tLeave where   @rAttendanceDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgId AND EmployeeId = @rEmployeeId AND BatchId =@rBatchId) 
					 BEGIN
							SET @rStatus = (Select Distinct LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
							IF(@rStatus IS NULL)
							BEGIN
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
								BEGIN 
									SET @rStatus = 'P'
									RETURN @rStatus
								END
								IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
								BEGIN 						
									SET @rStatus = 'A'
									RETURN @rStatus
								END
							END
							ELSE
							BEGIN
								RETURN @rStatus
							END																
					 END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
					RETURN @rStatus	
				END
			END
		END
		
	END
 
 if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
	Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
	
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'			
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
	 SET @rStatus = ''
	RETURN @rStatus
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeContactsGet](@rEmployeeId bigint)
RETURNS NVARCHAR(max)
AS
BEGIN
DECLARE @lContactNos NVARCHAR(MAX) = ''
	SELECT @lContactNos = 
		(SUBSTRING((CASE WHEN ISNULL(EC.PresentContactNo,'') = '' THEN '' ELSE EC.PresentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.PermanentContactNo,'') = '' THEN '' ELSE EC.PermanentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.EmergencyContactNo,'') = '' THEN '' ELSE EC.EmergencyContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.MobileNumber,'') = '' THEN '' ELSE EC.MobileNumber + ', ' END) + 
			(CASE WHEN ISNULL(EC.WhatsappContactNo,'') = '' THEN '' ELSE EC.WhatsappContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.PhoneNoCompany,'') = '' THEN '' ELSE EC.PhoneNoCompany + ', ' END),0,
			LEN((CASE WHEN ISNULL(EC.PresentContactNo,'') = '' THEN '' ELSE EC.PresentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.PermanentContactNo,'') = '' THEN '' ELSE EC.PermanentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.EmergencyContactNo,'') = '' THEN '' ELSE EC.EmergencyContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.MobileNumber,'') = '' THEN '' ELSE EC.MobileNumber + ', ' END) + 
			(CASE WHEN ISNULL(EC.WhatsappContactNo,'') = '' THEN '' ELSE EC.WhatsappContactNo + ', ' END) + 
			(CASE WHEN ISNULL(EC.PhoneNoCompany,'') = '' THEN '' ELSE EC.PhoneNoCompany + ', ' END))))

	FROM 
		[sCommon].[vEmployeeMaster] VEM
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = VEM.Id	
		LEFT JOIN [sHrm].[tEmployeeFamilyDetails] EF ON EF.EmployeeId = VEM.Id

	WHERE  VEM.Id = @rEmployeeId

	RETURN ISNULL(@lContactNos,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget] (@rDocumentId int,@rEmployeeId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lDepartmentId int
 DECLARE @lEmployeeId bigint

 SELECT @lDepartmentId = DepartmentId,@lEmployeeId = EmployeeId FROM sHrm.vEmployeeCommunication WHERE Id = @rEmployeeId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lDepartmentId
			  Inner Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=95 AND UserSourceId=@lEmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName  +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=95 AND UserSourceId=@lEmployeeId AND ( UD.UploadFunctionalityId=13)
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND UD.DocumentName is not null   AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeDocumentDepartmentwiseget] (@rDocumentId int,@rEmployeeId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lDepartmentId int
 DECLARE @lEmployeeId bigint

 SELECT @lDepartmentId = DepartmentId,@lEmployeeId = EmployeeId FROM sHrm.vEmployeeCommunication WHERE Id = @rEmployeeId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lDepartmentId
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sHrm.tEmployeeDocument ED ON SDM.Id=ED.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  where ED.EmployeeId=@lEmployeeId AND SDM.SubmitDocumentFunctionalityId = 2 AND DS.SubmitDocumentId is null  AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sHrm].[fEmployeeHolidayDates](
    @rEmployeeId bigint,
    @rDepartmentId int, 
    @rForYear int,
    @rForMonth int,
    @rBatchId int,
    @rOrgId int
)
RETURNS @HolidayDays TABLE (
    HolidayDate DATE
)
AS 
BEGIN
    DECLARE @FirstDate DATE
    DECLARE @LastDate DATE

    SET @FirstDate = CONVERT(DATE, CAST(@rForYear AS VARCHAR(4)) + '-' + RIGHT('0' + CAST(@rForMonth AS VARCHAR(2)), 2) + '-01')
    SET @LastDate = DATEADD(DAY, -1, DATEADD(MONTH, 1, @FirstDate))

    ;WITH HolidayEvents AS (
        SELECT ES.FromDate, ES.ToDate
        FROM sActivity.tEventSchedule ES
        INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id AND EA.SourceTypeId IN (2004, 95)
        LEFT JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = EA.SourceId AND (EC.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        WHERE ES.BatchId = @rBatchId
          AND ((SourceId = @rDepartmentId) OR (@rDepartmentId = 0))
          AND MONTH(ES.FromDate) = @rForMonth AND YEAR(ES.FromDate) = @rForYear
          AND MONTH(ES.ToDate) = @rForMonth AND YEAR(ES.ToDate) = @rForYear
          AND ES.IsHoliday = 1
    ),
    DateRange AS (
        SELECT HE.FromDate AS HolidayDate, HE.ToDate
        FROM HolidayEvents HE
        UNION ALL
        SELECT DATEADD(DAY, 1, DR.HolidayDate), DR.ToDate
        FROM DateRange DR
        WHERE DATEADD(DAY, 1, DR.HolidayDate) <= DR.ToDate
    )
    INSERT INTO @HolidayDays
    SELECT DISTINCT HolidayDate
    FROM DateRange
    WHERE HolidayDate BETWEEN @FirstDate AND @LastDate
    OPTION (MAXRECURSION 0);

    RETURN;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeHolidayDatesList](
    @rEmployeeId bigint,
    @rDepartmentId int, 
    @rForYear int,
    @rForMonth int,
    @rBatchId int,
    @rOrgId int
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
    DECLARE @FirstDate DATE;
    DECLARE @LastDate DATE;
    DECLARE @HolidayDays VARCHAR(MAX) = '';

    SET @FirstDate = CONVERT(DATE, CAST(@rForYear AS VARCHAR(4)) + '-' + RIGHT('0' + CAST(@rForMonth AS VARCHAR(2)), 2) + '-01');
    SET @LastDate = DATEADD(DAY, -1, DATEADD(MONTH, 1, @FirstDate));

    ;WITH HolidayEvents AS (
        SELECT ES.FromDate, ES.ToDate
        FROM sActivity.tEventSchedule ES
        INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id AND EA.SourceTypeId IN (2004, 95)
        LEFT JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = EA.SourceId AND (EC.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        WHERE ES.BatchId = @rBatchId
          AND ((SourceId = @rDepartmentId) OR (@rDepartmentId = 0))
          AND MONTH(ES.FromDate) = @rForMonth AND YEAR(ES.FromDate) = @rForYear
          AND MONTH(ES.ToDate) = @rForMonth AND YEAR(ES.ToDate) = @rForYear
          AND ES.IsHoliday = 1
    ),
    DateRange AS (
        SELECT HE.FromDate AS HolidayDate, HE.ToDate
        FROM HolidayEvents HE
        UNION ALL
        SELECT DATEADD(DAY, 1, DR.HolidayDate), DR.ToDate
        FROM DateRange DR
        WHERE DATEADD(DAY, 1, DR.HolidayDate) <= DR.ToDate
    )
    SELECT @HolidayDays = STUFF((
        SELECT DISTINCT ',' + CAST(DAY(HolidayDate) AS VARCHAR)
        FROM DateRange
        WHERE HolidayDate BETWEEN @FirstDate AND @LastDate
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '');

    RETURN @HolidayDays;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeHolidayGet](@rEmployeeId bigint,@rDepartmentId int, @rForYear int,@rForMonth int,@rBatchId int,@rOrgId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN	
Declare @ldate datetime,@lDays int
		DECLARE @Days int
		DECLARE @Firstdate datetime
		DECLARE @Lastdate datetime
		DECLARE @lCOUNT int=0
		DECLARE @lPreviousHoliday int
		DECLARE @lEventHoliday int
		
		SET @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		Select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		SET @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		SET @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)

 

--IF EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id INNER JOIN sSetup.tDepartmentMaster DM 
--ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) AND SourceTypeId in (2004, 95)
--AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1) 
IF EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id LEFT JOIN sSetup.tDepartmentMaster DM 
ON DM.Id=EA.SourceId LEFT JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=EA.SourceId AND (EC.EmployeeId=0 OR @rEmployeeId=0) WHERE ES.BatchId = @rBatchId 
AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) AND SourceTypeId in (2004, 95)AND ((MONTH(ES.FromDate)=@rForMonth) AND (YEAR(ES.FromDate)=@rForYear))	AND 
((MONTH(ES.ToDate)=@rForMonth) AND (YEAR(ES.ToDate)=@rForYear)) AND ES.IsHoliday=1) 
BEGIN

declare @temp as table (HLDY int)
insert into @temp (HLDY)
(SELECT SUM(HLDY) FROM  (SELECT DATEDIFF(dd,ES.FromDate,ES.ToDate)+1 AS HLDY
						FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id and ea.SourceTypeId =2004
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 				   
						WHERE ((ES.BatchId=@rBatchId)) AND ((MONTH(ES.FromDate)=@rForMonth) AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)=@rForMonth) AND (YEAR(ES.ToDate)=@rForYear)) AND ES.IsHoliday=1 
						GROUP BY ES.FromDate,ES.ToDate
					   
						UNION ALL
					   
						SELECT DATEDIFF(dd,ES.FromDate,ES.ToDate) +1 AS HLDY
						FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id and ea.SourceTypeId =95			    
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=EA.SourceId AND (EC.EmployeeId=@rEmployeeId OR (@rEmployeeId=0))
						WHERE ((ES.BatchId=@rBatchId)) AND ((MONTH(ES.FromDate)=@rForMonth) AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)=@rForMonth) AND (YEAR(ES.ToDate)=@rForYear)) AND ES.IsHoliday=1 
						GROUP BY ES.FromDate,ES.ToDate ) TMP GROUP BY HLDY)
						
						set @lEventHoliday = (select sum(HLDY) from @temp)
	
	--SET @lPreviousHoliday= (SELECT HoliDays From sHrm.tEmployeeWorkingDays WHERE BatchId=@rBatchId AND EmployeeId=@rEmployeeId AND ForMonth=@rForMonth 
	--						AND ForYear=@rForYear)
	--IF(@lPreviousHoliday Is NULL)
	--	SET @lPreviousHoliday = 0						
	SET @lCOUNT=@lEventHoliday --+ @lPreviousHoliday
	RETURN 	@lCOUNT	
	END
 
	RETURN ISNULL(@lCOUNT,0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER FUNCTION [sHrm].[fEmployeeJoiningCertificateTemplate]
(
	@EmployeeId [bigint]= 0,
    @Template NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE 
        --@EmployeeId  BIGINT,
        @Number INT,
        @EmployeeName NVARCHAR(200),
        @FirstName NVARCHAR(100),
        @MiddleName NVARCHAR(100),
        @LastName NVARCHAR(100),
        @Code NVARCHAR(20),
        @ShortName NVARCHAR(50),
        @DepartmentName NVARCHAR(100),
        @Designation NVARCHAR(100),
        @EmployeePhoto NVARCHAR(MAX),     
        @DateOfJoining DATE,
		@CertificateHeaderA4 NVARCHAR(MAX),

        @Remark NVARCHAR(500),
        @CertificateDate DATE,
        @PayScale NVARCHAR(150),
        @AgreementPeriod NVARCHAR(150),
        @CertificateRemark NVARCHAR(500),
        @OrgTitle NVARCHAR(100),
        @CreatedDateTime DATETIME,
        @UserDisplayName NVARCHAR(100),
        @EmployeeDesignation NVARCHAR(100),
        @ShortTitle NVARCHAR(100),
        @DepartmentName1 NVARCHAR(100),
        @MobileNumber NVARCHAR(20),

        @PresentStreetOne NVARCHAR(150),
        @PresentStreetTwo NVARCHAR(150),
        @PresentStreetThree NVARCHAR(150),
        @PresentCity NVARCHAR(50),
        @PresentState NVARCHAR(50),
        @PresentZipCode NVARCHAR(20),
        @PresentContactNo NVARCHAR(20),
        @UserDesignation NVARCHAR(100),
        @CertificateDateOfJoining DATE
        
    -- Fetch the values from the database
    SELECT 
        @EmployeeId = ISNULL(EmployeeId, 0),
        @Number = ISNULL(Number, 0),
        @EmployeeName = ISNULL(EmployeeName, ''),
        @FirstName = ISNULL(FirstName, ''),
        @MiddleName = ISNULL(MiddleName, ''),
        @LastName = ISNULL(LastName, ''),
        @Code= ISNULL(Code, ''),
        @ShortName = ISNULL(ShortName, ''),
        @DepartmentName = ISNULL(DepartmentName, ''),
        @Designation = ISNULL(Designation, ''),
		@EmployeePhoto = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("EmployeePhoto")))', 'NVARCHAR(MAX)'),''),
        @DateOfJoining = ISNULL(DateOfJoining, ''),
        @CertificateHeaderA4 = ISNULL(CAST('data:image/jpeg;base64,' AS NVARCHAR(MAX)) +
                      CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("CertificateHeaderA4")))', 'NVARCHAR(MAX)'),''),
        @Remark = ISNULL(Remark, ''),
        @CertificateDate = ISNULL(CertificateDate, ''),
        @PayScale = ISNULL(PayScale, ''),
        @AgreementPeriod = ISNULL(AgreementPeriod, ''),
        @CertificateRemark = ISNULL(CertificateRemark, ''),
        @OrgTitle = ISNULL(OrgTitle, ''),
        @CreatedDateTime = ISNULL(CreatedDateTime, ''),
        @UserDisplayName = ISNULL(UserDisplayName, ''),
        @EmployeeDesignation = ISNULL(EmployeeDesignation, ''),
        @ShortTitle = ISNULL(ShortTitle, ''),
        @DepartmentName1= ISNULL(DepartmentName1, ''),
        @MobileNumber = ISNULL(MobileNumber, ''),
        @PresentStreetOne = ISNULL(PresentStreetOne, ''),
        @PresentStreetTwo = ISNULL(PresentStreetTwo, ''),
        @PresentStreetThree = ISNULL(PresentStreetThree, ''),
        @PresentCity = ISNULL(PresentCity, ''),
        @PresentState = ISNULL(PresentState, ''),
        @PresentZipCode = ISNULL(PresentZipCode, ''),
        @PresentContactNo = ISNULL(PresentContactNo, ''),
        @UserDesignation = ISNULL(UserDesignation, ''),

        @CertificateDateOfJoining = ISNULL(CertificateDateOfJoining, '')
       
    FROM 
      [sHrm].[vPrintTemplateJoiningCertificateGet]  
    WHERE 
        EmployeeId = @EmployeeId

    -- Replace placeholders in the template with actual values
    SET @Template = REPLACE(@Template, '[EmployeeId]', @EmployeeId);
    --SET @Template = REPLACE(@Template, '[AdmissionDate]', CONVERT(NVARCHAR, @AdmissionDate, 103));
    SET @Template = REPLACE(@Template, '[Number]', @Number);
    SET @Template = REPLACE(@Template, '[EmployeeName]', @EmployeeName);
    SET @Template = REPLACE(@Template, '[FirstName]', @FirstName);
    SET @Template = REPLACE(@Template, '[MiddleName]', @MiddleName);
    SET @Template = REPLACE(@Template, '[LastName]', @LastName);
    --SET @Template = REPLACE(@Template, '[BonafideDate]', CONVERT(NVARCHAR, @BonafideDate, 103));
    SET @Template = REPLACE(@Template, '[Code]', @Code);
    SET @Template = REPLACE(@Template, '[ShortName]', @ShortName);
    SET @Template = REPLACE(@Template, '[DepartmentName]', @DepartmentName);
    SET @Template = REPLACE(@Template, '[Designation]', @Designation);
    SET @Template = REPLACE(@Template, '[EmployeePhoto]', @EmployeePhoto);
    SET @Template = REPLACE(@Template, '[DateOfJoining]',CONVERT(NVARCHAR, @DateOfJoining,103));
    SET @Template = REPLACE(@Template, '[CertificateHeaderA4]', @CertificateHeaderA4 );
    SET @Template = REPLACE(@Template, '[Remark]', @Remark);
    SET @Template = REPLACE(@Template, '[CertificateDate]', CONVERT(NVARCHAR,@CertificateDate,103));
    SET @Template = REPLACE(@Template, '[PayScale]', @PayScale);
    SET @Template = REPLACE(@Template, '[AgreementPeriod]', @AgreementPeriod);
    SET @Template = REPLACE(@Template, '[CertificateRemark]', @CertificateRemark);
    SET @Template = REPLACE(@Template, '[OrgTitle]', @OrgTitle);
    SET @Template = REPLACE(@Template, '[CreatedDateTime]', CONVERT(NVARCHAR,@CreatedDateTime,103));
    SET @Template = REPLACE(@Template, '[UserDisplayName]', @UserDisplayName);
    SET @Template = REPLACE(@Template, '[EmployeeDesignation]', @EmployeeDesignation);
    SET @Template = REPLACE(@Template, '[ShortTitle]', @ShortTitle);
    SET @Template = REPLACE(@Template, '[DepartmentName1]', @DepartmentName1);
    SET @Template = REPLACE(@Template, '[MobileNumber]', @MobileNumber);

	SET @Template = REPLACE(@Template, '[PresentStreetOne]', @PresentStreetOne);
    SET @Template = REPLACE(@Template, '[PresentStreetTwo]', @PresentStreetTwo);
	SET @Template = REPLACE(@Template, '[PresentStreetThree]', @PresentStreetThree);
    SET @Template = REPLACE(@Template, '[PresentCity]', @PresentCity);
    SET @Template = REPLACE(@Template, '[PresentState]', @PresentState);
    SET @Template = REPLACE(@Template, '[PresentZipCode]', @PresentZipCode);
	SET @Template = REPLACE(@Template, '[PresentContactNo]', @PresentContactNo);

    SET @Template = REPLACE(@Template, '[UserDesignation]', @UserDesignation);
    SET @Template = REPLACE(@Template, '[CertificateDateOfJoining]',CONVERT(NVARCHAR, @CertificateDateOfJoining,103));
    
    RETURN @Template;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sHrm].[fEmployeeLeaveStatusGet](@rMonth int,@rYear int, @rEmployeeId bigint)
RETURNS [nvarchar](200) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult nvarchar(200)=''
SELECT @lResult =Count(L.Id)  FROM sHrm.tLeave L 
INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
WHERE 
--(L.StatusId = 549 OR L.StatusId = 550)
L.EmployeeId = @rEmployeeId AND (MONTH(L.FromDate)=@rMonth OR MONTH(L.ToDate)=@rMonth) AND (YEAR(L.FromDate)=@rYear OR YEAR(L.ToDate)=@rYear)
AND IsLWP=1
RETURN  ISNULL(@lResult,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeLeaveTypeCodeGet](@rBatchId int, @rEmployeeId bigint,@rAttendanceDate Date)
RETURNS nvarchar(100) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @LeaveType nvarchar(100)=''
	SELECT 
		@LeaveType=ISNULL(LTM.Code,'') 
	FROM 
		sHrm.tLeave L
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId 
		--INNER JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=L.EmployeeId
	WHERE 
		L.EmployeeId=@rEmployeeId 
		AND @rAttendanceDate BETWEEN L.FromDate AND L.ToDate
		AND L.BatchId = @rBatchId
		AND StatusId=550
	RETURN  @LeaveType 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeNameGet](@rFirstName nvarchar(100),@rMiddleName nvarchar(100),@rLastName nvarchar(100),@rEmployeeNameFormatId tinyint)
RETURNS [nvarchar](300) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rEmployeeName Nvarchar(300)
IF @rEmployeeNameFormatId = 1
SET @rEmployeeName =  @rFirstName + ' ' + @rLastName
ELSE IF @rEmployeeNameFormatId = 2
SET @rEmployeeName =  @rFirstName + ' ' + @rMiddleName + ' ' + @rLastName
ELSE IF @rEmployeeNameFormatId = 3
 SET @rEmployeeName = @rLastName + ' ' + @rFirstName
ELSE IF @rEmployeeNameFormatId = 4
SET @rEmployeeName = @rLastName + ' ' + @rFirstName + ' ' + @rMiddleName
ELSE IF @rEmployeeNameFormatId = 5
SET @rEmployeeName = @rFirstName
ELSE
SET @rEmployeeName =  @rFirstName + ' ' + @rLastName     
RETURN @rEmployeeName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeSubjectGet](@rEmployeeId bigint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rSubject nvarchar(2000)

	
SELECT @rSubject = COALESCE(@rSubject + ', ','') + Title 
FROM   (SELECT DISTINCT SM.Title 
		FROM sAcademic.tTeacherSubject TS 
		INNER JOIN sSetup.tSubjectMaster SM ON TS.SubjectId = SM.Id			   
		WHERE TS.EmployeeId = @rEmployeeId) Result
			 		
    RETURN ISNULL(@rSubject,'') 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId int,@rAttendanceDate nvarchar(20), @rDateOfJoining date,@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lWeekOff nvarchar(20)
	Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
	DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
	DECLARE @lCOUNT int 
	DECLARE @lEmployeeFirstWeekOffDayId int
	DECLARE @lEmployeeSEcondWeekOffDayId int
	DECLARE @lEmployeeFirstWeekOffRuleId int
	DECLARE @lEmployeeSecondWeekOffRuleId int



	SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate)+1

	SET @lEmployeeFirstWeekOffDayId= (SELECT EmployeeFirstWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSEcondWeekOffDayId= (SELECT EmployeeSEcondWeekOffDayId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeFirstWeekOffRuleId= (SELECT EmployeeFirstWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 
	SET @lEmployeeSecondWeekOffRuleId= (SELECT EmployeeSecondWeekOffRuleId FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId) 



	IF ((@lEmployeeFirstWeekOffDayId !=0 AND @lEmployeeFirstWeekOffRuleId !=0 ) OR (@lEmployeeSEcondWeekOffDayId != 0 AND @lEmployeeSecondWeekOffRuleId!=0))
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END 	
	ELSE
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95	
	END

	IF @EmpFirstWeekOffRule = 1 
	BEGIN		
		IF(@lWeekOff = @lWeekDay1)
		BEGIN	
				
			Set @rStatus = 'W'
			RETURN @rStatus	
		END 					
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
				SET @rStatus = 'P'
		END
		IF Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 						
				SET @rStatus = 'A'
		END		
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id			
					WHERE ES.BatchId = @rBatchId 
					AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
		END
	END
				
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END	 
	END
	Else if @EmpFirstWeekOffRule = 3 
	BEGIN
		IF @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END 
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 5 
	BEGIN   
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			        SET @rStatus = 'H'	
			RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 6 
	BEGIN	   
		IF @WeekNumber = 1 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END			 
		END 
	END
	
	Else if @EmpFirstWeekOffRule = 7 
	BEGIN  
		IF @WeekNumber = 2 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @rStatus = 'H'	
				RETURN @rStatus		
		    END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 8 
	BEGIN  
		IF @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END 
		END
	END
	Else if @EmpFirstWeekOffRule = 9 
	BEGIN
		IF @WeekNumber = 4 
		BEGIN			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95) 
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus		
			END	 
		END		 
	END	
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'	
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @rStatus = 'W'
			RETURN @rStatus	
		END
		if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @rStatus = 'P'
		END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 
			SET @rStatus = 'A'
		END	
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
		WHERE ES.BatchId = @rBatchId 
		AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
		--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
		--AND SourceTypeId in (95)
		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
			SET @rStatus = 'H'	
			RETURN @rStatus	
		END
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'		
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 5
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 6
	BEGIN
		IF @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	Else if @EmpSecondWeekOffRule = 7
	BEGIN
		IF @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
					
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId 
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END
	
	Else if @EmpSecondWeekOffRule = 8
	BEGIN
		IF @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId 
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END	 
		END
	END
	
	Else if @EmpSecondWeekOffRule = 9
	BEGIN
		IF @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId
				AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
				-- AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
				--AND SourceTypeId in (95)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END 
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				RETURN @rStatus	
			END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @rStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @rStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			WHERE ES.BatchId = @rBatchId 
			AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
			--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
			--AND SourceTypeId in (95)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @rStatus = 'H'	
				RETURN @rStatus	
			END
		END
	END

	--add for 29237 mantis if condition
	--It Take assign Holiday acording to SourcetypeId
	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				WHERE ES.BatchId = @rBatchId
					AND (((SourceId=@rEmployeeId OR @rEmployeeId=0) AND SourceTypeId in (95)) OR ((SourceId=@rDepartmentId OR @rDepartmentId=0) AND SourceTypeId in (2004, 3)))
					--AND ((SourceId=@rEmployeeId) OR (@rEmployeeId=0)) 
					--AND SourceTypeId in (95)
					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	BEGIN
		SET @rStatus = 'H'	
		RETURN @rStatus	
	END

	if(@rDateOfJoining IS NOT NULL AND @rDateOfLeaving IS NOT NULL)
		Set @ldate = @rAttendanceDate	
	if ISDATE(@ldate)=1	
	BEGIN
		if(@rDateOfJoining  > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA' 
			RETURN @rStatus
		END
		IF(@rDateOfLeaving<>'')
		BEGIN
			if(@rDateOfLeaving <= @rAttendanceDate)
			BEGIN
				SET @rStatus='L'
				RETURN @rStatus
			END
		END
	END
	IF(@rStatus Is NULL)
		SET @rStatus = ''
	RETURN @rStatus
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fMonthWiseNoOfLeave](@rType bit, @rFromDate Date,@rTodate Date,@rForMonth int,@rForYear int, @rLeavePeriodId int,@rLaveTypeId int)
RETURNS  DECIMAL(12,2)       

  WITH EXECUTE AS CALLER
AS 
BEGIN    
         DECLARE @rTempFromDate date
		 DECLARE @rDays  DECIMAL(12,2)
         DECLARE @rIsLWP bit
         
         SELECT @rIsLWP = IsLWP from sHrm.tLeaveTypeMaster Where Id = @rLaveTypeId
         
         IF(@rIsLWP = @rType)
		 BEGIN
			 SET @rTempFromDate = @rFromDate
		 
			IF(DATEPART(MONTH,@rFromDate) = DATEPART(MONTH,@rTodate)) 
				SET @rTempFromDate = @rFromDate
			ELSE IF(DATEPART(MONTH,@rFromDate) = @rForMonth)
				SET @rTempFromDate = @rFromDate
			ELSE IF(DATEPART(MONTH,@rToDate) = @rForMonth) 
			BEGIN
				SELECT @rTempFromDate = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@rToDate)-1),@rToDate),101) 
			END
		 
			;WITH c(d) AS
			(
				SELECT TOP (DATEDIFF(DAY, @rTempFromDate, @rTodate)+1)
				DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @rTempFromDate)
				FROM sys.all_columns
				WHERE DATEPART(MONTH,@rTempFromDate)=@rForMonth 
			) 
			SELECT    
			@rDays = COUNT(*)
			FROM c WHERE DATEPART(MONTH,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForMonth
			AND DATEPART(YEAR,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForYear
			GROUP BY DATEDIFF(MONTH, 0, d)	 
    
			IF(@rLeavePeriodId = 2)
			   SET  @rDays = (@rDays /2)
			IF(@rLeavePeriodId = 3)
			   SET  @rDays = (@rDays /4)
			END
		ELSE
		BEGIN
			SET @rDays = 0
		END
		RETURN  @rDays
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sHrm].[fTeachingSubjectGet](@rEmployeeId bigint)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @rTeachingSubject nvarchar(2000)
	(
		SELECT @rTeachingSubject=COALESCE(@rTeachingSubject+', ','') +  Subjects 
		FROM sHrm.tEmployeeQualification 
		WHERE EmployeeId = @rEmployeeId
	)
	
	RETURN ISNULL(@rTeachingSubject,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER FUNCTION [sHrm].[fWeekHOffGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)

--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
--BEGIN
--	Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95
--	Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95  
-- END 
-- Else
-- BEGIN
--	Select @lWeekDay1 = EmployeeFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
--	Select @lWeekDay2 = EmployeeSEcondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
-- END
 
SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
 --Select  @lStatus =  Case When @lWeekOff = @lWeekDay1 Then 'W' Else '-' End 
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
 
--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
--BEGIN
	 
--	Select @EmpFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
--	Select @EmpSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	 
-- END
-- Else
-- BEGIN
   
--	Select @EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
--	Select @EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 

	IF EXISTS(SELECT 1 FROM sActivity.tWeekOffSetting WHERE SourceId = @rEmployeeId AND SourceTypeId=95)
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
	END 
	ELSE
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END
	 
-- END
--IF(@lDate > GETDATE())
--BEGIN
--	SET @lStatus = ''
--	RETURN @lStatus	
--END	 
	 
--if @lStatus = 'W'
--BEGIN

	
	if @EmpFirstWeekOffRule = 1 
	BEGIN		
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				
				Set @lStatus = 'W'
				RETURN @lStatus	
			 END 

			  if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 						
						SET @lStatus = 'A'
					END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
					 BEGIN
						 SET @lStatus = 'H'	
						 RETURN @lStatus		
					 END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
	END
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
						IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @lStatus = 'H'	
			   RETURN @lStatus		
		        END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus
				END	
			END
		--	Else
		--	BEGIN
		--		Set @lStatus ='-'
		--	END
			 
		--END
		--Else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
						--Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	Else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	Else if @EmpFirstWeekOffRule = 5 
	BEGIN   
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 

			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			        SET @lStatus = 'H'	
			RETURN @lStatus		
		    END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 6 
	BEGIN	   
		IF @WeekNumber = 1 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END	
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END		 
		END 
	END
	
	Else if @EmpFirstWeekOffRule = 7 
	BEGIN  
		IF @WeekNumber = 2 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		    BEGIN
			    SET @lStatus = 'H'	
				RETURN @lStatus		
		    END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	
	Else if @EmpFirstWeekOffRule = 8 
	BEGIN  
		IF @WeekNumber = 3 
		BEGIN	
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END
	END
	Else if @EmpFirstWeekOffRule = 9 
	BEGIN
		IF @WeekNumber = 4 
		BEGIN			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus		
			END	 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus	
			END
		END		 
	END	
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
	END
	   
      if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @lStatus = 'W'
			RETURN @lStatus	
		END
		if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
		BEGIN 
			SET @lStatus = 'P'
		END
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
		BEGIN 
			SET @lStatus = 'A'
		END	
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND SourceTypeId in (2004, 3)
		AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		BEGIN
			SET @lStatus = 'H'	
			RETURN @lStatus	
		END
		IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
		BEGIN
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			RETURN @lStatus	
		END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus= '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus	
				END
			END
		--	else
		--	BEGIN
		--		Set @lStatus='-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN	
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus
				END	
			END
		--	else
		--	BEGIN
		--		Set @lStatus = '-'
		--	END
			 
		--END
		--else
		--BEGIN
		--	Set @lStatus = '-'
		--	RETURN @lStatus	
		--END
	END
	Else if @EmpSecondWeekOffRule = 5
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	Else if @EmpSecondWeekOffRule = 6
	BEGIN
		IF @WeekNumber = 1 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND SourceTypeId in (2004, 3)
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	Else if @EmpSecondWeekOffRule = 7
	BEGIN
		IF @WeekNumber = 2 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END
					
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	
	Else if @EmpSecondWeekOffRule = 8
	BEGIN
		IF @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END	
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END	 
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END
	END
	
	Else if @EmpSecondWeekOffRule = 9
	BEGIN
		IF @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus	
            END 
			if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
			BEGIN 
				SET @lStatus = 'P'
			END
				if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
			BEGIN 
				SET @lStatus = 'A'
			END		
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
				AND SourceTypeId in (2004, 3)
				AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				RETURN @lStatus	
			END
			IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
			BEGIN	
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
				RETURN @lStatus
			END	
		END 
	END
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				RETURN @lStatus
			END

				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
					 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=0)
					BEGIN 
						SET @lStatus = 'A'
					END
					IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId in (2004, 3)
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				IF Exists(select 1 From sHrm.tLeave L WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate)
				BEGIN	
					SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
					FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
					WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
					RETURN @lStatus
				END	
			END
	END
--END
 
 
  
			
	RETURN @lStatus	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sHrm].[fWeekHOffGetBio](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)

SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)

	--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
	--BEGIN
	--	Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95
	--	Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95  
	--END 
	--Else
	--BEGIN
	--	Select @lWeekDay1 = EmployeeFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	--	Select @lWeekDay2 = EmployeeSEcondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	--END

	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1

	--if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
	--BEGIN
	--	Select @EmpFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	--	Select @EmpSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	--END
	--Else
	--BEGIN
	--	Select @EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	--	Select @EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	--END
	
	
	IF EXISTS(SELECT 1 FROM sActivity.tWeekOffSetting WHERE SourceId = @rEmployeeId AND SourceTypeId=95)
	BEGIN
		SELECT @lWeekDay1 = FirstWeekOffDayId, @lWeekDay2 = SecondWeekOff,@EmpFirstWeekOffRule = FristWeekOffRuleId,@EmpSecondWeekOffRule = SEcondWeekOffRuleId FROM sActivity.tWeekOffSetting  WHERE SourceId = @rEmployeeId AND SourceTypeId=95
	END 
	ELSE
	BEGIN
		SELECT @lWeekDay1 = EmployeeFirstWeekOffDayId,@lWeekDay2 = EmployeeSEcondWeekOffDayId,@EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId,@EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId  FROM sSetup.tOrganizationMaster  WHERE Id = @rOrgId 
	END

	
	--IF @lWeekDay1 > 1 
	--BEGIN
	--	SET @lWeekDay1 = @lWeekDay1 -1
	--END
	
	--IF @lWeekDay2 > 1 
	--BEGIN
	--	SET @lWeekDay2 = @lWeekDay2 -1
	--END


	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId AND EA.SourceTypeId = 2004 WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
	AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	BEGIN
		RETURN 'H'	
	END	

	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id WHERE ES.BatchId = @rBatchId
	AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1 AND EA.SourceId = @rEmployeeId AND EA.SourceTypeId = 95)  
	BEGIN
		RETURN 'H'	
	END
		
	-- Emp First Week Of fRule
	if @EmpFirstWeekOffRule = 1 
	BEGIN
		if(@lWeekOff = @lWeekDay1)
		--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
		BEGIN	
			RETURN 'W'
		END 					 
	END
	Else if @EmpFirstWeekOffRule = 2 
		BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'				
			END
		END
		END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			If(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'							 
			END
	END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
		if(@lWeekOff = @lWeekDay1)
		--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'			
			END
	END
	END
	else if @EmpFirstWeekOffRule = 5
	BEGIN		   
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END	
		END
	END
	else if @EmpFirstWeekOffRule = 6
	BEGIN		   
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END	
	 END
	else if @EmpFirstWeekOffRule = 7
	BEGIN		   
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END
	END	
	else if @EmpFirstWeekOffRule = 8
	BEGIN
		   
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'				
			END
		END
	END
	else if @EmpFirstWeekOffRule = 9
	BEGIN		   
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END
	END
	--Add EmpFirstWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpFirstWeekOffRule = 10
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
		if(@lWeekOff = @lWeekDay1)
		--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay1,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'			
			END
		END
	END
	
	-- Emp Second Week Off Rule
	if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
		 --if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END	
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END	
		END
	END
	else if @EmpSecondWeekOffRule = 5
	BEGIN		 
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END	
		END
	END
	else if @EmpSecondWeekOffRule = 6
	BEGIN		 
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'				
			END
		END				
	END
	else if @EmpSecondWeekOffRule = 7
	BEGIN		 
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'				
			END
		END
	END
	else if @EmpSecondWeekOffRule = 8
	BEGIN			
		if @WeekNumber = 3
		BEGIN			
			if(@lWeekOff = @lWeekDay2)		
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END				
		END
	END
	else if @EmpSecondWeekOffRule = 9
	BEGIN		 
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END
		END
	END		
	--Add EmpSecondWeekOffRule = 10 due to mantisid - 0028624
	else if @EmpSecondWeekOffRule = 10
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 2 or @WeekNumber = 3 or @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			--if convert(date,sHRM.fnGetNthWeekdayOfMonth(@lDate,@lWeekDay2,@WeekNumber))=@lDate
			BEGIN
				RETURN 'W'
			END	
		END
	END
	SELECT @lStatus=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
	
	--if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
	--BEGIN 		
	--	RETURN 'P'
	--END	
	
	--IF(@lStatus='-')
	--	SET @lStatus = @rBiometricStatus
		
	RETURN @lStatus	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sHrm].[fWeekHOffHolidayGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
	BEGIN
		
		DECLARE @lDate nvarchar(20)  
		DECLARE @lWeekOff nvarchar(100)
	 
		SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
		
		IF ISDATE (@lDate)=1
		BEGIN
			DECLARE @tbl TABLE(tid int identity(1,1),id int)
			INSERT INTO @tbl
			SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS dgid FROM
			(
				SELECT CAST('<XMLRoot><RowData>' + REPLACE(weekoffs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
				FROM sSetup.tOrganizationMaster where Id = @rOrgid
			) t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
			 
			SET @lWeekOff = [sAssessment].[fGetWeekdayNumber](@lDate)
			
			IF  EXISTS(SELECT 1 from @tbl where @lWeekOff in (id)) 
			BEGIN
				SET @lStatus = 'W'
				--RETURN @lStatus	
			END	 
			
			IF(@lDate > GETDATE())
			BEGIN
				SET @lStatus = ''
				--RETURN @lStatus	
			END	 
			
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE  ((ES.BatchId=@rBatchId) OR (@rBatchId=0))  AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1 AND SourceTypeId = 2004)  
			BEGIN
				SET @lStatus = 'H'	
				--RETURN @lStatus		
			END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
		 END
	END	
	RETURN @lStatus	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER FUNCTION [sHrm].[fWeekHOffHolidayLeaveGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rEmployeeId bigint,@rStatus nvarchar(20),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
 
	DECLARE @lDate nvarchar(20) = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
	
	
 
	if(ISDATE(@lDate)=1)
	BEGIN
     IF  EXISTS(SELECT 1
		 from  sHrm.tLeave where   @lDate BETWEEN FromDate AND ToDate AND  OrgId = @rOrgid AND EmployeeId = @rEmployeeId AND BatchId =@rBatchid) 
		 BEGIN
				SET @rStatus = (Select LTM.Code from sHrm.tLeaveTypeMaster LTM INNER JOIN sHrm.tLeave l On LTM.Id= l.LeaveTypeId AND l.StatusId!=551 where  (@lDate BETWEEN L.FromDate AND L.ToDate ) AND L.OrgId = @rOrgid AND L.EmployeeId = @rEmployeeId AND L.BatchId =@rBatchid)
				RETURN @rStatus	
		END	 
	 END
	RETURN @rStatus	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sLoan].[fEmployeeLoanInstalmentGet](@SalaryMonth bigint, @SalaryYear int,@EmployeeId bigint ,@PayElementDefaultId int  )
RETURNS decimal(12,2) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rInstalmentAmount decimal(12,2)
		
		
	SELECT @rInstalmentAmount=ISNULL(SUM(ISNULL(EMI.EmiAmount,0)+ISNULL(EMI.InterestAmount,0)),0)
	
	FROM [sLoan].[tLoanDetail]  AS LND
		INNER JOIN [sLoan].[tLoanTypeMaster]         AS LTM ON LTM.Id=LND.LoanTypeId
		INNER JOIN sHrm.tEmployeeMaster              AS EMP ON EMP.Id=LND.EmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
		INNER JOIN [sLoan].[tLoanPayrollMapping]     AS LPM ON LPM.LoanTypeId=LTM.Id    AND LTM.OrgId=LPM.OrgId
		INNER JOIN [sPayroll].[tPayElementDefault]   AS PED ON PED.ID=LPM.PayElementId  AND LPM.OrgId=LTM.OrgId
		INNER JOIN [sLoan].[tLoanEMI]				 AS EMI ON EMI.LoanDetailId=LND.id
	WHERE LND.IsObsolete=0
		AND EMI.IsObsolete=0
		AND EMI.StatusId = 1
		AND ((LND.EmployeeId=@EmployeeId)			    OR (@EmployeeId=0))
		AND ((LPM.PayElementId=@PayElementDefaultId)    OR (@PayElementDefaultId=0))
		AND ((MONTH(EMI.EmiDate)=@SalaryMonth)		    OR (@SalaryMonth=0))
		AND ((YEAR(EMI.EmiDate)=@SalaryYear)			OR (@SalaryYear=0)) 
				
    RETURN ISNULL(@rInstalmentAmount,0) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sOrderEntry].[fTestMaximumValueGet](@rTestParameterId int,@rGenderId int,@rServiceValue decimal(12,2))
RETURNS [decimal](12,2) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lMaximum  decimal(12,2)
(SELECT @lMaximum  = Maximum from sOrderEntry.tTestParameterDetail
where TestParameterId=@rTestParameterId AND GenderId = @rGenderId
AND Maximum >= @rServiceValue AND Minimum <= @rServiceValue) 
 
    RETURN @lMaximum 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sOrderEntry].[fTestMinimumValueGet](@rTestParameterId int,@rGenderId int,@rServiceValue decimal(12,2))
RETURNS [decimal](12,2) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lMinimum  decimal(12,2)
(SELECT @lMinimum  = Minimum from sOrderEntry.tTestParameterDetail
where TestParameterId=@rTestParameterId AND GenderId = @rGenderId
AND Maximum >= @rServiceValue AND Minimum <= @rServiceValue) 
    RETURN @lMinimum 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION  [sPayroll].[fCalculateDependentBasedOnFormula](@lFormula nvarchar(200), @lDependentAmount decimal(22,2))
RETURNS decimal(22,2)
AS
BEGIN
	DECLARE @lFormulaToGetValue TABLE  (Id int Identity, FormulaStr nvarchar(50))
	INSERT INTO @lFormulaToGetValue SELECT * FROM sCommon.fnSplit(@lFormula,';')
	DECLARE @StaticString nvarchar(50) = 'DPE>='
	DECLARE @OutAmount decimal (22,2)
	DECLARE @Tablecnt INT;
	DECLARE @lcnt INT;
	DECLARE @tempStr NVARCHAR(50)
	DECLARE @lReturnAmount decimal(22,2)
	
	SET @Tablecnt = 0;
	SET @lcnt = 1;
	IF RTRIM(LTRIM(@lFormula)) = '' 
	BEGIN
		SET @OutAmount = 0
	END
	SELECT @Tablecnt = MAX(Id) From @lFormulaToGetValue
	WHILE @lcnt <= @Tablecnt
	BEGIN	
		SELECT @tempStr = LTRIM(RTRIM(FormulaStr)) FROM @lFormulaToGetValue WHERE Id = @lcnt
		IF CHARINDEX(@StaticString, @tempStr,1 ) > 0
		BEGIN	
			SET @lReturnAmount = ISNULL((SUBSTRING(@tempStr, CHARINDEX(@StaticString, @tempStr,1 ) + Len(@StaticString), CHARINDEX(',', @tempStr, 1) - (CHARINDEX(@StaticString, @tempStr,1) + Len(@StaticString)))),0)					
			If CHARINDEX(',', @tempStr, 1) > 0 
            BEGIN
		         SET @OutAmount = SUBSTRING(@tempStr, CHARINDEX(',', @tempStr, 1) + 1,10)
		         IF @lDependentAmount >= @lReturnAmount  
				 BEGIN				 
					SET @OutAmount = @OutAmount 
				 	BREAK
				 END
	        END 
	    END     
	    Else
			BEGIN										
				SET @OutAmount  = SUBSTRING(reverse(@lFormula),1, CHARINDEX(';',reverse(@lFormula),1)-1)
				SET @OutAmount =  reverse(@OutAmount)
			End 		
		SET @lcnt = @lcnt + 1;
	END	
	
	RETURN @OutAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sPayroll].[fCalculateLWP]
	(
		@rEmployeeId bigint,
		@rPayProcessId int,	 
		@rAmount decimal(22,6)
	)
RETURNS DECIMAL(22,6)
AS
	BEGIN	
        DECLARE @lLWPDeduction decimal(22,2)
        SET @lLWPDeduction = 0.0

		IF(@rAmount > 0)
		BEGIN 
			DECLARE @1SalaryMonth int
			DECLARE @1SalaryYaer int
			DECLARE @1WorkingDays int
			DECLARE @1TotalDays int			
			DECLARE @1LWP decimal(12,2) 
			
			
			
			
			SELECT @1SalaryMonth = SalaryMonth,@1SalaryYaer = SalaryYear from sPayroll.tPayProcess Where Id = @rPayProcessId	 
			SELECT @1LWP = Lwp, @1WorkingDays = WorkingDays FROM sPayroll.tPayProcessEmployee WHERE PayProcessId=@rPayProcessId
			AND EmployeeId = @rEmployeeId
			--where ForMonth = @1SalaryMonth AND ForYear = @1SalaryYaer AND EmployeeId = @rEmployeeId	   
			--SELECT @1LWP = LWP, @1WorkingDays = TotalWorkingDays from sHrm.tEmployeeAttendance 
			--where ForMonth = @1SalaryMonth AND ForYear = @1SalaryYaer AND EmployeeId = @rEmployeeId	
			
			--select @1TotalDays = datediff(day, 
			--		dateadd(day, 0, dateadd(month, ((@1SalaryYaer - 1900) * 12) + @1SalaryMonth - 1, 0)),
			--		dateadd(day, 0, dateadd(month, ((@1SalaryYaer - 1900) * 12) + @1SalaryMonth, 0))
			--		)
			
			 
		 --   IF(@1TotalDays > 0)
			SET @lLWPDeduction =  ((@rAmount/@1WorkingDays) * @1LWP)
	    END
	    
	    
    RETURN ISNULL(@lLWPDeduction,0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sPayroll].[fCalculateProfessionalTaxRange]
	(		
		@rSalary decimal(22,6)
	)
RETURNS DECIMAL(22,6)
AS
	BEGIN	
        DECLARE @lTax decimal(22,6)
        DECLARE @1LowerSalaryRange Decimal(22,6)        
        DECLARE @1GraterSalaryRange Decimal(22,6)
        
        SET @lTax = 0.0 
        
			SELECT  TOP 1 @lTax = Tax  FROM sPayroll.tProfessionalTaxRange where Salary < @rSalary Order By Salary Desc
		 
		    --select @lTax = Tax from sPayroll.tProfessionalTaxRange where Salary >= @1LowerSalaryRange AND Salary < @1GraterSalaryRange
			 
	    
    RETURN @lTax
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sPayroll].[fGetPayElementIncludeInPayslip]
	(
		@rMonth Int,
		@rYear Int,
		@rPayElementId Int
	)
RETURNS bit
AS
BEGIN

	DECLARE @IsIncludeInPaySlip Bit 
	DECLARE @lDt AS DATE
	SELECT @lDt = ( CONVERT(DATETIME,  CAST(@rMonth AS VARCHAR) + '/' + '1' + '/' + CAST(@rYear AS VARCHAR)))
	SET @lDt =  DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @lDt) + 1, 0))	
	
	     BEGIN 
			SET @IsIncludeInPaySlip = (SELECT IsIncludeInPaySlip FROM  sPayroll.tPayElementSetup
										WHERE (EffectiveDate <= @lDt OR 
										ISNULL(EffectiveDate, '1/1/1900') = '1/1/1900')
										AND PayElementId = @rPayElementId)
				
			
		
		END	   
    RETURN @IsIncludeInPaySlip
    
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER FUNCTION [sPayroll].[fGetPayElementNetAmount] (
	@rPayElementId INT
	,@rEmployeeId BIGINT
	,@rPayrollGroupId INT
	,@rPayrollYearId INT
	,@rIsEmployeeSpecific BIT
	)
RETURNS DECIMAL(12, 2)
AS
BEGIN
	DECLARE @lPaySetupId INT;

	SELECT @lPaySetupId = Id
	FROM sPayroll.tPaySetup PS
	WHERE PS.PayElementId = @rPayElementId
		AND PS.SourceId = CASE 
			WHEN ISNULL(@rIsEmployeeSpecific, 0) = 1
				THEN @rEmployeeId
			ELSE @rPayrollGroupId
			END
		AND PS.SourceTypeId = CASE 
			WHEN ISNULL(@rIsEmployeeSpecific, 0) = 1
				THEN 95
			ELSE 2020
			END

	DECLARE @lReturnAmount DECIMAL(12, 2) = 0

	SELECT @lReturnAmount = SUM(CASE 
				WHEN Am.IsDeduct = 0
					THEN Am.Amount
				WHEN Am.IsDeduct = 1
					THEN - Am.Amount
				ELSE 0
				END) * ISNULL(PS.Percentage, 0) / 100
	FROM sPayroll.tPaySetup PS
	INNER JOIN (
		SELECT PSD.PaySetupId
			,PSD.IsDeduct
			,CASE 
				WHEN PE.IsDepend = 0
					THEN ISNULL((
								SELECT TOP 1 PS.Amount
								FROM sPayroll.tPaySetup PS
								WHERE PS.PayElementId = PE.Id
									AND PS.SourceId = CASE 
										WHEN ISNULL(PE.IsEmployeeSpecific, 0) = 1
											THEN @rEmployeeId
										ELSE @rPayrollGroupId
										END
									AND PS.SourceTypeId = CASE 
										WHEN ISNULL(PE.IsEmployeeSpecific, 0) = 1
											THEN 95
										ELSE 2020
										END
									AND PS.PayrollYearId = @rPayrollYearId
								), 0)
				ELSE sPayroll.fGetPayElementNetAmount(PE.Id, @rEmployeeId, @rPayrollGroupId, @rPayrollYearId, PE.IsEmployeeSpecific)
				END AS Amount
		FROM sPayroll.tPaySetupDependent PSD
		INNER JOIN sPayroll.tPayElement PE ON PE.Id = PSD.DependentPayElementId
		WHERE PSD.PaySetupId = @lPaySetupId
		) AS Am ON PS.Id = @lPaySetupId
	GROUP BY PS.Id
		,PS.Percentage

	RETURN @lReturnAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sPayroll].[fGetPaySetupDependentElement]
	( 
		@rPaySetupId int  
	)
RETURNS Nvarchar(Max)
AS
  BEGIN	 
       
       DECLARE @1DependPayElement nvarchar(MAX)
      
       select  @1DependPayElement =  STUFF((SELECT ', ' + Title
                    from sPayroll.tPaySetupDependent PSD INNER JOIN sPayroll.tPayElement PE ON PE.ID = PSD.DependentPayElementId  Where PaySetupId = @rPaySetupId                
                    order by PaySetupId
            FOR XML PATH(''), TYPE
            ).value('.','NVARCHAR(MAX)') 
        ,1,1,'')
        
        
        RETURN ISNULL(@1DependPayElement,'')
      	  
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sPayroll].[fGetPreviousEsiDeduction] 
(@rEffectiveFromDate AS DATE, @rEffectiveToDate AS DATE) 
RETURNS INT AS  
BEGIN 
	
--DECLARE @rEffectiveDate DATETIME
--SET @rEffectiveDate = '2010-6-06'
	DECLARE @lHasPreviousEsiDeduction INT 
	DECLARE @lStartMonth INT
	DECLARE @lEndMonth INT
	DECLARE @lMidMonth INT
	
	SET @lHasPreviousEsiDeduction = 0
	SET @lStartMonth = (SELECT MONTH(StartDate) FROM sPayroll.tFiscalYear WHERE FiscalYearTypeId = 3)
	SET @lEndMonth = (SELECT MONTH(EndDate) FROM sPayroll.tFiscalYear WHERE FiscalYearTypeId = 3)
	SET @lMidMonth = (@lStartMonth + 6)

--SELECT MONTH(@rEffectiveDate) EffectiveMonth, @lStartMonth StartMonth, @lEndMonth EndMonth, @lMidMonth AS MidMonth
IF(MONTH(@rEffectiveFromDate) BETWEEN @lStartMonth AND @lMidMonth)
BEGIN

WHILE (@lMidMonth > = @lStartMonth)
BEGIN
   IF ((SELECT DISTINCT ProcessMonth FROM sPayroll.tEsiProcess EP
		INNER JOIN sPayroll.tPayElementProcessDetail PEPD
			ON EP.PayElementProcessDetailId = PEPD.Id
		INNER JOIN sPayroll.tPayElementProcess PEP
			ON PEP.Id = PEPD.PayElementProcessId
		 WHERE PEP.ProcessMonth = @lMidMonth) > 0)
   BEGIN
	   SET @lHasPreviousEsiDeduction = 1	
	   BREAK	
   END
   ELSE
	   BEGIN
	   --SELECT @lMidMonth AS MidMonth
	   SET @lMidMonth = @lMidMonth - 1
   --CONTINUE 
   END

END
END

ELSE IF(MONTH(@rEffectiveFromDate) BETWEEN @lMidMonth AND @lEndMonth)
BEGIN

WHILE (@lMidMonth < = @lEndMonth)
BEGIN
   IF ((SELECT DISTINCT ProcessMonth FROM sPayroll.tEsiProcess EP
		INNER JOIN sPayroll.tPayElementProcessDetail PEPD
			ON EP.PayElementProcessDetailId = PEPD.Id
		INNER JOIN sPayroll.tPayElementProcess PEP
			ON PEP.Id = PEPD.PayElementProcessId
		 WHERE PEP.ProcessMonth = @lMidMonth) > 0)
   BEGIN
	   SET @lHasPreviousEsiDeduction = 1	
	   BREAK	
   END
   ELSE
	   BEGIN
	   --SELECT @lMidMonth AS MidMonth
	   SET @lMidMonth = @lMidMonth + 1
   --CONTINUE 
   END

END
END

RETURN @lHasPreviousEsiDeduction
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sPayroll].[fMonthYearForPayrollGet](@rPayrollYearId int)
RETURNS  @List TABLE (
		 MonthNumber tinyint,
		 YearNumber smallint,
		 MonthTitle nvarchar(20),
		 NoOfDays tinyint,
		 PayrollYearId int 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	declare @rFromDate DATE
    declare @rToDate DATE 
	Select @rFromDate=FromDate,@rToDate=ToDate FROM sPayroll.tPayrollYearMaster WHERE Id=@rPayrollYearId 
		 
	WHILE (@rFromDate <= @rToDate)
	BEGIN	
	INSERT INTO @List 
	SELECT 
			DATEPART(MONTH,@rFromDate) AS MonthNumber,
			DATENAME(YEAR,@rFromDate) AS YearNumber,
			DATENAME(MONTH,@rFromDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate) + 1, 0)),
			@rPayrollYearId AS PayrollYearId
			SET @rFromDate = DATEADD(M,1,@rFromDate)  
	END 
	 
IF NOT EXISTS(SELECT * FROM @List WHERE MonthNumber = DATEPART(MONTH,@rToDate) AND 
YearNumber = DATENAME(YEAR,@rToDate)
AND PayrollYearId  = @rPayrollYearId)
BEGIN
INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rToDate) AS MonthNumber,
			DATENAME(YEAR,@rToDate) AS YearNumber,
			DATENAME(MONTH,@rToDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate) + 1, 0)),
			@rPayrollYearId AS PayrollYearId 
END
			  

		  
	
	--;with tMonth_Year (CurrentDate,BatchId)
 --   AS
 --   (
 --       SELECT @rFromDate,@rBatchId
 --       UNION ALL
 --       SELECT DATEADD(MONTH,1,CurrentDate),@rBatchId
 --       from tMonth_Year
 --       where DATEADD(MONTH,1,CurrentDate)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rToDate)+1,0))
 --   )
    
 --   INSERT INTO @List 
 --   SELECT 
	--		DATEPART(MONTH,CurrentDate) AS MonthNumber,
	--		DATENAME(YEAR,CurrentDate) AS YearNumber,
	--		DATENAME(MONTH,CurrentDate) AS MonthTitle,
	--		@rBatchId AS BatchId
	--FROM 
	--	tMonth_Year 
    
    RETURN  
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sPayroll].[fPayElementSortOrderGet]
	(
		@rMonth Int,
		@rYear Int,
		@rPayElementId Int
	)
RETURNS INT
AS
BEGIN

	DECLARE @lSortOrder Int 
	DECLARE @lDt AS DATE
	SELECT @lDt = ( CONVERT(DATETIME,  CAST(@rMonth AS VARCHAR) + '/' + '1' + '/' + CAST(@rYear AS VARCHAR)))
	SET @lDt =  DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @lDt) + 1, 0))	
	
	----DECLARE @rDate DATETIME
	----SET @rDate =  '2010-9-04'
     
       BEGIN 
			SET @lSortOrder = (SELECT SortOrder FROM  sPayroll.tPayElementSetup
								WHERE (EffectiveDate <= @lDt OR 
								ISNULL(EffectiveDate, '1/1/1900') = '1/1/1900')
								AND PayElementId = @rPayElementId)
				
			
		
		END	
   
    RETURN @lSortOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sPoliciesForms].[fFileFolderSizeGet](@len FLOAT)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @order int= 1
	DECLARE @size NVARCHAR(50)=''

	WHILE  (@len >= 1024  AND  @order < 5)
		BEGIN
		SET 	@order=@order+1
		SET @len = @len / 1024 
	END

	select @size=item  from [sCommon].[fnSplitRowID]('BYTES,KB,MB,GB,TB,',',') WHERE RowID=@order

	RETURN CONVERT(NVARCHAR(50),CEILING(@len))+'  '+ @size
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sPoliciesForms].[fFolderPathGet] (@FolderId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @columns varchar(max) = ''
    ;WITH cteReports (id, PerentFolderId, Title, EmpLevel)AS (

	SELECT id, PerentFolderId, case when PerentFolderId=0 then  CAST(CONVERT(varchar,CreatedUserId)  + '\' + ISNULL(Title, '')  AS VARCHAR(8000)) else CAST(ISNULL(Title, '')  AS VARCHAR(8000)) end, 0 AS EmpLevel 
	FROM [sPoliciesForms].[tFolderFile]
    WHERE id = @FolderId      
	UNION ALL
    
	SELECT e.id, e.PerentFolderId,  case when e.PerentFolderId=0 then  CAST(CONVERT(varchar,e.CreatedUserId)  + '\' + ISNULL(e.Title, '')  AS VARCHAR(8000)) else CAST(ISNULL(e.Title, '')  AS VARCHAR(8000)) end, r.EmpLevel + 1
    FROM [sPoliciesForms].[tFolderFile] e
    INNER JOIN cteReports r ON e.id = r.PerentFolderId
    )
    SELECT @columns = COALESCE(@columns + '\', '') + Title
    FROM cteReports
    ORDER BY id

	SELECT @columns=case when len(@columns)>0 then @columns  else @columns end

    RETURN @columns
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sPoliciesForms].[fFolderSizeGet](@PerentFolderId INT)
RETURNS FLOAT WITH EXECUTE AS CALLER
AS 
BEGIN

	DECLARE @Size FLOAT=0

	;WITH FolderSize (id,  Size)
	AS
	(
		SELECT id, ISNULL(Size,0)Size 
		FROM [sPoliciesForms].[tFolderFile]  
		WHERE PerentFolderId =@PerentFolderId
  		UNION ALL
  		SELECT e.id,  ISNULL(e.Size,0)Size 
		FROM [sPoliciesForms].[tFolderFile] e
		INNER JOIN FolderSize r
		ON e.PerentFolderId = r.id
	)
	SELECT @Size= ISNULL(SUM(Size),0) FROM FolderSize
	RETURN @Size
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sProcurement].[fGetStockIssueQuantityWithoutReturn] (
    @rStockIssueId INT,
    @rStockIssueDetailId INT
)
RETURNS DECIMAL(18, 2)
AS
BEGIN
    DECLARE @Quantity DECIMAL(18, 2)

    SELECT @Quantity = (AVG(SIB.Quantity) - SUM(SIRB.ReturnQuantity))
    FROM sProcurement.tStockIssueReturn SIR
    INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
    INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
    WHERE SIR.StockIssueId = @rStockIssueId 
      AND SIB.StockIssueDetailId = @rStockIssueDetailId
    GROUP BY SIR.StockIssueId, SIB.StockIssueDetailId

    RETURN @Quantity
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sProcurement].[fnGetStockDepositeAdd](@StockIssueReturnId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lResult  VARCHAR(MAX)=''

	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SIRB.ReturnQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM 
	sProcurement.tStockIssueReturn SIR
	INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
	INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.Id = SIB.StockIssueDetailId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE 
	SIR.Id = @StockIssueReturnId
	)

	SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
 
	RETURN @lResult

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sProcurement].[fnGetStockDepositeDetail](@rDepositHeadId int,@rAcademicId bigint, @rFromDate date,@rToDate date)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lStockItemName nvarchar(max)=''

	SELECT @lStockItemName = STUFF((SELECT ',' + (ISNULL(SIM.Title,''))
							 FROM sIp.tStoreLocationMaster SLM
								INNER JOIN sProcurement.tStockIssue SI ON SI.FromStoreLocationId = SLM.Id --AND SI.IssueToSourceId =  @rAcademicId 
								INNER JOIN sProcurement.tStockIssueDetail SD ON SD.StockIssueId = SI.Id
								INNER JOIN sStudent.tAcademic A ON A.Id = SI.IssueToSourceId
								INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SD.StockItemId

								WHERE 
								A.Id = @rAcademicId 
								AND SLM.DepositHeadId = @rDepositHeadId
								AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
								AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)') 
							,1,1,'')
 
	RETURN ISNULL(@lStockItemName,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sSetup].[fMonthYearForBatchGet](@rBatchId int)
RETURNS @List TABLE (
	 MonthNumber tinyint,
	 YearNumber smallint,
	 MonthTitle nvarchar(20),
	 NoOfDays tinyint,
	 BatchId int 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	declare @rFromDate DATE
    declare @rToDate DATE 
	Select @rFromDate=FromDate,@rToDate=ToDate FROM sSetup.tBatchMaster WHERE Id=@rBatchId 
	 
	 WHILE (@rFromDate <= @rToDate)
	BEGIN
	
	
	INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rFromDate) AS MonthNumber,
			DATENAME(YEAR,@rFromDate) AS YearNumber,
			DATENAME(MONTH,@rFromDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate) + 1, 0)),
			@rBatchId AS BatchId	 

		SET @rFromDate = DATEADD(M,1,@rFromDate)  
	END
	
 
IF NOT EXISTS(SELECT * FROM @List WHERE MonthNumber = DATEPART(MONTH,@rToDate) AND 
YearNumber = DATENAME(YEAR,@rToDate)
AND BatchId  = @rBatchId)
BEGIN
INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rToDate) AS MonthNumber,
			DATENAME(YEAR,@rToDate) AS YearNumber,
			DATENAME(MONTH,@rToDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate) + 1, 0)),
			@rBatchId AS BatchId 
END
			  

		  
	
	--;with tMonth_Year (CurrentDate,BatchId)
 --   AS
 --   (
 --       SELECT @rFromDate,@rBatchId
 --       UNION ALL
 --       SELECT DATEADD(MONTH,1,CurrentDate),@rBatchId
 --       from tMonth_Year
 --       where DATEADD(MONTH,1,CurrentDate)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rToDate)+1,0))
 --   )
    
 --   INSERT INTO @List 
 --   SELECT 
	--		DATEPART(MONTH,CurrentDate) AS MonthNumber,
	--		DATENAME(YEAR,CurrentDate) AS YearNumber,
	--		DATENAME(MONTH,CurrentDate) AS MonthTitle,
	--		@rBatchId AS BatchId
	--FROM 
	--	tMonth_Year 
    
    RETURN  
    
END


 
 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sSetup].[fMonthYearForBatchLeaveGet](@rBatchId int)
RETURNS  @List TABLE (
		 MonthNumber tinyint,
		 YearNumber smallint,
		 MonthTitle nvarchar(20),
		 NoOfDays tinyint,
		 BatchId int 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	declare @rFromDate DATE
    declare @rToDate DATE 
	Select @rFromDate=LeaveYearFromDate,@rToDate=LeaveYearToDate FROM sSetup.tBatchMaster WHERE Id=@rBatchId 
		 
	WHILE (@rFromDate <= @rToDate)
	BEGIN	
	INSERT INTO @List 
	SELECT 
			DATEPART(MONTH,@rFromDate) AS MonthNumber,
			DATENAME(YEAR,@rFromDate) AS YearNumber,
			DATENAME(MONTH,@rFromDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate) + 1, 0)),
			@rBatchId AS BatchId
			SET @rFromDate = DATEADD(M,1,@rFromDate)  
	END 
	 
IF NOT EXISTS(SELECT * FROM @List WHERE MonthNumber = DATEPART(MONTH,@rToDate) AND 
YearNumber = DATENAME(YEAR,@rToDate)
AND BatchId  = @rBatchId)
BEGIN
INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rToDate) AS MonthNumber,
			DATENAME(YEAR,@rToDate) AS YearNumber,
			DATENAME(MONTH,@rToDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate) + 1, 0)),
			@rBatchId AS BatchId 
END
			  

		  
	
	--;with tMonth_Year (CurrentDate,BatchId)
 --   AS
 --   (
 --       SELECT @rFromDate,@rBatchId
 --       UNION ALL
 --       SELECT DATEADD(MONTH,1,CurrentDate),@rBatchId
 --       from tMonth_Year
 --       where DATEADD(MONTH,1,CurrentDate)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rToDate)+1,0))
 --   )
    
 --   INSERT INTO @List 
 --   SELECT 
	--		DATEPART(MONTH,CurrentDate) AS MonthNumber,
	--		DATENAME(YEAR,CurrentDate) AS YearNumber,
	--		DATENAME(MONTH,CurrentDate) AS MonthTitle,
	--		@rBatchId AS BatchId
	--FROM 
	--	tMonth_Year 
    
    RETURN  
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sSetup].[fPortalXMLTagsReplaceReverse](@lString [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN
    SET  @lString =   sCommon.fReplace(sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace
                                     (sCommon.fReplace(@lString,'#amp;','&'),
                                                                  '#gt;','>'), 
                                                                  '#quot;', '"'), 
                                                                  '#lt;','<'),
                                                                  '#39;', '''')
    RETURN @lString
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER FUNCTION [sSetup].[fStudentCapGet]( @rOrgGroupBatchId int)
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	 Declare  @lStatus nvarchar(10)
	Select @lStatus=COUNT(*)
	from sStudent.tAcademic A 
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId 
	Where BM.OrgGroupBatchId=@rOrgGroupBatchId and SM.StatusId=1 and BM.IsInContext=1
	RETURN @lStatus
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sStudent].[fAssignedBulkClubGet](@rAcademicId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
	  DECLARE @lTempClub TABLE(ClubName nvarchar(100))
	  INSERT INTO @lTempClub(ClubName)
	  SELECT CM.Title AS ClubName FROM sActivity.tClubMaster CM
	  LEFT JOIN sActivity.tAssignClub AC ON AC.ClubId = CM.Id
	  WHERE AC.AcademicId = @rAcademicId
	  
	  DECLARE @rAttClub nvarchar(500)
	  SELECT @rAttClub= coalesce(@rAttClub+',','')+convert(nvarchar(500),ClubName )
	  FROM @lTempClub
		
      RETURN  ISNULL(@rAttClub,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sStudent].[fAssignedClubGet](@rAcademicId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
	  DECLARE @lTempClub TABLE(ClubName nvarchar(100))
	  INSERT INTO @lTempClub(ClubName)
	  SELECT CM.Title AS ClubName FROM sActivity.tClubMaster CM
	  LEFT JOIN sActivity.tAssignClub AC ON AC.ClubId = CM.Id
	  WHERE AC.AcademicId = @rAcademicId AND CM.IsObsolete = 0
	  
	  DECLARE @rAttClub nvarchar(500)
	  SELECT @rAttClub= coalesce(@rAttClub+',','')+convert(nvarchar(500),ClubName )
	  FROM @lTempClub
		
      RETURN  ISNULL(@rAttClub,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sStudent].[fAssignedCustomTagGet](@rAcademicId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
	  DECLARE @lTempCustomTag TABLE(CustomTagName nvarchar(100))
	  INSERT INTO @lTempCustomTag(CustomTagName)
	  SELECT CTM.Title AS CustomTagName FROM sStudent.tCustomTagMaster CTM
	  LEFT JOIN sStudent.tStudentCustomTag SCT ON SCT.CustomTagId = CTM.Id 
	  LEFT JOIN sStudent.vStudentAllDetail SAD ON SAD.StudentId = SCT.StudentId
	  WHERE SAD.AcademicId = @rAcademicId
	  
	  DECLARE @rAttCustomTag nvarchar(500)
	  SELECT @rAttCustomTag= coalesce(@rAttCustomTag+',','')+convert(nvarchar(500),CustomTagName )
	  FROM @lTempCustomTag
		
      RETURN  ISNULL(@rAttCustomTag,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sStudent].[fDivisionInchargeDetailsGet](@rAcademicId bigint, @rBatchId int)
	RETURNS @List TABLE (
				DivisionId int,
				TeacherFullName nvarchar(200),
				TeacherDesignation nvarchar(200),
				TeacherQualification nvarchar(200),
				TeacherPhoto varbinary(max)
			)  
WITH EXECUTE AS CALLER
AS
BEGIN

	DECLARE @lDivisionInchargeId bigint = 0
	DECLARE @lDivisionId int = 0
	DECLARE @lBatchId int = 0

	--SELECT
	--	@lDivisionInchargeId = ISNULL(DM.InchargeEmployeeId, 0),
	--	@lDivisionId = SA.DivisionId
	--	--@lBatchId = SA.BatchId
	--FROM
	--	sStudent.vStudentAllDetail SA
	--	INNER JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
	--	WHERE SA.AcademicId = @rAcademicId

	SELECT TOP 1
		@lDivisionInchargeId = ISNULL(DIE.EmployeeId, 0),
		@lDivisionId = SA.DivisionId
	FROM sStudent.vStudentAllDetail SA
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON  DIE.DivisionId=SA.DivisionId
	WHERE SA.AcademicId = @rAcademicId AND DIE.BatchId = @rBatchId
	ORDER BY DIE.Number DESC

	IF(@lDivisionInchargeId > 0)
	BEGIN

		--WITH tempTable as
		--(
		INSERT INTO @List
		SELECT DIE.DivisionId, 
			ISNULL(EMT1.FirstName+' '+EMT1.MiddleName+' '+EMT1.LastName,'') AS TeacherFullName,
			ISNULL(EDM1.Title,'') AS TeacherDesignation,
			ISNULL(EPD1.Qualification,'') AS TeacherQualification,
			EI1.EmployeePhoto AS TeacherPhoto
			-- ROW_NUMBER() Over(PARTITION BY DIE.DivisionId ORDER BY DIE.Number DESC) As RowNumber
		FROM sSetup.tDivisionInchargeEmployee DIE
			INNER JOIN sHrm.tEmployeeMaster EMT1 ON EMT1.Id= DIE.EmployeeId AND  ISNULL(EMT1.IsOtherUser,0) = 0
			LEFT JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EMT1.Id
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM1 ON EDM1.Id=EJD1.EmployeeDesignationId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD1 ON EPD1.EmployeeId=EMT1.Id
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId=EMT1.Id
		WHERE DIE.DivisionId = @lDivisionId
			AND DIE.BatchId = @rBatchId
			AND DIE.EmployeeId = @lDivisionInchargeId
		--)
		--INSERT INTO @List
		--SELECT DivisionId, TeacherFullName, TeacherDesignation, TeacherQualification, TeacherPhoto FROM tempTable
		--WHERE RowNumber = 1

		RETURN

	END
	ELSE
	BEGIN

		SELECT @lDivisionId = SA.DivisionId
		FROM sStudent.vStudentAllDetail SA
			INNER JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
		WHERE SA.AcademicId = @rAcademicId

		INSERT INTO @List
		SELECT DM.Id AS DivisionId,
			ISNULL(EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName,'') AS TeacherFullName,
			ISNULL(EDM.Title,'') AS TeacherDesignation,
			ISNULL(EPD.Qualification,'') AS TeacherQualification,
			EI.EmployeePhoto AS TeacherPhoto
		FROM sSetup.tDivisionMaster DM
			LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id= DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
		WHERE DM.Id = @lDivisionId

		RETURN

	END
	RETURN
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sStudent].[fGetDashboardStudentCount](@rStatusId INT,@rCommonOrgGroupBatchId INT,@rType nvarchar(100),@rOrgId int)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @StudentCount INT

IF(@rType= 'OrgGroupwiseStudentCount')
BEGIN
	SELECT @StudentCount= (SELECT COUNT(SM.ID)
			 FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0)
				  AND BM.IsInContext = 1)
	
END

IF(@rType= 'OrgwiseStudentCount')
BEGIN
	SELECT @StudentCount= (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND OM.Id = @rOrgId AND BM.IsInContext = 1)
END

IF(@rType= 'OrgSubGroupwiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((OM.OrgSubGroupId = @rOrgId))			 
				  AND BM.IsInContext = 1)
END

IF(@rType= 'DeptwiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster DM on DM.Id=CM.DepartmentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
	WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((DM.Id = @rOrgId)) AND BM.IsInContext = 1)
END

IF(@rType= 'ClasswiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster DM on DM.Id=CM.DepartmentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
	WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((CM.Id = @rOrgId)) AND BM.IsInContext = 1)
END
	RETURN  @StudentCount 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sStudent].[fMandatoryFieldGet](@rOrgGroupId int,@rStrMandatoryFeildId Nvarchar(Max))
RETURNS  @List TABLE (
		
		 IsDisplayFatherName bit,
		 IsDisplayReligion bit,
		 IsDisplayBloodGroup bit,
		 IsDisplayBirthPlace bit,
		 IsDisplayBirthTaluka bit,
		 IsDisplayBirthDistrict bit,
		 IsDisplayBirthState bit,
		 IsDisplayBirthCountry bit,
		 IsDisplayFamilyCaste bit,
		 IsDisplayFamilySubCaste bit,
		 IsDisplayCasteCategory bit,
		 IsDisplayHouse bit,
		 IsDisplayMotherTongue bit,
		 IsDisplayNationality bit,
		 IsDisplayReferenceRemark   bit,
		IsDisplayParentContactNo   bit,
		IsDisplayParentEmail   bit,
		IsDisplayStudentContactNo   bit,
		IsDisplayStudentEmail   bit,
		IsDisplayLocalAddress1   bit,
		IsDisplayLocalAddress2   bit,
		IsDisplayLocalAddress3   bit,
		IsDisplayLocalAddressCity   bit,
		IsDisplayLocalAddressState   bit,
		IsDisplayLocalAddressCountry   bit,
		IsDisplayLocalAddressPINCode   bit,
		IsDisplayLocalAddressContactNo   bit,
		OrgGroupId smallint 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	INSERT INTO @List 
	SELECT 
		   (CASE WHEN charindex('1001',@rStrMandatoryFeildId) = 0 THEN  0 ELSE 1 END) AS IsDisplayFatherName,
		   (CASE WHEN charindex('1002',@rStrMandatoryFeildId) = 0 THEN 0 ELSE 1 END)AS IsDisplayReligion,
		   (CASE WHEN charindex('1003',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBloodGroup,
		   (CASE WHEN charindex('1004',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthPlace,
		   (CASE WHEN charindex('1005',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthTaluka,
		   (CASE WHEN charindex('1006',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthDistrict,
		   (CASE WHEN charindex('1007',@rStrMandatoryFeildId) = 0 THEN 0 ELSE  1 END)AS IsDisplayBirthState,
		   (CASE WHEN charindex('1008',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayBirthCountry,
		   (CASE WHEN charindex('1009',@rStrMandatoryFeildId) = 0 THEN 0 ELSE  1 END)AS IsDisplayFamilyCaste,
		   (CASE WHEN charindex('1010',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayFamilySubCaste,
		   (CASE WHEN charindex('1011',@rStrMandatoryFeildId) = 0 THEN 0  ELSE 1 END)AS IsDisplayCasteCategory,
		   (CASE WHEN charindex('1012',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayHouse,
		   (CASE WHEN charindex('1013',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayMotherTongue,
		   (CASE WHEN charindex('1014',@rStrMandatoryFeildId) = 0  THEN 0  ELSE 1 END)AS IsDisplayNationality,
			(CASE  WHEN charindex('1015',@rStrMandatoryFeildId) = 0   THEN  0 ELSE 1 END ) AS  IsDisplayReferenceRemark,
			(CASE  WHEN charindex('1017',@rStrMandatoryFeildId) = 0  THEN  0 ELSE 1 END ) AS  IsDisplayParentContactNo,
			(CASE  WHEN charindex('1018',@rStrMandatoryFeildId)  = 0   THEN  0 ELSE 1 END ) AS  IsDisplayParentEmail,
			(CASE  WHEN charindex('1019',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayStudentContactNo,
			(CASE  WHEN charindex('1020',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayStudentEmail,
			(CASE  WHEN charindex('1021',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress1,
			(CASE  WHEN charindex('1022',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress2,
			(CASE  WHEN charindex('1023',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddress3,
			(CASE  WHEN charindex('1024',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressCity,
			(CASE  WHEN charindex('1025',@rStrMandatoryFeildId)= 0  THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressState,
			(CASE  WHEN charindex('1026',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressCountry,
			(CASE  WHEN charindex('1027',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressPINCode,
			(CASE  WHEN charindex('1028',@rStrMandatoryFeildId)= 0   THEN  0 ELSE 1 END ) AS  IsDisplayLocalAddressContactNo,
		    @rOrgGroupId AS OrgGroupId
		  
	 
    RETURN  
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sStudent].[fStudentAgeGet](@rDateofBirth [date],@rAsOnDate [date],@rOrgId [smallint])
RETURNS [nvarchar](20) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @rAgeDiff int

      DECLARE @rAgeGroupTitle Nvarchar(20)
      BEGIN
      SELECT @rAgeDiff =  DATEDIFF(YEAR,@rDateofBirth,@rAsOnDate)     
     
        --SELECT @rAgeGroupTitle  = Title FROM sCommon.tAgeGroupMaster
        --WHERE  (@rAgeDiff BETWEEN AgeFrom AND AgeTo) AND OrgId = @rOrgId   
        SELECT @rAgeGroupTitle = @rAgeDiff                
                                    
      END

     
      RETURN @rAgeGroupTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sStudent].[fStudentAgeGroupGet](@rDateofBirth [date],@rAsOnDate [date],@rOrgId [smallint])
RETURNS [nvarchar](20) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @rAgeDiff int

      DECLARE @rAgeGroupTitle Nvarchar(20)
      BEGIN
      SELECT @rAgeDiff =  DATEDIFF(YEAR,@rDateofBirth,@rAsOnDate)     
     
        SELECT @rAgeGroupTitle  = Title FROM sCommon.tAgeGroupMaster
        WHERE  (@rAgeDiff BETWEEN AgeFrom AND AgeTo) AND OrgId = @rOrgId   
                       
                                    
      END

     
      RETURN @rAgeGroupTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sStudent].[fStudentClassSubjectGet](@rOrgId int,@rClassId int)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rSubject nvarchar(2000)
 
	SELECT 
		@rSubject = COALESCE(@rSubject + ', ','') + S.Title
	FROM 
		[sSetup].[tSubjectMaster] S
		INNER JOIN [sSetup].[tClassSubject] CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId
	WHERE 
		(S.OrgId=@rOrgId)	  
 
    RETURN ISNULL(@rSubject,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sStudent].[fStudentContactsGet](@rStudentId bigint)
RETURNS NVARCHAR(max)
AS
BEGIN
DECLARE @lContactNos NVARCHAR(MAX) = ''
	SELECT @lContactNos = 
		(SUBSTRING((CASE WHEN ISNULL(SC.PresentContactNo,'') = '' THEN '' ELSE SC.PresentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.PermanentContactNo,'') = '' THEN '' ELSE SC.PermanentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.EmergencyContactNo,'') = '' THEN '' ELSE SC.EmergencyContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.ParentContactNo,'') = '' THEN '' ELSE SC.ParentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.StudentContactNo,'') = '' THEN '' ELSE SC.StudentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SFF.FatherContactNo,'') = '' THEN '' ELSE SFF.FatherContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SFF.MotherContactNo,'') = '' THEN '' ELSE SFF.MotherContactNo + ', ' END),0,
			LEN((CASE WHEN ISNULL(SC.PresentContactNo,'') = '' THEN '' ELSE SC.PresentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.PermanentContactNo,'') = '' THEN '' ELSE SC.PermanentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.EmergencyContactNo,'') = '' THEN '' ELSE SC.EmergencyContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.ParentContactNo,'') = '' THEN '' ELSE SC.ParentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SC.StudentContactNo,'') = '' THEN '' ELSE SC.StudentContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SFF.FatherContactNo,'') = '' THEN '' ELSE SFF.FatherContactNo + ', ' END) + 
			(CASE WHEN ISNULL(SFF.MotherContactNo,'') = '' THEN '' ELSE SFF.MotherContactNo + ', ' END))))

	FROM 
		sStudent.vStudentFull SF
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SF.StudentId	
		LEFT JOIN sStudent.tStudentFamily SFF ON SFF.StudentId = SF.StudentId

	WHERE SF.StudentId = @rStudentId

	RETURN ISNULL(@lContactNos,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER FUNCTION [sStudent].[fStudentCurrentDivisionGet](@rStudentId bigint)
RETURNS [nvarchar](100) WITH EXECUTE AS CALLER
AS 
BEGIN
      DECLARE @rCurrentDivision Nvarchar(100) = ''
      BEGIN
      SELECT @rCurrentDivision = (C.Title + ' ' + DM.Title)   FROM sStudent.tStudentMaster SM
      INNER JOIN sStudent.tAcademic A ON SM.Id = A.StudentId 
      INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
      INNER JOIN sSetup.tClassMaster C ON DM.ClassId = C.Id 
      INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id     
      WHERE StudentId = @rStudentId AND BM.IsHistory = 0                                    
      END     
      RETURN @rCurrentDivision
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sStudent].[fStudentDocumentAllBatchClasswiseget] (@rDocumentId int,@rAcademicId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lClassId int
 DECLARE @lStudentId bigint

 SELECT @lClassId = ClassId,@lStudentId = StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName  +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lClassId
			   Inner Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=2003 AND UserSourceId=@lStudentId AND ( UD.UploadFunctionalityId=11)
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName +'-OGB-'+cast(UD.OrgGroupBatchId as nvarchar) as DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			   Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=SDM.Id AND UserSourceTypeId=2003 AND UserSourceId=@lStudentId AND ( UD.UploadFunctionalityId=11)
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1  AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sStudent].[fStudentDocumentClasswiseget] (@rDocumentId int,@rAcademicId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lClassId int
 DECLARE @lStudentId bigint

 SELECT @lClassId = ClassId,@lStudentId = StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lClassId
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND DS.SubmitDocumentId is null  AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sStudent].[fStudentNameGet](@rFirstName nvarchar(100),@rMiddleName nvarchar(100),@rLastName nvarchar(100),@rStudentNameFormatId tinyint)
RETURNS [nvarchar](300) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rStudentName Nvarchar(300)
IF @rStudentNameFormatId = 1
SET @rStudentName =  @rFirstName + ' ' + @rLastName
ELSE IF @rStudentNameFormatId = 2
SET @rStudentName =  @rFirstName + ' ' + @rMiddleName + ' ' + @rLastName
ELSE IF @rStudentNameFormatId = 3
 SET @rStudentName = @rLastName + ' ' + @rFirstName
ELSE IF @rStudentNameFormatId = 4
SET @rStudentName = @rLastName + ' ' + @rFirstName + ' ' + @rMiddleName
ELSE IF @rStudentNameFormatId = 5
SET @rStudentName = @rFirstName
ELSE
SET @rStudentName =  @rFirstName + ' ' + @rLastName     

SET @rStudentName = RTRIM(LTRIM(REPLACE(@rStudentName,'  ', ' ')))

RETURN @rStudentName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sStudent].[fStudentOptionalSubjectList]( @AcademicId BIGINT )
RETURNS NVARCHAR (2000) WITH EXECUTE AS CALLER
AS
BEGIN

DECLARE @OptionalSubList NVARCHAR(2000)

SELECT 
 @OptionalSubList  = COALESCE(@OptionalSubList+',','') + SubM.Code

 FROM
 	
	sAssessment.tOptionalSubject OS 
	INNER JOIN sSetup.tClassSubject CS ON CS.Id =  OS.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id =  CS.SubjectId
	
	WHERE  OS.AcademicId =  @AcademicId

	RETURN ISNULL(@OptionalSubList,'') 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sStudent].[fStudentPendingDocumentGet] (
    @rStudentId BIGINT,
	@rClassId INT
)
RETURNS NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @lResult NVARCHAR(MAX) = ''

    SELECT @lResult = STUFF(
        (
            SELECT DISTINCT ', ' + DM.DocumentName
            FROM sCommon.tSubmitDocumentMaster DM
            INNER JOIN sCommon.tSubmitDocumentScope SDS ON DM.Id = SDS.SubmitDocumentId
            LEFT JOIN sStudent.tStudentDocument SD ON DM.Id = SD.SubmitDocumentMasterId 
                AND SD.StudentId = @rStudentId
            WHERE SD.StudentId IS NULL 
                AND DM.SubmitDocumentFunctionalityId = 1
				AND SDS.SourceTypeId = 2016 AND SDS.SourceId = @rClassId
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

    IF @lResult IS NULL OR @lResult = ''
        SET @lResult = 'Nothing' 

    RETURN @lResult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 



CREATE OR ALTER FUNCTION [sStudent].[fStudentShortNameGet](@rFirstName nvarchar(100),@rLastName nvarchar(100),@rStudentNameFormatId tinyint)
RETURNS [nvarchar](300) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rStudentName Nvarchar(300)
IF @rStudentNameFormatId = 1
SET @rStudentName =  @rFirstName + ' ' + @rLastName
ELSE IF @rStudentNameFormatId = 2
SET @rStudentName =  @rFirstName + ' ' + @rLastName
ELSE IF @rStudentNameFormatId = 3
 SET @rStudentName = @rLastName + ' ' + @rFirstName
ELSE IF @rStudentNameFormatId = 4
SET @rStudentName = @rLastName + ' ' + @rFirstName 
ELSE
SET @rStudentName =  @rFirstName + ' ' + @rLastName     
RETURN @rStudentName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sTally].[fGetStudentNameFormat]
(
    @formatType NVARCHAR(50), 
    @Divcode NVARCHAR(20),
    @firstName NVARCHAR(100),  
    @middleName NVARCHAR(100),
    @lastName NVARCHAR(100),  
    @orgId INT,
	@Stucode NVARCHAR(20)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @formattedName NVARCHAR(MAX);
    IF @formatType = 'Class Division Name OrgId ID'
        SET @formattedName = ISNULL(@Divcode, '') + ' ' +
                             ISNULL(@firstName, '') + ' ' +
                             ISNULL(@middleName, '') + ' ' +
                             ISNULL(@lastName, '') + '#' +
                             CONVERT(NVARCHAR(10), ISNULL(@orgId, 0)) + '#' +
							 ISNULL(@Stucode, '');
    ELSE IF @formatType = 'Name OrgId ID'
        SET @formattedName = ISNULL(@firstName, '') + ' ' +
                             ISNULL(@middleName, '') + ' ' +
                             ISNULL(@lastName, '') + '#' +
                             CONVERT(NVARCHAR(10), ISNULL(@orgId, 0)) + '#' +
							 ISNULL(@Stucode, '');
    ELSE IF @formatType = 'Name OrgId ID Class Division'
        SET @formattedName = ISNULL(@firstName, '') + ' ' +
                             ISNULL(@middleName, '') + ' ' +
                             ISNULL(@lastName, '') + '#' +
                             CONVERT(NVARCHAR(10), ISNULL(@orgId, 0)) + '#' +
                             ISNULL(@Stucode, '') + '#' +
							 ISNULL(@Divcode, '');

    RETURN @formattedName;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get the tax rate based on the date passed
	Created date     : 10 Jan 2010
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : IsHistory and TaxGroupId added in the condition
*******************************************************************************/
CREATE OR ALTER FUNCTION [sTax].[fExtTaxRateGet]
	(
		@rTaxGroupId Int,
		@rDate DateTime
	)
	
RETURNS Decimal(22,6)
AS
BEGIN
	DECLARE @lTaxRate Decimal(22,6)
	SELECT 
			@lTaxRate = TaxRate 
	FROM 
			sTax.tTaxRateSetup
	WHERE 
			EffectiveFromDateTime =	(SELECT 
											MAX(EffectiveFromDateTime) 
									 FROM 
											sTax.tTaxRateSetup 
									 WHERE 
										CAST(CONVERT(NVARCHAR(20), EffectiveFromDateTime, 101) AS DATETIME) 
												<= CAST(CONVERT(NVARCHAR(20), @rDate, 101) AS DATETIME) 
									 AND
										TaxGroupId = @rTaxGroupId AND IsObsolete = 0
										AND IsHistory = 0)
										
			AND TaxGroupId = @rTaxGroupId 
		
	RETURN @lTaxRate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sTimetable].[fBatchGet](@rTimeTableSchemaId int,@rDivisionId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	
      DECLARE @lOrgGroupBatchId INT
      DECLARE @lOrgId INT
      DECLARE @lBatchId INT
      
      SET @lOrgGroupBatchId=(SELECT OrgGroupBatchId FROM sTimetable.tTimeTableSchema WHERE Id=@rTimeTableSchemaId)
      SET @lOrgId=(SELECT OrgId FROM sSetup.tDivisionMaster WHERE Id=@rDivisionId)
      SET @lBatchId=(SELECT Id FROM sSetup.tBatchMaster WHERE OrgGroupBatchId=@lOrgGroupBatchId AND OrgId=@lOrgId)
      
      RETURN @lBatchId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sTimetable].[fNextBatchIdGet](@rBatchId int, @rOrgGroupBatchId int)
RETURNS int WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lBatchId int
	DECLARE @lOrgId int

	SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id = @rBatchId
	SELECT @lBatchId=Id FROM sSetup.tBatchMaster WHERE OrgId = @lOrgId AND OrgGroupBatchId=@rOrgGroupBatchId

	RETURN @lBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sTimetable].[fTimeTableDetailGet](@rTimeTableId int,@rIsDisplayCode bit=0)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rTimeTableDetail nvarchar(2000)
	SELECT 
		@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br>','') + 
		CASE 
			WHEN @rIsDisplayCode =1 
			THEN ISNULL(EM.ShortName,'') +'-'+ ISNULL(SM.Code,'') 
			ELSE ISNULL(EM.FirstName,'') +' '+ ISNULL(EM.LastName,'') +'-'+ ISNULL(SM.Title,'') 
		END
	FROM 
		sTimetable.tTimeTableDetail TTD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
		INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	WHERE 
		TTD.TimeTableId = @rTimeTableId AND  ISNULL(EM.IsOtherUser,0) = 0

	IF(@rTimeTableDetail IS NOT NULL)
		SET @rTimeTableDetail = ',<br>'+@rTimeTableDetail

RETURN ISNULL(@rTimeTableDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER FUNCTION [sTimetable].[fTimeTableDivisionGet](@rTimeTableSchemaId int,@rTimeTableId int,@rEmployeeId bigint,@rDayId tinyint,@rLectureNumber tinyint,@rIsDisplayCode bit=0)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rTimeTableDetail nvarchar(2000)
	SELECT 
		@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br>','') +
		CASE 
			WHEN @rIsDisplayCode =1 
			THEN VBCD.ClassDivisionName +'-'+ ISNULL(SM.Code,'') 
			ELSE VBCD.ClassName +' '+ VBCD.DivisionName +'-'+ ISNULL(SM.Title,'') 
		END
	FROM 
		sTimetable.tTimeTable T 
        INNER JOIN sTimetable.tTimeTableDetail TD ON T.Id = TD.TimeTableId 
        INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
        INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=TD.SubjectId
	WHERE 
		T.TimeTableSchemaId = @rTimeTableSchemaId AND TD.EmployeeId = @rEmployeeId 
		AND T.Id = @rTimeTableId
		AND T.DayId=@rDayId AND T.LectureNumber = @rLectureNumber

	IF(@rTimeTableDetail IS NOT NULL)
		SET @rTimeTableDetail = ',<br>'+@rTimeTableDetail

RETURN ISNULL(@rTimeTableDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sTimetable].[fTimeTableSubjectGet](@rTimeTableSchemaId int,@rSubjectId int,@rLectureNumber tinyint, @rDayId tinyint,@rIsTimeTableDetail bit)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @rTimeTableDetail nvarchar(2000)
	
	IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
	BEGIN
	IF(@rIsTimeTableDetail=0)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName +'|'+ ISNULL(TTM.FromTime,0) +'-'+ ISNULL(TTM.ToTime,0)
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = T.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = T.DayId AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND ISNULL(TTM.IsBreak,0)=0 and ISNULL(TTM.IsBreakBefore,0)=0
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND T.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	ELSE IF(@rIsTimeTableDetail=1)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName +'|'+ ISNULL(TTM.FromTime,0) +'-'+ ISNULL(TTM.ToTime,0)
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sTimetable.tTimeTableDetail TT ON  T.Id = TT.TimeTableId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TT.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = T.DayId AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND ISNULL(TTM.IsBreak,0)=0 and ISNULL(TTM.IsBreakBefore,0)=0
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND TT.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	END
ELSE
	BEGIN
	IF(@rIsTimeTableDetail=0)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName 
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = T.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND T.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	ELSE IF(@rIsTimeTableDetail=1)
	BEGIN
		SELECT 
			@rTimeTableDetail=COALESCE(@rTimeTableDetail+',<br> ','') + EM.ShortName + ' - ' + VBCD.ClassDivisionName
		FROM 
			sTimetable.tTimeTable T 
			INNER JOIN sTimetable.tTimeTableDetail TT ON  T.Id = TT.TimeTableId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TT.EmployeeId
			INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId
			INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
		WHERE 
			T.TimeTableSchemaId = @rTimeTableSchemaId
			AND TT.SubjectId =  @rSubjectId
			AND T.DayId=@rDayId 
			AND T.LectureNumber = @rLectureNumber
			AND  ISNULL(EM.IsOtherUser,0) = 0

		IF(@rTimeTableDetail IS NOT NULL)
			SET @rTimeTableDetail = ',<br> '+@rTimeTableDetail
	END
	
	END
	RETURN ISNULL(@rTimeTableDetail,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER FUNCTION [sTransport].[fAssignRouteCodeGet](@rTransportId int,@rBusRouteId int,@rOrgId smallint,@rOrgGroupBatchId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
declare @rSourceIdList nvarchar(max)=''

Select @rSourceIdList=@rSourceIdList + ISNULL(VA.Code,'') +','

FROM sTransport.tAssignRoute AR 
        INNER JOIN  sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId  AND AR.SourceTypeId=2003 AND VA.StatusId=1
        INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
          WHERE 
        BRM.TransportId=@rTransportId 
      	AND ((BRDM.Id=@rBusRouteId) OR (@rBusRouteId=0))
        AND VA.OrgGroupBatchId=@rOrgGroupBatchId
      AND ((VA.OrgId=@rOrgId) OR (@rOrgId=0))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        IF (RIGHT(@rSourceIdList, 1) = ',')
   set @rSourceIdList = LEFT(@rSourceIdList, LEN(@rSourceIdList) - 1)
   
      RETURN  isnull(@rSourceIdList,'')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCommon].[ExplodeDates](@startdate datetime, @enddate datetime) 
 returns table as 
 return ( 
 with  
 N0 as (SELECT 1 as n UNION ALL SELECT 1) 
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2) 
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2) 
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2) 
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2) 
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2) 
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2) 
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6) 
SELECT DATEADD(day,num-1,@startdate) as thedate 
FROM nums 
WHERE num <= DATEDIFF(day,@startdate,@enddate) + 1 
 );

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER FUNCTION [sCommon].[ExplodeNumber](@StartNumber int, @EndNumber BIGINT) 
 returns table as 
 return ( 
 with  
 N0 as (SELECT 1 as n UNION ALL SELECT 1) 
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2) 
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2) 
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2) 
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2) 
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2) 
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2) 
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6) 
SELECT num as Counter ,@StartNumber+ (num-1) As Number
FROM nums 
WHERE num <= ((@EndNumber-@StartNumber) + 1 )
 );

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fAgeAtDate](
    @DOB    datetime,
    @PassedDate datetime
)

returns int
with SCHEMABINDING
as
begin

declare @iMonthDayDob int
declare @iMonthDayPassedDate int


select @iMonthDayDob = CAST(datepart (mm,@DOB) * 100 + datepart  (dd,@DOB) AS int) 
select @iMonthDayPassedDate = CAST(datepart (mm,@PassedDate) * 100 + datepart  (dd,@PassedDate) AS int) 

return DateDiff(yy,@DOB, @PassedDate) 
- CASE WHEN @iMonthDayDob <= @iMonthDayPassedDate
  THEN 0 
  ELSE 1
  END

End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sCommon].[fGetDateOfBirthInWord](
    @DOB datetime
)
RETURNS nvarchar(50)
WITH SCHEMABINDING
AS
BEGIN

	DECLARE @years int, @months int, @DateOfBirthInWord nvarchar(50)

	SELECT @years = YEAR(GETDATE()) - YEAR(@DOB)
	SELECT @months = MONTH(GETDATE()) - MONTH(@DOB)
	SET @months = (@years * 12) + @months
	SET @years = (@months / 12)
	SET @months = (@months % 12)
	SELECT @DateOfBirthInWord = CONVERT(nvarchar(10), @years) + ' Years ' + CONVERT(nvarchar(10), @months) + ' Months'

	RETURN @DateOfBirthInWord
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER FUNCTION [sFinanceCommon].[fDefaultCurrencyValueGet]
(
    @rOrgGroupId INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT 
        CurrencyTitle = ISNULL(
            (SELECT TOP 1 ISNULL(CS.ItemValue, CM.ItemValue)
             FROM sConfig.tConfigurationMaster CM
             LEFT JOIN sConfig.tConfigurationSetup CS
                 ON CM.Id = CS.ConfigurationId
                 AND CS.SourceTypeId = 2010
                 AND CS.SourceId = @rOrgGroupId
             WHERE CM.Id = 153), 'Rupees'),
        CurrencyCode = ISNULL(
            (SELECT TOP 1 ISNULL(CS.ItemValue, CM.ItemValue)
             FROM sConfig.tConfigurationMaster CM
             LEFT JOIN sConfig.tConfigurationSetup CS
                 ON CM.Id = CS.ConfigurationId
                 AND CS.SourceTypeId = 2010
                 AND CS.SourceId = @rOrgGroupId
             WHERE CM.Id = 154), 'Rs.')
)

GO
