

INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('23.11.30',231130,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO

CREATE SCHEMA [sChatbot];
    --AUTHORIZATION [DEVuser];

GO

ALTER TABLE [sAlert].[tCustomTemplateMaster]
    ADD [WhatsAppTemplate]  NVARCHAR (MAX) NULL,
        [MobileAppTemplate] NVARCHAR (MAX) NULL;

GO
ALTER TABLE [sCertificate].[tLeaving]
    ADD [LCCopyRemark] NVARCHAR (MAX) NULL;

GO
ALTER TABLE [sCommunication].[tCircularConsent] ALTER COLUMN [AnsFieldList] NVARCHAR (MAX) NULL;

GO
ALTER TABLE [sCommunication].[tDailyThoughtAssign] ALTER COLUMN [DailyThoughtId] NVARCHAR (1000) NOT NULL;


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [HesabeAccessCode]        NVARCHAR (50) NULL,
        [HesabeMerchantKey]       NVARCHAR (50) NULL,
        [HesabeMerchantIV]        NVARCHAR (50) NULL,
        [HesabeMerchantCode]      NVARCHAR (50) NULL,
        [HesabeVersion]           NVARCHAR (10) CONSTRAINT [DF_tGatewayProduct_HesabeVersion] DEFAULT ((2.0)) NULL,
        [HesabeIsLiveEnvironment] BIT           NULL;


GO
ALTER TABLE [sPayroll].[tProfessionalTaxRange]
    ADD [GenderId] TINYINT CONSTRAINT [DF_tProfessionalTaxRange_GenderId] DEFAULT ((0)) NOT NULL;


GO
CREATE TABLE [sChatbot].[tChatbotAuditLog] (
    [ChannelId]       BIGINT         IDENTITY (1, 1) NOT NULL,
    [UserId]          BIGINT         NOT NULL,
    [Feedback]        BIT            NULL,
    [Description]     NVARCHAR (MAX) NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedDateTime] DATETIME       NULL,
    CONSTRAINT [PK_tChatbotAuditLog] PRIMARY KEY CLUSTERED ([ChannelId] ASC)
);

GO
CREATE TABLE [sChatbot].[tChatbotAuditLogDetail] (
    [ChatId]          BIGINT         IDENTITY (1, 1) NOT NULL,
    [ChannelId]       BIGINT         NOT NULL,
    [Question]        NVARCHAR (MAX) NOT NULL,
    [Answer]          NVARCHAR (MAX) NOT NULL,
    [Feedback]        BIT            NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedDateTime] DATETIME       NULL,
    CONSTRAINT [PK_tChatbotAuditLogDetail] PRIMARY KEY CLUSTERED ([ChatId] ASC)
);

GO

PRINT N'Refreshing View [sCertificate].[vPrintTemplateLeavingCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateLeavingCertificate]';


GO
PRINT N'Refreshing View [sCertificate].[vPrintTemplateTransferCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[vPrintTemplateTransferCertificate]';


GO
PRINT N'Altering Function [sAttendance].[fWeekHOffGet]...';


GO
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
PRINT N'Altering Function [sHrm].[fAttendanceJoiningDateGet]...';


GO

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
PRINT N'Altering Function [sHrm].[fAttendanceWithApproveLeaveGet]...';


GO

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
PRINT N'Altering Function [sHrm].[fAttendanceWithLeaveGet]...';


GO
 
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
PRINT N'Altering Function [sHrm].[fEmployeeWiseAttendanceJoiningDateGet]...';


GO

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
	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
PRINT N'Altering Function [sHrm].[fWeekHOffGet]...';


GO
 
 
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
PRINT N'Altering Function [sHrm].[fWeekHOffGetBio]...';


GO
 
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
PRINT N'Creating Function [sHrm].[fEmployeeContactsGet]...';


GO
CREATE 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
PRINT N'Altering Procedure [sAlert].[pCustomTemplateMasterAdd]...';


GO
ALTER PROCEDURE [sAlert].[pCustomTemplateMasterAdd]

	@rId int,
	@rOrgId smallint,
	@rTitle nvarchar(100),
	@rMailSubject nvarchar(100),
	@rMailTemplate nvarchar(max),
	@rSMSTemplate nvarchar(max),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rSMSTemplateID nvarchar(100),
	@rWhatsAppTemplate nvarchar(max)='',
	@rMobileAppTemplate nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
	--	If Exists(select Id from sAlert.tCustomTemplateMaster where Title=@rTitle AND OrgId=@rOrgId )
	--		BEGIN
	--		select -100 as Result
	--		RETURN
	--	END 
	--END
	
	BEGIN TRANSACTION	
	
	--IF(@rId = 0)	
	
	If NOT Exists(select Id from sAlert.tCustomTemplateMaster where Title=@rTitle AND OrgId=@rOrgId )
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tCustomTemplateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAlert.tCustomTemplateMaster
		(
			Id,
			OrgId,
			Title,
			MailSubject,
			MailTemplate,
			SMSTemplate,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			SMSTemplateID,
			WhatsAppTemplate,
			MobileAppTemplate
		)
	VALUES
		(
			@lNextNumber,
			@rOrgId,
			@rTitle,
			@rMailSubject,
			@rMailTemplate,
			@rSMSTemplate,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSMSTemplateID,
			@rWhatsAppTemplate,
			@rMobileAppTemplate
		)
	END	 
	--ELSE IF(@rIsAllOrg=1)
	--BEGIN
	--SET @lNextNumber = @rId
	--UPDATE  sAlert.tCustomTemplateMaster
	--    SET
	--		MailSubject=@rMailSubject,
	--		MailTemplate=@rMailTemplate,
	--		SMSTemplate=@rSMSTemplate,
	--		IsObsolete=@rIsObsolete,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()
			
	--      WHERE Title=@rTitle 
	--		AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
	-- END  
	ELSE
	BEGIN
	SET @lNextNumber = 1
	UPDATE  sAlert.tCustomTemplateMaster
	    SET
			Title=@rTitle,
			MailSubject=@rMailSubject,
			MailTemplate=@rMailTemplate,
			SMSTemplate=@rSMSTemplate,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			SMSTemplateID=@rSMSTemplateID,
			WhatsAppTemplate = @rWhatsAppTemplate,
			MobileAppTemplate = @rMobileAppTemplate
			
	      WHERE Title=@rTitle AND OrgId=@rOrgId  
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END
GO
PRINT N'Altering Procedure [sAlert].[pCustomTemplateMasterGet]...';


GO

ALTER PROCEDURE [sAlert].[pCustomTemplateMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rMailSubject nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	IF(@rIsSearch=1)
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rMailSubject = sCommon.fSearchStringGet(@rMailSubject)
		END
	
	SELECT 
	
			CTM.Id,
			CTM.Title,
			CTM.MailSubject,
			CTM.MailTemplate,
			CTM.SMSTemplate,
			CTM.IsObsolete,
			CTM.OrgId,
			OM.DisplayTitle AS Organization,
			CTM.SMSTemplateID,
			ISNULL(CTM.WhatsAppTemplate,'')AS WhatsAppTemplate,
			ISNULL(CTM.MobileAppTemplate,'')AS MobileAppTemplate
			
    FROM 
            sAlert.tCustomTemplateMaster CTM
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CTM.OrgId
             
    WHERE 
	  
			((CTM.Id = @rId) OR (@rId = 0))
		AND ((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND ((CTM.MailSubject like @rMailSubject) OR (ISNULL(@rMailSubject,'') = '')) 
		AND ((CTM.OrgId=@rOrgId) OR (@rOrgId=0))

		ORDER BY CTM.Title ASC
  
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptLeavingCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rUserName nvarchar(100)=''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId


SELECT @lOrgId=RG.OrgId,
@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=3 WHERE RGM.Id=3
 
--WHERE  RG.OrgId=@rOrgId AND RG.ReportRemarkGroupId=3

--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3
--END


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end 
		,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark    --add for 28079 mantis end 
		                                    
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingAdd]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rLCNumber int
       ,@rLCDate date
       ,@rLeftDate date
       ,@rLCCopy tinyint
       ,@rLCRemark nvarchar(200)
       ,@rLCProgress nvarchar(200)
       ,@rLCConduct nvarchar(200)
       ,@rLCReason nvarchar(200)
       ,@rLCBookNumber nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rToCollege nvarchar(200)
	   ,@rToCollegeAddress nvarchar(200)
	   ,@rLastExamName nvarchar(200)
	   ,@rLastExamResult nvarchar(200)
	   ,@rRepeatDetail nvarchar(100)
	   ,@rSubjectStudied nvarchar(300)
	   ,@rPromoteToClass nvarchar(50)
	   ,@rFeeDetail nvarchar(100)
	   ,@rFeeConcessionDetail nvarchar(100)
	   ,@rExtraCurricularActivities nvarchar(200)
	   ,@rNCCScoutDetail nvarchar(100)
	   ,@rTermsInInstitute nvarchar(500)
	   ,@rBatchId int
	   ,@rIsNumberBatchWise bit = 0
	   ,@rTotalDays int=0
	   ,@rPresentDays int=0
	   ,@rProofOfDOB nvarchar(200)
	   ,@rLCCopyRemark nvarchar(max)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
	 
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 ELSE
 	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId)-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF (@lAdmissionDate > @rLCDate)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
	
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
		           ,BatchId
				   ,TotalDays
				   ,PresentDays
				   ,ProofOfDOB
				   ,LCCopyRemark
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
		           ,@rBatchId
				   ,@rTotalDays 
			       ,@rPresentDays 
				   ,@rProofOfDOB
				   ,@rLCCopyRemark
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 select 111
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				    ,BatchId = @rBatchId
					,TotalDays = @rTotalDays 
			        ,PresentDays = @rPresentDays 
					,ProofOfDOB = @rProofOfDOB
					,LCCopyRemark = @rLCCopyRemark
				WHERE Id = @rId
				
		 
		END 
		
		
				UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		 
		  --Update Batch Status 
			UPDATE A
			SET BatchStatusId = 3 
			FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
			WHERE SM.StatusId = 3 AND SM.Id = @lStudentId
		 --Ends

		   --Update Class Status 
			UPDATE A
			SET ClassStatusId = 3 ,
			 UpdatedUserId = @rCreatedUserId, 
		     UpdatedDateTime =sCommon.fGetDate()
			FROM sStudent.tAcademic A
			WHERE A.Id = @rAcademicId
		 --Ends
		 
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingGet]...';


GO
 
ALTER PROCEDURE [sCertificate].[pLeavingGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
			
		END
	
	SELECT 
	
			L.Id,
			L.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			L.LCNumber,
			L.LCDate,
			L.LeftDate,
			L.LCCopy,
			L.LCRemark,
			L.LCProgress,
			L.LCConduct,
			L.LCReason,
			L.LCBookNumber,
			L.ToCollege,
			L.ToCollegeAddress
			,L.LastExamName 
		    ,L.LastExamResult 
		    ,L.RepeatDetail 
		    ,L.SubjectStudied
		    ,L.PromoteToClass 
		    ,L.FeeDetail 
		    ,L.FeeConcessionDetail
		    ,L.ExtraCurricularActivities
		    ,L.NCCScoutDetail 
		    ,L.TermsInInstitute
			,ISNULL(L.TotalDays,0)AS TotalDays
			,ISNULL(L.PresentDays,0) AS PresentDays
			,StuA.ProofOfDOB
			,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark
		
  FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
			
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
		
			ORDER BY L.LCNumber
END
GO
PRINT N'Altering Procedure [sCommunication].[pDailyThoughtAssignAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pDailyThoughtAssignAdd]
	 @rOrgId int,
	 @rMonth smallint,
	 @rXml nvarchar(MAX),
	 @rSourceId bigint = 0,
	 @rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rXml AS XML)  
   
	DECLARE @tDailyThoughtAssign TABLE  
	(  
		Id INT IDENTITY(1, 1),  
		Day SMALLINT,
		DailyThoughtId nvarchar(1000),  
		IsSelect  SMALLINT
	)   
    INSERT INTO @tDailyThoughtAssign  
    SELECT           
            T.c.value('@Day','smallint') AS Day,  
            T.c.value('@DailyThoughtId','nvarchar(1000)') AS DailyThoughtId,  
            T.c.value('@IsSelect','smallint') AS IsSelect             
    FROM   
            @StrXML.nodes('/Table/DailyThought')T(c)  

	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM @tDailyThoughtAssign))                
	BEGIN
		DECLARE @lIsSelect SmallInt,@lDay SmallInt
		DECLARE @lDailyThoughtId nvarchar(1000)

		SELECT @lIsSelect = IsSelect , @lDailyThoughtId = DailyThoughtId,@lDay = Day FROM @tDailyThoughtAssign WHERE Id = @lCount

		IF(@lIsSelect = 1)
		BEGIN
			--IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE DailyThoughtId = @lDailyThoughtId AND Month = @rMonth AND OrgId = @rOrgId AND Day <> @lDay)
			--BEGIN
			--	SELECT -101 AS Result

			--	COMMIT TRANSACTION
			--	RETURN
			--END
			IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](@lDailyThoughtId, ',')))
			BEGIN
				SELECT -102 AS Result

				COMMIT TRANSACTION
				RETURN
			END
			
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				UPDATE sCommunication.tDailyThoughtAssign
				SET
				DailyThoughtId = @lDailyThoughtId
				WHERE
				Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
			ELSE IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				INSERT INTO sCommunication.tDailyThoughtAssign
				(
					DailyThoughtId,
					Day,
					Month,
					OrgId,
					SourceId,
					SourceTypeId	
				)
				VALUES
				(
					@lDailyThoughtId,
					@lDay,
					@rMonth,
					@rOrgId,
					@rSourceId,
					@rSourceTypeId
				)
			END
		END
		ELSE
		BEGIN
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE  Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				DELETE FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
		END
		SET @lCount = @lCount + 1
	END
		SELECT 1 AS RESULT
	COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() as result
	END CATCH
END
GO
PRINT N'Altering Procedure [sOp].[pGatewayProductAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
        @rId int,
	    @rGatewayConfigurationId int,
		@rTitle nvarchar(150),
		@rGatewayURL nvarchar(1000),
		@rServerPort nvarchar(50),
		@rLoginId nvarchar(50),
		@rLoginPassword nvarchar(50),
		@rProductId nvarchar(100),
		@rOrgGroupId int,
		@rCCAvenueMerchantID nvarchar(50)='',
		@rCCAvenueAccessCode nvarchar(100)='',
		@rCCAvenueWorkingKey nvarchar(100)='',
		@rCCAvenueWhitelistURL nvarchar(500)='',
		@rCCAvenueSubAccountId nvarchar(100)='',
		
		@rAtomReqHashKey nvarchar(100)='',
		@rAtomRespHashKey nvarchar(100)='',
		@rPaytmMID nvarchar(50)='',
		@rPaytmMerchantKey nvarchar(50)='',
		@rPaytmChannelId nvarchar(20)='',
		@rPaytmIndustryTypeId nvarchar(20)='',
		@rPaytmWebsite nvarchar(20)='',
		@rPaytmStatusCheckURL nvarchar(500)='',
		@rPayUMoneyMERCHANTID nvarchar(20)='',
		@rPayUMoneyMERCHANTKEY nvarchar(20)='',
		@rPayUMoneySALT nvarchar(20)='',
		@rPayUMoneyHASHSEQUENCE nvarchar(200)='',
		@rPayUMoneyAUTHHEADER nvarchar(50)='',
		@rBillDeskMerchantID nvarchar(50)='',
		@rBillDeskChecksumKey nvarchar(50)='',
		@rBillDeskSecurityID nvarchar(50)='',
		@rBillDeskUniqueIdentifier nvarchar(50)='',
		@rEazypayMerchantId nvarchar(50)='',
		@rEazypayAESKey nvarchar(50)='',
		@rAxisMerchantId nvarchar(50)='',
		@rAxisAPIKey nvarchar(50)='',
		@rAxisResponseKey nvarchar(50)='',
		@rRazorpayMID nvarchar(50)='',
		@rRazorpayKeyID nvarchar(50)='',
		@rRazorpaySecretKey nvarchar(50)='',
		@rBBPSCharge nvarchar(500) = '',
		@rBBPSGST decimal(12,2) = 0,
		@rGrayQuestClientId nvarchar(50)='',
		@rGrayQuestSecretKey nvarchar(50)='',
		@rGrayQuestApiKey nvarchar(50)='',

		@rEasebuzzKey nvarchar(50)='',
		@rEasebuzzSalt nvarchar(50)='',
		@rEasebuzzIsLiveEnvironment bit = null,
		@rEasebuzzIsEnableiFrame bit = null,
		@rEasebuzzSubMerchantId nvarchar(50)='',

		@rHesabeAccessCode nvarchar(50)='',
		@rHesabeMerchantCode nvarchar(50)='',
		@rHesabeMerchantKey nvarchar(50) = '',
		@rHesabeMerchantIV nvarchar(50)='',
		@rHesabeVersion nvarchar(10) = '2.0',
		@rHesabeIsLiveEnvironment bit = null
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE],
			[PayUMoneyAUTHHEADER],
			[BillDeskMerchantID],
			[BillDeskChecksumKey],
			[BillDeskSecurityID],
			[BillDeskUniqueIdentifier],
			[EazypayMerchantId],
			[EazypayAESKey],
			[AxisMerchantId],
			[AxisAPIKey],
			[AxisResponseKey],
			[RazorpayMID],
			[RazorpayKeyID],
			[RazorpaySecretKey],
			[BBPSCharges],
			[BBPSGST],
			GrayQuestClientId,
			GrayQuestSecretKey,
			GrayQuestAPIKey,
			[EasebuzzKey],
			[EasebuzzSalt],
			[EasebuzzIsLiveEnvironment],
			[EasebuzzIsEnableiFrame],
			[EasebuzzSubMerchantId],
			HesabeAccessCode,
			HesabeMerchantKey,
			HesabeMerchantIV,
			HesabeMerchantCode,
			HesabeVersion,
			HesabeIsLiveEnvironment
		)
		VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE,
			@rPayUMoneyAUTHHEADER,
			@rBillDeskMerchantID,
			@rBillDeskChecksumKey,
			@rBillDeskSecurityID,
			@rBillDeskUniqueIdentifier,
			@rEazypayMerchantId,
			@rEazypayAESKey,
			@rAxisMerchantId,
			@rAxisAPIKey,
			@rAxisResponseKey,
			@rRazorpayMID,
			@rRazorpayKeyID,
			@rRazorpaySecretKey,
			@rBBPSCharge,
			@rBBPSGST,
			@rGrayQuestClientId,
			@rGrayQuestSecretKey,
			@rGrayQuestApiKey,
			@rEasebuzzKey,
			@rEasebuzzSalt,
			@rEasebuzzIsLiveEnvironment,
			@rEasebuzzIsEnableiFrame,
			@rEasebuzzSubMerchantId,
			@rHesabeAccessCode,
			@rHesabeMerchantKey,
			@rHesabeMerchantIV,
			@rHesabeMerchantCode,
			@rHesabeVersion,
			@rHesabeIsLiveEnvironment
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE,
			[PayUMoneyAUTHHEADER]=@rPayUMoneyAUTHHEADER,
			[BillDeskMerchantID]=@rBillDeskMerchantID,
			[BillDeskChecksumKey]=@rBillDeskChecksumKey,
			[BillDeskSecurityID]=@rBillDeskSecurityID,
			[BillDeskUniqueIdentifier]=@rBillDeskUniqueIdentifier,
			[EazypayMerchantId]=@rEazypayMerchantId,
			[EazypayAESKey]=@rEazypayAESKey,
			[AxisMerchantId]=@rAxisMerchantId,
			[AxisAPIKey]=@rAxisAPIKey,
			[AxisResponseKey]=@rAxisResponseKey,
			[RazorpayMID]=@rRazorpayMID,
			[RazorpayKeyID]=@rRazorpayKeyID,
			[RazorpaySecretKey]=@rRazorpaySecretKey,
			[BBPSCharges] = @rBBPSCharge,
			[BBPSGST] = @rBBPSGST,
			GrayQuestClientId = @rGrayQuestClientId,
			GrayQuestSecretKey = @rGrayQuestSecretKey,
			GrayQuestAPIKey = @rGrayQuestApiKey,
			[EasebuzzKey] = @rEasebuzzKey,
			[EasebuzzSalt] = @rEasebuzzSalt,
			[EasebuzzIsLiveEnvironment] = @rEasebuzzIsLiveEnvironment,
			[EasebuzzIsEnableiFrame] = @rEasebuzzIsEnableiFrame,
			[EasebuzzSubMerchantId] = @rEasebuzzSubMerchantId,
			HesabeAccessCode = @rHesabeAccessCode,
			HesabeMerchantKey = @rHesabeMerchantKey,
			HesabeMerchantIV = @rHesabeMerchantIV,
			HesabeMerchantCode = @rHesabeMerchantCode,
			HesabeVersion = @rHesabeVersion,
			HesabeIsLiveEnvironment = @rHesabeIsLiveEnvironment
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sOp].[pGatewayProductGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE,
			ISNULL(GP.PayUMoneyAUTHHEADER,'') AS PayUMoneyAUTHHEADER,
			
			ISNULL(GP.BillDeskMerchantID,'') AS BillDeskMerchantID,
			ISNULL(GP.BillDeskChecksumKey,'') AS BillDeskChecksumKey,
			ISNULL(GP.BillDeskSecurityID,'') AS BillDeskSecurityID,
			ISNULL(GP.BillDeskUniqueIdentifier,'') AS BillDeskUniqueIdentifier,
			ISNULL(GP.EazypayMerchantId,'') AS EazypayMerchantId,
			ISNULL(GP.EazypayAESKey,'') AS EazypayAESKey,

			ISNULL(GP.AxisMerchantId,'') AS AxisMerchantId,
			ISNULL(GP.AxisAPIKey,'') AS AxisAPIKey,
			ISNULL(GP.AxisResponseKey,'') AS AxisResponseKey,

			ISNULL(GP.RazorpayMID,'') AS RazorpayMID,
			ISNULL(GP.RazorpayKeyID,'') AS RazorpayKeyID,
			ISNULL(GP.RazorpaySecretKey,'') AS RazorpaySecretKey,

			ISNULL(GP.BBPSCharges,'') AS BBPSCharges,
			ISNULL(GP.BBPSGST,0) AS BBPSGST,

			ISNULL(GP.GrayQuestClientId,'') AS GrayQuestClientId,
			ISNULL(GP.GrayQuestSecretKey,'') AS GrayQuestSecretKey,
			ISNULL(GP.GrayQuestApiKey,'') AS GrayQuestApiKey,

			ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,
			ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt,
			ISNULL(GP.EasebuzzIsLiveEnvironment, 0) AS EasebuzzIsLiveEnvironment,
			ISNULL(GP.EasebuzzIsEnableiFrame, 0) AS EasebuzzIsEnableiFrame,
			ISNULL(GP.EasebuzzSubMerchantId,'') AS EasebuzzSubMerchantId,

			ISNULL(GP.HesabeAccessCode,'') AS HesabeAccessCode,
			ISNULL(GP.HesabeMerchantKey,'') AS HesabeMerchantKey,
			ISNULL(GP.HesabeMerchantIV, '') AS HesabeMerchantIV,
			ISNULL(GP.HesabeMerchantCode, '') AS HesabeMerchantCode,
			ISNULL(GP.HesabeVersion, '2.0') AS HesabeVersion,
			ISNULL(GP.HesabeIsLiveEnvironment,0) AS HesabeIsLiveEnvironment
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END
GO
PRINT N'Altering Procedure [sPayroll].[pCalculateStaticPayElement]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculateStaticPayElement] 
	      
	        @rPayProcessEmployeeId bigint,
	        @rOrgGroupId int,
	        @rSalary DECIMAL(22,6),
	        @rSourceId bigint,
	        @rDeductionAmount DECIMAL(22,6),
	        @rPayrollId int,
	        @rPayrollYearId int,
			@lPayrollGroupId int =0,
			@rSalaryMonth tinyint = 0,
			@rSalaryYear smallint = 0,
			@rEmployeeId bigint = 0
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	DECLARE @lProfessionalTaxAgeRestriction int
	
	SELECT @lProfessionalTaxAgeRestriction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 406 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	

	IF (@lProfessionalTaxAgeRestriction IS NULL) OR (LEN(@lProfessionalTaxAgeRestriction) = 0)
		SET @lProfessionalTaxAgeRestriction = 65
	
	BEGIN
	
	DECLARE @lNextNumber BIGINT 
	DECLARE @1Basic DECIMAl(22,6) 
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6) 
    DECLARE @1Tax DECIMAL(22,6)
    --DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)
    
    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployerFpsPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)
    DECLARE @1EmployeePfAmount DECIMAL(22,2)
    DECLARE @1EmployerPfAmount DECIMAL(22,2)
    DECLARE @1AdminChargesPercent DECIMAL(22,2)
    DECLARE @1EdliPercent DECIMAL(22,3)
    DECLARE @1InspectionChargesPercent DECIMAL(22,3)
    
    
    DECLARE @lEmployerFpsPercent DECIMAL(22,2)
    DECLARE @lValuesforMax DECIMAL(22,2) 
    DECLARE @1Max DECIMAL(22,2)
    DECLARE @lRestrictionEmployerFpsPercent DECIMAL(22,2)
    DECLARE @1Bal DECIMAL(22,2)
    DECLARE @lEmployerPfPercent DECIMAL(22,2)

	SET @1Tax = 0.0
	SET @1EmployeePfAmount = 0.0
	SET @1EmployeeESIAmount = 0.0
	SET @1Basic = 0.0
	SET @1PfSalaryLimit = 0.0
	
	SET @1EmployeePfPercent = 0.0
    SET @1EmployerPfPercent = 0.0
    SET @1EmployerFpsPercent = 0.0
    SET @1AdminChargesPercent = 0.0
    SET @1EdliPercent = 0.0
    SET @1InspectionChargesPercent = 0.0
    
     
    SET @lEmployerFpsPercent = 0.0
    SET @lValuesforMax = 0.0
    SET @1Max = 0.0
    SET @lRestrictionEmployerFpsPercent = 0.0
    SET @1Bal = 0.0
    SET @lEmployerPfPercent = 0.0
       
    SET @1EmployeeESIPercent = 0.0
    SET @1EmployerESIPercent = 0.0
    DECLARE @lPTPayElementId int    
    DECLARE @lPFPayElementId int
    DECLARE @lBasicPayElementId int
    DECLARE @lESIPayElementId int
    DECLARE @1EmployeePfPercentEmpSetup DECIMAL(12,2)
	
	SELECT @lPTPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	SELECT @lPFPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 56
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lESIPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 55


	 --For Professional Tax
	 IF EXISTS (SELECT 1 FROM  sPayroll.tPayProcessElement  
				   Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId)     	    
		BEGIN

		DECLARE @lDOB date 
		DECLARE @lMonthBeginDate date
		DECLARE @lMonthEndDate date
		DECLARE @lAge smallint
		DECLARE @lGenderId tinyint --mantis :27611


		SELECT @lDOB = DateOfBirth,@lGenderId=GenderId FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @rEmployeeId	--mantis :27611	
		SET @lMonthBeginDate= CAST(CAST(@rSalaryYear AS varchar) + '-' + CAST(@rSalaryMonth AS varchar) + '-' + '1' AS date)		
		SET @lMonthEndDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lMonthBeginDate)+1,0))
		SET @lAge = [sCommon].[fAgeAtDate] (@lDOB,@lMonthEndDate)
		
		IF(@lAge <= @lProfessionalTaxAgeRestriction OR @lDOB is null)
		BEGIN
		DECLARE @lGrossBasic decimal(22,6)=0
		  --      Select * from sPayroll.tProfessionalTaxRange
		        
		  --      SELECT  TOP 1  Tax  FROM sPayroll.tProfessionalTaxRange 
				--where Salary < @rSalary Order By Salary Desc


      DECLARE @lConfigValueForPTCalculation nvarchar(50)=''
	  SELECT @lConfigValueForPTCalculation = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 378 AND SourceId = @rOrgGroupId

	  IF(@lConfigValueForPTCalculation  IS NOT NULL AND  @lConfigValueForPTCalculation!='')
	  BEGIN
		IF(@lConfigValueForPTCalculation ='TotalEarning')
		  BEGIN
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        
		        IF @1Tax <> 0
		        BEGIN 
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END	
		  ELSE IF(@lConfigValueForPTCalculation ='GrossBasic')   
		  BEGIN  
		  
			  SELECT @lGrossBasic = ISNULL(SUM(GrossBasic),0) FROM sPayroll.tPayProcessEmployee WHERE ID =  @rPayProcessEmployeeId

			  SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
			  where Salary <= @lGrossBasic AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        
		        IF @1Tax <> 0
		        BEGIN 
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END
	  END
	  ELSE
	  BEGIN
	      
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        
		        IF @1Tax <> 0
		        BEGIN 
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
	  END

	  

		END
END	
		--print 'Professional Tax Done'
	
	 --For PfElement
	 
	  IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId)
	  BEGIN
	  
	  -- start for age calculation
	  DECLARE @lEmployeeId bigint = 0
	  DECLARE @lPayProcessId int = 0
	  DECLARE @lSalaryMonth tinyint = 0
	  DECLARE @lSalaryYear smallint = 0  
	  DECLARE @lEmployeeAge smallint = 0  
	  DECLARE @lDateOfBirth date	
	  DECLARE @lFirstDateOfMonth date
	  DECLARE @lLastDateOfMonth date
	  
	  SELECT @lEmployeeId = EmployeeId,@lPayProcessId = PayProcessId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId
	  SELECT @lDateOfBirth = DateOfBirth FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @lEmployeeId
	  SELECT @lSalaryMonth = SalaryMonth,@lSalaryYear = SalaryYear  FROM sPayroll.tPayProcess WHERE Id = @lPayProcessId
	 
      SET @lFirstDateOfMonth= CAST(CAST(@lSalaryYear AS varchar) + '-' + CAST(@lSalaryMonth AS varchar) + '-' + '1' AS date)
      SET @lLastDateOfMonth=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDateOfMonth)+1,0))
      SET @lEmployeeAge = [sCommon].[fAgeAtDate] (@lDateOfBirth,@lLastDateOfMonth)
      
      -- end for age calculation
      

	  
			  SET @1Basic = 0.0	          
	          SET @1PayProcesdsElementId = 0.0
	      
	   --   SELECT @1Basic = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lBasicPayElementId	      
		  --SELECT @1Basic =  Amount FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND PayElementId = @lBasicPayElementId  --Basic Pay Element
		  
		  SELECT @1Basic = ISNULL(SUM(amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement PE 
		  ON PPE.PayElementId = PE.ID  WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId IN 
		  (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS 
		  ON  PD.PaySetupId = PS.ID
		  INNER JOIN sPayroll.tPayElement PE 
		  ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId
		  AND PE.PayElementDefaultId = 56 AND SourceID = @lPayrollGroupId)	     
		  
	     
	      -- For PF Process(sPayroll.tPfProcess) 
	      
	      SELECT 
			  @1PfSalaryLimit = PfSalaryLimit,
			  @1EmployeePfPercent=EmployeePfPercent,
			  @1EmployerPfPercent=EmployerPfPercent, 
			  @1EmployerFpsPercent=EmployerFpsPercent,
			  @1AdminChargesPercent=AdminChargesPercent,
			  @1EdliPercent=EdliPercent,
			  @1InspectionChargesPercent=InspectionChargesPercent
	      FROM  
			  sPayroll.tPfSetup Where PayrollYearId = @rPayrollYearId 
	      
	      
	      SELECT @1EmployeePfPercentEmpSetup = Percentage  FROM sPayroll.tPaySetup WHERE SourceTypeId = 95 AND SourceId = (SELECT EmployeeId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId)
				AND PayElementId = @lPFPayElementId AND PayrollYearId = @rPayrollYearId
	   
	   IF @1EmployeePfPercentEmpSetup IS NOT NULL
	   SET @1EmployeePfPercent = @1EmployeePfPercentEmpSetup
	  
	      
	   SELECT @1PayProcesdsElementId = Id  FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId
	       
	       --SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
	       
	       
	        IF(@lEmployeeAge >= 58)
			BEGIN
				SET @lEmployerFpsPercent =  0
			END
			ELSE
			BEGIN
				SET @lEmployerFpsPercent =  ROUND(@1Basic*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
			END
	      
	       SET @lValuesforMax = ROUND(@1PfSalaryLimit*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
	       
	       IF(@lEmployerFpsPercent>@lValuesforMax)
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent-@lValuesforMax,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent,0)
			END
			
			IF(@lEmployerFpsPercent = @1Max)
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent-@1Max,@lRoundOffToWholeNumber)
			END
			
			IF(@lEmployerFpsPercent > @lValuesforMax)
			BEGIN
				SET @1Bal = ROUND(@lEmployerFpsPercent-@lValuesforMax,0)
			END
		   ELSE
			BEGIN
				SET @1Bal = 0
			END
			
		   	SET @lEmployerPfPercent = ROUND(@1Basic*@1EmployerPfPercent/100,@lRoundOffToWholeNumber)
		   		        
	       IF(@1Basic < @1PfSalaryLimit)
			   BEGIN
			   
				 IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Bal+ @lEmployerPfPercent,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       ELSE
			   BEGIN
			   
			   IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployerPfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       
	       --IF(@1Basic > @1PfSalaryLimit)
	       --   BEGIN
	           --SET @1EmployeePfAmount = @1Basic*@1EmployeePfPercent/100 
	             INSERT INTO  [sPayroll].[tPfProcess]
							   (
							    [PayProcessElementId]
							   ,[EmployeePfAmount]
							   ,[EmployerPfAmount]
							   ,[EmployerFpsAmount]
							   ,[EligibleFpsAmount]
							   ,[AdminChargesAmount]
							   ,[EdliChargesAmount]
							   ,[InspectionChargesAmount]
							   )
							   Values
							   (
							     @1PayProcesdsElementId,
							     @1EmployeePfAmount,
							     @1EmployerPfAmount,
							     @lRestrictionEmployerFpsPercent,
							     0.0,
							     @1AdminChargesPercent,
							     @1EdliPercent,
                                 @1InspectionChargesPercent	    
							    ) 
					
				 IF(@1PfSalaryLimit > 0)			    
				 BEGIN
					UPDATE sPayroll.tPayProcessElement 
					SET Amount = @1EmployeePfAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId			    
				 END	
				--END 		
				
				--print 'For Element'	
	  END
	  
	  --FOR Esi Element
	 IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId)
	  BEGIN
			   SET @1PayProcesdsElementId = 0.0  
			   SET @1ESISalaryLimit = 0.0			
			   SELECT  @1ESISalaryLimit = EsiSalaryLimit,@1EmployeeESIPercent=EmployeeEsiPercent,@1EmployerESIPercent = EmployerEsiPercent FROM sPayroll.tEsiSetup Where PayrollYearId = @rPayrollYearId
			   SELECT @1PayProcesdsElementId = Id FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId
			    
		   IF(@1ESISalaryLimit > @rSalary)					   
			  BEGIN
			  SET @1EmployeeESIAmount = @rSalary * @1EmployeeESIPercent/100	
			   INSERT INTO [sPayroll].[tEsiProcess]
						   (
							    [PayProcessElementId]
							   ,[EmployeeEsiAmount]
							   ,[EmployerEsiAmount]
						   )
						   Values
						   (
						       @1PayProcesdsElementId
						      ,@rSalary * @1EmployeeESIPercent/100
						      ,@rSalary * @1EmployerESIPercent/100
						   )
						   
					 UPDATE sPayroll.tPayProcessElement 
				 SET Amount = @1EmployeeESIAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId  
			   END	 
			   --print 'For ESI'	
	  END  
	  
	  SET @1TotalDeductionAmount = @rDeductionAmount + @1Tax + @1EmployeePfAmount + @1EmployeeESIAmount
	  
	  UPDATE sPayroll.tPayProcessEmployee  
	  SET  
	      TotalEarning = ROUND(@rSalary,@lRoundOffToWholeNumber),
	      TotalDeduction = ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber),	       
		  NetAmount = ROUND(@rSalary,@lRoundOffToWholeNumber) - ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber)  
	  WHERE ID =  @rPayProcessEmployeeId   
	    
    END
	 
END
GO
PRINT N'Altering Procedure [sPayroll].[pProfessionalTaxRangeAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeAdd] 
	      
		    @rId int
           ,@rSalary decimal(22,6)
           ,@rTax decimal(22,6)
           ,@rPayrollYearId int
           ,@rOrgGroupId smallint
           ,@rCreatedUserId bigint
		   ,@rGenderId tinyint=0
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tProfessionalTaxRange', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tProfessionalTaxRange]
           (
            [Id]
           ,[Salary]
           ,[Tax]
           ,[PayrollYearId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
		   ,[GenderId]
           )
     VALUES
           (
            @lNextNumber 
           ,@rSalary 
           ,@rTax 
           ,@rPayrollYearId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
		   ,@rGenderId
           )
         END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tProfessionalTaxRange]
			   SET  
				   [Salary] = @rSalary
				  ,[Tax] = @rTax 
				  ,[GenderId]=@rGenderId
			 
      
			  Where Id = @rId	     		    
		END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Professional Tax Range Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering Procedure [sPayroll].[pProfessionalTaxRangeGet]...';


GO
ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeGet]
	 @rId int,
	 @rPayrollYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

       SELECT   
           [Id]
		  ,[Salary]
		  ,[Tax]
		 ,isnull(GenderId,0) as GenderId
	   FROM  [sPayroll].[tProfessionalTaxRange]
  
  
Where  
     (Id = @rId OR @rId = 0) AND 
     PayrollYearId = @rPayrollYearId
     
     ORDER BY Salary DESC,GenderId
		
END
GO

 
ALTER PROCEDURE [sAcademic].[pTaskConsolidatedDashboardGet]

     @rOrgGroupId smallint,
     @rTypeId int,
     @rDate date,
     @rType nvarchar(20),
     @rCommonOrgGroupBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	---Attendance Task Wise 
	IF( @rType = 'Attendance')
		BEGIN
			IF(@rTypeId = 1)
				BEGIN
				SELECT 				
			OGM.Id AS OrgGroupId,
			OGM.Title AS OrgGroupName,
			 (
				 SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  NOT in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				 -- IsInContext
				 AND BM.IsInContext = 1
				) Temp WHERE rowno=1
			 ) AS Pending,
			 (SELECT
					COUNT(DISTINCT DM.Id) AS TotalDivision
			  FROM
					sSetup.tDivisionMaster DM
					INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
					INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= SA.StudentId AND SM.StatusId =1
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
			  WHERE OGM.Id =OGMR.Id
			  AND DM.IsObsolete=0 AND OGMR.IsObsolete = 0 --AND BM.IsActive = 1 
					AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGMR.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
					-- IsInContext
					AND BM.IsInContext = 1
			) AS Total,
			(
			SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				-- IsInContext
				AND BM.IsInContext = 1
				) Temp WHERE rowno=1) AS Complated
      FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
			INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				
					 WHERE 
		    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
			-- IsInContext
			AND BM.IsInContext = 1
	 GROUP BY
			OGM.Id, OGM.Title
	 ORDER BY
			OGM.Id	
				
				
		--			  SELECT 				
		--	OGM.Id AS OrgGroupId,
		--	OGM.Title AS OrgGroupName,
		--	 CONVERT(nvarchar(10),ISNULL(AT1.DivisionPresent,0)) AS Pending
		--	,CONVERT(nvarchar(10),ISNULL(AT2.TotalDivision,0)) AS Total
		--	,CONVERT(nvarchar(10),ISNULL(AT3.DoneAttendance,0)) AS Complated
  --    FROM 
		--	sSetup.tOrgGroupMaster OGM
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
		--	INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		--	LEFT JOIN --Attendance Pending
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DivisionPresent,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT1 ON AT1.OrgGroupId = OGM.Id
		--	  --SELECT
		--		 --  COUNT(DISTINCT DM.Id) AS DivisionPresent,
		--		 --  OGM.Id AS OrgGroupId
		--	  --FROM
		--		 -- sSetup.tDivisionMaster DM
		--		 -- INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--		 -- INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--		 -- INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		 -- INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--		 -- INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		 -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--		 -- INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id 
		--	  --WHERE
		--		 -- SR.IsPresent = 1 AND SR.AttendanceDate = @rDate 
		--		 -- --AND BM.IsActive=1 
		--		 -- AND DM.IsObsolete=0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  --GROUP BY
		--		 -- OGM.Id
		--	--) AT1 ON AT1.OrgGroupId = OGM.Id
		--	LEFT JOIN  --Attendance Total
		--	(
		--	  SELECT
		--			COUNT(DISTINCT DM.Id) AS TotalDivision,
		--			OGM.Id AS OrgGroupId
		--	  FROM
		--			sSetup.tDivisionMaster DM
		--			INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
		--	  WHERE
		--			DM.IsObsolete=0 AND OGM.IsObsolete = 0 --AND BM.IsActive = 1 
		--			AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  GROUP BY
		--			OGM.Id
		--	) AT2 ON AT2.OrgGroupId = OGM.Id
		--	LEFT JOIN --Attendance Done
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT3 ON AT3.OrgGroupId = OGM.Id

			
	 --WHERE 
		--    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
	 --GROUP BY
		--	OGM.Id, OGM.Title,DivisionPresent,TotalDivision,DoneAttendance
	 --ORDER BY
		--	OGM.Id	
				END
				ELSE IF( @rTypeId = 11)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
				   -- IsInContext
				   AND BM.IsInContext = 1
						--AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
					END
				ELSE IF( @rTypeId = 12)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
					END
				ELSE IF (@rTypeId = 13)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id  in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
					END
		END
	IF(@rType = 'CW/HW')
			IF(@rTypeId=2)
				BEGIN
					SELECT 				
						OGM.Id AS OrgGroupId,
						OGM.Title AS OrgGroupName,
						ISNULL((
-- ClassworkAssigned								
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL)
						-- IsInContext
						AND BM.IsInContext = 1 
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkAssigned,
					ISNULL((
--ClassworkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					Where TSD.DivisionId = TSD1.DivisionId AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate)),0) 
					AS ClassworkNotAssigned,
					ISNULL((
--ClassworkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkNotApplicable,
					ISNULL((
--HomeWorkAssigned
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkAssigned,
					ISNULL((
--HomeWorkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
					Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId 
					AND AC.ClassWorkDate=@rDate)),0) 
					AS HomeWorkNotAssigned,
					ISNULL((
--HomeWorkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE
						AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkNotApplicable
						 FROM 
								sSetup.tOrgGroupMaster OGM
								INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								INNER JOIN sStudent.tAcademic A ON A.OrgId = OM.Id
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
								--LEFT JOIN 
								--(
								--  SELECT 
								--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
								--		OGM.Id AS OrgGroupId
								--  FROM sAcademic.tClasswork AC
								--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
								--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
								--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
								--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
								--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
								--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								--  WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
								--		AND AC.ClassWorkDate=@rDate AND ClassworkStatusId = 1 AND (Classwork != '' OR  Classwork = NULL)
								--  GROUP BY 
								--		OGM.Id
								--) CW1 ON CW1.OrgGroupId = OGM.Id
				--				LEFT JOIN(
				--					  SELECT
				--							COUNT(DISTINCT SM.Id) AS ClassWork,
				--							OGM.Id AS OrgGroupId
				--					  FROM
				--							sSetup.tSubjectMaster SM
				--							INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
				--							INNER JOIN sStudent.tAcademic SA ON SA.ClassId = CS.ClassId
				--							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--							INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				    
				--					  WHERE
				--							--BM.IsActive=1 AND 
				--							SM.IsObsolete=0 AND OGM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
				--					  GROUP BY
				--							OGM.Id
				--						) CW2 ON CW2.OrgGroupId = OGM.Id

				--				--LEFT JOIN 
				--				--(
				--				--  SELECT 
				--				--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--				--		OGM.Id AS OrgGroupId
				--				--  FROM sAcademic.tClasswork AC
				--				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--				--	   INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
				--				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				--  WHERE 
				--				--	   AC.ClassWorkDate=@rDate AND (Classwork = NULL OR Classwork='') AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				--  GROUP BY 
				--				--		OGM.Id
				--				--) CW2 ON CW2.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--				(
				--				  SELECT 
				--						COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--						OGM.Id AS OrgGroupId
				--				  FROM sAcademic.tClasswork AC
				--					   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--					   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--					   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--					   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--					   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--					   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				  WHERE 
				--					   AC.ClassWorkDate=@rDate AND ClassworkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				  GROUP BY 
				--						OGM.Id
				--				) CW3 ON CW3.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND (HomeWork != '' OR HomeWork=NULL)
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW1 ON HW1.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND(HomeWork = NULL OR HomeWork='')
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW2 ON HW2.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					 
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW3 ON HW3.OrgGroupId = OGM.Id
						 WHERE 
								OGM.IsObsolete = 0  AND Bm.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
								-- IsInContext
								AND BM.IsInContext = 1
						 GROUP BY OGM.Id, OGM.Title
							--	OGM.Id, OGM.Title,CW1.Classwork,CW2.Classwork, CW3.Classwork,HW1.HomeWork,HW2.HomeWork, HW3.HomeWork
						 ORDER BY
								OGM.Id
				END
				ELSE IF( @rTypeId = 21)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By DM.OrderIndex
					END
				ELSE IF( @rTypeId = 22)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId

						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 23)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						Order By DM.OrderIndex
					END
					ELSE IF (@rTypeId = 24)
						BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By DM.OrderIndex
									
					END
				ELSE IF( @rTypeId = 25)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 26)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2 
						AND (HomeWork != '' OR HomeWork=NULL)
						-- IsInContext
						AND BM.IsInContext = 1
						Order By DM.OrderIndex
					END
END
GO
PRINT N'Altering Procedure [sActivity].[pEventAttendanceGet]...';


GO
ALTER PROCEDURE [sActivity].[pEventAttendanceGet]
	 
	 
	 @rEventScheduleId int,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rOrgId smallint,
	 @rBatchId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		-- For Student Deatils
		IF(@rDivisionId != 0)
		BEGIN 
			SELECT
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo,
				vSA.Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				vSA.BatchId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
			WHERE
				vSA.OrgId=@rOrgId AND vSA.DivisionId = @rDivisionId
				AND vSA.BatchId = @rBatchId
				AND (vSA.StatusId =1 )
			ORDER BY vSA.RollNo	
		END
		
		-- For Employee Deatils
		IF(@rDepartmentId != 0)
		BEGIN 
			SELECT
				vECD.EmployeeId AS SourceId,
				vECD.Code,
				vECD.EmployeeName AS Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete
			FROM 
				sHrm.vEmployeeCommonDetail vECD
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vECD.OrganizationDepartmentId AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vECD.EmployeeId AND EAT.SourceTypeId = 95
			WHERE
				vECD.OrgId=@rOrgId AND vECD.OrganizationDepartmentId = @rDepartmentId
				AND (vECD.EmployeeStatusId = 7)
			ORDER BY vECD.Code	
		END
END
GO
PRINT N'Altering Procedure [sActivity].[pEventAttendanceListGet]...';


GO
ALTER PROCEDURE [sActivity].[pEventAttendanceListGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rCode nvarchar(20)='',
	@rFirstName nvarchar(100)='',
	@rBatchId int = 0,
	@rDepartmentId int=0,
	@rEventTypeId int = 0,
	@rEventId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rAcademicId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		END
	SELECT 
			SA.AcademicId,
			SA.FirstName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			--SA.DivisionId,
			SA.RollNo,
			SA.OrgId,
			ISNULL (EA.IsSelfPresent,0) AS IsSelfPresent,
			ISNULL (EA.IsMotherPresent,0) AS IsMotherPresent,
			ISNULL (EA.IsFatherPresent,0) AS IsFatherPresent,
			ISNULL (EA.IsGuardianPresent,0) AS IsGuardianPresent,
			ES.FromDate,
			ES.ToDate,
			EM.Title AS EventTypeName,
			ES.Title AS EventName,
			ES.EventTypeId AS EventTypeId,
			ISNULL (EA.EventScheduleId,0) as EventScheduleId,
		
			
			ISNULL (EA.SchoolFeedback,'') AS SchoolFeedback,
			ISNULL (EA.ParentFeedback,'') AS ParentFeedback,
			ISNULL (EA.ParentAction,'') AS ParentAction,
			ISNULL (EA.SchoolAction,'') AS SchoolAction,
		ISNULL (EA.IsTrackForReview,0) AS IsTrackForReview,
		SA.DepartmentName,
		SA.BatchName
			
		
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND ((ES.Id = @rEventId) OR (@rEventId = 0))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			AND((SA.StatusId= 1))--add for 28753 mantis

			ORDER BY SA.ClassId,SA.DivisionId
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionMeritListGET]...';


GO

 
ALTER PROCEDURE [sAdmission].[pAdmissionMeritListGET]

	 @rClassId  nvarchar(max) = '',
	 @rBatchId int = 0,
	 @rOrgId int,
	 @rStatus int,
	 @rMinMeritMarks decimal(12,2),
	 @rMaxMeritMarks decimal(12,2),
	 @rFromDate date,
	 @rToDate date,
	 @rAdmissionMinMeritMarks decimal(10,2),
	 @rAdmissionMaxMeritMarks decimal(10,2)
	 --@rTitle nvarchar(100),
	 --@rStatusId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	SELECT AF.Id,
		AFS.AdmissionFormId,
		AFS.AdmissionStatusId,
		AF.FormNo,
	    (AF.FirstName+' '+AF.MiddleName+' '+AF.LastName)AS Name,
		AF.ContactNo,
		AFS.DiscussionDate,
		ASM.Title,
		SUM(ASS.ObtainMark)AS obtain,
		AF.StatusId 
	FROM sAdmission.tAdmissionForm AF 
		Inner JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		Left JOIN sAdmission.tAdmissionSetupStudent ASS ON AF.Id=ASS.AdmissionFormId 
		LEFT JOIN sAdmission.tAdmissionSetup ADS ON ASS.AdmissionSetupId=ADS.Id 
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId             
	WHERE ((AF.ForClassId IN(@rClassId)) OR (@rClassId=0))
		AND((AF.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (( AFS.DiscussionDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND (( AFS.DiscussionDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((AF.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((ASS.ObtainMark >=@rMinMeritMarks) OR (ISNULL(@rMinMeritMarks,0) =0))
		--AND ((ASS.ObtainMark <=@rMaxMeritMarks) OR (ISNULL(@rMaxMeritMarks,0) =0))
		AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		--AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		--AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		AND ((AF.MeritMarks >=@rAdmissionMinMeritMarks) OR (ISNULL(@rAdmissionMinMeritMarks,0) =0))
		AND ((AF.MeritMarks <=@rAdmissionMaxMeritMarks) OR (ISNULL(@rAdmissionMaxMeritMarks,0) =0))
		
		GROUP BY AF.Id,AF.FormNo,AF.ContactNo,AF.FirstName,AF.MiddleName,AF.LastName,AFS.AdmissionFormId,AFS.AdmissionStatusId,ASM.Title,AF.StatusId,AFS.DiscussionDate
		Having 
		(SUM(ASS.ObtainMark) >= @rMinMeritMarks OR  (ISNULL(@rMinMeritMarks,0) =0) ) 
		AND (SUM(ASS.ObtainMark) <= @rMaxMeritMarks OR (ISNULL(@rMaxMeritMarks,0) =0))
		ORDER BY AF.Id
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionDetailsGet]...';


GO


ALTER PROCEDURE [sAdmission].[pRptAdmissionDetailsGet]
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rFromMeritMarks int,
	 @rToMeritMarks int,
	 @rIsDetail bit =0 --Mantis : 0028438
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	
	 AF.FormNo,
	 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
	 AF.ForClassId,
	 AF.DateOfBirth,
	 AF.BatchId,
	 AF.OrgId,
	 AF.City,
	 AF.Country,
	 AF.State AS CityState,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 CM.Title AS Class,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 AF.CastCategoryId,
	 @rBuilder1 AS Builder1,
	 @rBuilder2 AS Builder2,
	 @rIsDetail AS IsDetail
	 
  FROM 
				sAdmission.tAdmissionForm AF
				INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
				LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId=GM.Id
				LEFT JOIN sCommon.tStatusMaster SM ON AF.StatusId=SM.Id	
 WHERE 	
       AF.BatchId=@rBatchId
    --AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
		AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
	--Group By FormNo,GM.Title,FirstName,MiddleName,LastName,DateOfBirth,City,Country,State,ContactEmail,
	--         ContactNo,PreviousSchool,MeritGrade,MeritMarks,FamilyCast,FamilySubCast,CastCategoryId
				
END
GO
PRINT N'Altering Procedure [sAlert].[pAlertQueueLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pAlertQueueLogAdd]
	@rId bigint = 0,
	@rMessageDate datetime = null,
	@rQueueMessage nvarchar(max) = '',
	@rEventId int = 0,
	@rAlertModeId tinyint = 0,
	@rOrgId smallint = 0,
	@rCreatedUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT  
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertQueueLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO [sAlert].[tAlertQueueLog]
				([AutoId]
				,[MessageDate]
			    ,[QueueMessage]
			    ,[EventId]
			    ,[AlertModeId]
			    ,[OrgId]
			    ,[CreatedUserId]
			    ,[CreatedDateTime])
		   VALUES
				(@lNextNumber
				,@rMessageDate
			    ,@rQueueMessage
			    ,@rEventId
			    ,@rAlertModeId
			    ,@rOrgId
			    ,@rCreatedUserId
			    ,sCommon.fGetDate())

			SELECT @lNextNumber AS Result
		END
		ELSE
		BEGIN
			UPDATE [sAlert].[tAlertQueueLog] SET [QueueMessage] = @rQueueMessage WHERE AutoId = @rId

			SELECT @rId AS Result
		END
	COMMIT TRANSACTION
    END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricAbsentTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100),
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int =135
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		if(@rEventId=0)
		begin 
			set @rEventId=135
		end
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId=0-- isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				,min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				--For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				--AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				--For Optimization
				Group by SourceId,SourceTypeId
			END
			
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sHrm.vEmployeeCommonDetail EM 
				Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND E.StatusId = 7  -- Added
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')

			
			--select * from #tTable
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@rTemplate,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					replace (
					replace(@lSMSTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[EmployeeName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[EmployeeName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName AS EmployeeName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pEmployeeBiometricFirstInLastOutListGet]...';


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInLastOutListGet]
	@rEventId int,--127 for firstin 128 LastOut
	@rOrgId int,
	@rTemplate nvarchar(max),
	@rDate dateTime,
	@rMailSubject nvarchar(max)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--set @rDate=cast(@rDate as datetime)

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	if(@rEventId=127)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	end
	else if(@rEventId=128)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_Out'
	end
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.EmployeeId AS AcademicId,
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[PresentTime]'','+@lColumnName+'),
					''[TimeStamp]'','+@lColumnName+'),
					''[PresentDate]'','''+ISNULL(CONVERT(varchar,@rDate,103),'''')+''')
					 AS Template,
					 '''+@rMailSubject+''' as MailSubject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS Name,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					OM.Title AS SchoolName,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+'
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MT.Attn_dt=cast(rtrim(YEAR('''+CONVERT(nvarchar(20),@rDate)+''') *10000+ Month('''+CONVERT(nvarchar(20),@rDate)+''') *100+ 01) as datetime)
				And '+@lColumnName+' <> ''00:00'' 
				AND EM.StatusId = 7	'
		print (@Query)
		execute (@Query)	


	
END
GO
PRINT N'Altering Procedure [sAlert].[pIssueBookAllGet]...';


GO
ALTER PROCEDURE [sAlert].[pIssueBookAllGet]
	 
	 @rSourceTypeId smallint,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rTemplate nvarchar(max),	 	
	 @rMailSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SELECT distinct
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name AS Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId
					INNER JOIN sStudent.vStudentCommunication SC1 ON SC1.StudentId = BL1.ReaderSourceId AND SC1.BatchId = BL1.BatchId  AND BL1.ReaderSourceTypeId=2003
					INNER JOIN sSetup.tBatchMaster BMM1 ON BMM1.Id = BL1.BatchId 
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BL1.OrgId
					INNER JOIN sLibrary.tLibraryMaster LM1 ON LM.Id=BL1.LibraryId
					WHERE
							(BL1.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
						AND ((BL1.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
						AND ((BL1.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
						AND (BL1.OrgId = @rOrgId)
						AND (BL1.BatchId = @rBatchId)
						AND (BL1.ReaderSourceTypeId != 0)
						AND ((SC1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
						AND ((SC1.ClassId=@rClassId) OR (@rClassId=0))
						AND ((SC1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
						--AND BL1.IsCurrentStatus=1 
						AND BL1.StatusId = 523
						AND BL1.ReaderSourceId=BL.ReaderSourceId	
						AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
                    FOR XML PATH('')),1,1,''))),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=2003
					AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = SC.StudentId AND BL1.BatchId =SC.BatchId  
					AND BMM.Id = BL1.BatchId  AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id
					AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
					AND BL1.StatusId = 523
					--AND BL1.IsCurrentStatus=1 		
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			LM.Title AS LibraryName
	From 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND SC.BatchId = BL.BatchId  AND BL.ReaderSourceTypeId=2003
		INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE
		(BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND (BL.ReaderSourceTypeId != 0)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND BL.StatusId = 523
		--AND BL.IsCurrentStatus=1 

	UNION 

	SELECT distinct
			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId As AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			EC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							--AND BL1.IsCurrentStatus=1
							AND BL1.StatusId = 523
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.StatusId = 523
							--AND BL1.IsCurrentStatus=1	
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			LM.Title AS LibraryName
	         
	FROM 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EC.DepartmentId
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EC.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

	WHERE 

		 (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7	
		AND BL.StatusId = 523
		--AND BL.IsCurrentStatus=1 
		 
END
GO
PRINT N'Altering Procedure [sAlert].[pPublishExamScheduleGet]...';


GO


ALTER PROCEDURE [sAlert].[pPublishExamScheduleGet]
	 	 @rExamId int,
		 @rBatchId int,
		 @rSubject nvarchar(100)='',
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select		
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			@rSubject AS [Subject],
			replace (
			replace (
			replace (
			replace(@rTemplate,
			'[StudentName]',SC.Name),
			'[ExamName]',ESGM.Title),
			'[ClassName]',SC.ClassName),
			'[ExamSubjectDetail]', STUFF    
            (    
                (
					Select  ',' + Char(10) + SM.Title +':' + CONVERT(nvarchar,ED.ExamDate) +':'+ CONVERT(nvarchar,ED.ExamTime) +':' + ED.ExamTopic 
					from sSetup.tSubjectMaster SM 
					INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
					Where CS.ClassId = CM.Id
					FOR XML PATH('')    
                )    
                    
            ,1,1,''))
			 AS MsgText,
			 -- Add Char(10) in above due to this mantis 0028117
			 SC.ClassName AS Class,
			 SC.AcademicId AS SourceId,
			 2001 AS SourceTypeId,
			 SC.OrgId,
			 SC.OrgGroupId,
			 SC.AcademicId AS ReceiverSourceId,
			 2001 AS ReceiverSourceTypeId,
			 SC.WhatsAppContactNo,
			 ESGM.Title AS ExamName
 FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			--INNER JOIN sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId=SM.Id	
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.ClassId = EM.ClassId  AND EM.BatchId = SC.BatchId AND SC.StatusId = 1
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
   WHERE       
            EM.Id=@rExamId
			AND EM.BatchId = @rBatchId
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricAbsentTimeGet]...';


GO


ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int=136

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003),0)

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId,
				min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 
				-- For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=136 and SourceTypeId=2003 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				-- For Optimization
				Group by SourceId,SourceTypeId
			END

			-- For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sStudent.vStudentCommunication SC 
				Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')
		
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[StudentName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAssessment].[ExamSettingApplyAllClassUpdate]...';


GO

ALTER PROCEDURE [sAssessment].[ExamSettingApplyAllClassUpdate]
	 
			@rBatchId int
			,@rExamSubGroupId int           
			,@rClassId int
			,@rIsRankNo bit
			,@rIsGrade bit
			,@rIsPercentile bit
			,@rIsPercentage bit
			,@rIsSubjectPercentile bit
			,@rGradeSetId int
			,@rIsProcessResult bit
			,@rIsMarkInDecimal bit
			,@rIsNegativeMarks bit
			,@rIsPrePrinted bit
			,@rIsDisplayBirthDate bit
			,@rIsDisplayPhoto bit
			,@rIsDisplayschoolName bit
			,@rIsIncludeCoScholastic bit
			,@rIsLockForEdit bit
			,@rRemark1 nvarchar(1000)
			,@rRemark2 nvarchar(300)
			,@rDisplayTitle nvarchar(150)
			,@rFooterAdjustment smallint
			,@rReportId smallint
			,@rRemark3 nvarchar(300)
			,@rIsDisplayHeightWeight bit
			,@rIsDisplayAttendance bit
			,@rIsDisplayResultStatus bit
			,@rDetailAdjustment smallint
			,@rTermScopeId smallint
			,@rMaximumMark Decimal
			,@rOrgId int,
			@rCoScholasticScopeId smallint,
			@rCoScholasticGradeSet int,
			@rPercentileScope smallint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rSubjectGroupPerPage smallint,
			@rIsExcludeAbsentTotal bit,
			@rDecimalUpto nvarchar(10),
			@rIsShowTotalMark bit=0,
			@rRemark1Caption nvarchar(100),
			@rRemark2Caption nvarchar(100),
			@rRemark3Caption nvarchar(100),
			@rTeacherSignCaption nvarchar(100),
			@rPrincipalSignCaption nvarchar(100),
			@rParentSignCaption nvarchar(100),
			@rIsAllExamPassRequired bit=0 , 
			@rIsGenerateRankNo bit = 0,
			@rResultSheetAdditionalTitle nvarchar(100)='',
			@rDisplayAttendanceId Smallint=0,
			@rReportHeaderId smallint=0,
			@rIsFailPercentageZero bit = 0,
			@rIsDisplayParentName bit = 0,
			@rIsDisplayGradeString bit = 0,
			@rIsShowResultIndicator bit = 0,
			@rIsDisplayHighestDivisionMark bit = 0,
			@rIsDisplayHighestDivisionGrade bit = 0,
			@rIsDisplayActivityGrade bit = 0

			WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF (@rTermScopeId < 0)
	SET @rTermScopeId = 0
	
	
	
	 BEGIN		
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			    IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   coscholasticgradesetid = @rCoScholasticgradeset,
			   percentilescopeid=@rpercentilescope,
			   isdisplayteachersign = @rIsdisplayteachersign,
			   isdisplayprincipalsign = @risdisplayprincipalsign,
			   SubjectGroupPerPage = @rSubjectGroupPerpage,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMark,
			   Remark1Caption=@rRemark1Caption,
			   Remark2Caption=@rRemark2Caption,
			   Remark3Caption=@rRemark3Caption,
			   TeacherSignCaption = @rTeacherSignCaption,
			   PrincipalSignCaption =@rPrincipalSignCaption,
			   ParentSignCaption =@rParentSignCaption,
			   IsAllExamPassRequired =@rIsAllExamPassRequired,
			   IsGenerateRankNo = @rIsGenerateRankNo,
			   ResultSheetAdditionalTitle=@rResultSheetAdditionalTitle,
			   DisplayAttendanceId=@rDisplayAttendanceId,
			   ReportHeaderId=@rReportHeaderId,
			   IsRemovePercentageForFail=@rIsFailPercentageZero,
			   IsDisplayParentName=@rIsDisplayParentName,
			   IsDisplayGradeString=@rIsDisplayGradeString,
			   IsDisplayResultIndicator = @rIsShowResultIndicator,
			   IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark,
			   IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade,
			   IsDisplayActivityGrade =@rIsDisplayActivityGrade
             
	      WHERE ClassId = @rClassId AND ExamSubGroupId=@rExamSubGroupId AND BatchId = @rBatchId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamSubjectListGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamSubjectListGet]
	 @rClassId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	--Add CS.IsObsolete = 0 for mantisid - 0028508	
	SELECT 
	    0 AS ExamDetailId,
		SM.Title as SubjectName,
		CS.Id as ClassSubjectId,
		'0' AS Minimum,
		'0' AS Maximum,
		ISNULL(CS.ORDERINDEX,0) AS DisplayOrder,
		'false' AS IsDisplayInMarksheet,
		'false' AS IsIncludeInTotal,
		'false' AS IsShowSubjectGrade,
		sCommon.fGetDate() AS ExamDate,
		'0' AS ExamTime,
		'0' AS ExamTopic,
		'0' AS ExamLanguage,
		'0' AS GradeSetDetailId,
		'false' as Selected
	FROM 
			[sSetup].[tClassMaster] CM INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId	
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = 0
			
	Where (CS.Classid=@rClassId or @rClassId=0) AND CS.IsObsolete = 0  	    
			order by CS.OrderIndex ASC
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptAllClassSubjectGradeAnalysis]...';


GO

ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As ClassName,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS AveragePerMark,
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS LowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G8  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		where 
			A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
			AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND ISNULL(RD.IsPresent,0) = 0 
		) AS AbsentCount,
		(select MAX(ED.Maximum) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaximumMark --Mantis : 0028713
	  
	 from
 

		sAssessment.tExamDetail ED		
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		
	
		WHERE 
 
			
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0
  	
END

-- SP Drag and Drop
--BEGIN
	--SELECT 
	-- '' AS Builder1,
	-- 0 AS ClassId,
	-- 0 AS DivisionId,
	-- '' AS ClassName,
	-- '' AS DivisionName,
	-- 0 AS NoOfStudent,
	-- Convert(DECIMAL,0) HighestPerMark,
	-- Convert(DECIMAL,0) AveragePerMark,
	-- Convert(DECIMAL,0) LowestPerMark,
	-- 0 AS GradeCount1,
	-- 0 AS GradeCount2,
	-- 0 AS GradeCount3,
	-- 0 AS GradeCount4,
	-- 0 AS GradeCount5,
	-- 0 AS GradeCount6,
	-- 0 AS GradeCount7,
	-- 0 AS GradeCount8,
	-- 0 AS GradeCount9,
	-- 0 AS GradeCount10,
	-- '' AS Grade1,
	-- '' AS Grade2,
	-- '' AS Grade3,
	-- '' AS Grade4,
	-- '' AS Grade5,
	-- '' AS Grade6,
	-- '' AS Grade7,
	-- '' AS Grade8,
	-- '' AS Grade9,
	-- '' AS Grade10,
	-- 0 AS SubjectId,
	-- '' AS SubjectName,
	-- 0 AS OrderIndex,
	-- 0 AS AbsentCount,
	-- Convert(DECIMAL,0) MaximumMark

--END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @DecimalConfigid nvarchar(20)='' , @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster where Id=@rBatchId
SELECT @DecimalConfigid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId

--add for 28663 mantis start
DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId
--add for 28663 mantis end
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,	--add for 28663 mantis
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark				--add for 28663 mantis

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
		LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		--AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptStudentResultDetailSub]...';


GO
ALTER PROCEDURE [sAssessment].[pRptStudentResultDetailSub]
	 
	@rExamId bigint,
	@rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #tmp
(
Id int identity(1,1),
ResultDetailsName nvarchar(100),
ResultDetailsValue nvarchar(100)
)
INSERT INTO #tmp
	SELECT Distinct
		ISNULL(NULLIF(ALS.PercentageLabel,''),'Percentage') AS ResultDetailsName,
		Convert(nvarchar,R.Percentage)AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId) 
		AND (R.ExamId = @rExamId)
		AND EM.IsPercentage = 1
UNION  All
SELECT Distinct
		--'Grade' AS ResultDetailsName,
		ISNULL(NULLIF(ALS.OverallGradeLabel,''),'Over All Grade') AS ResultDetailsName,
		R.ResultGrade AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId) 
		AND (R.ExamId = @rExamId)
		AND EM.IsGrade = 1
UNION ALL
SELECT Distinct
		--'Result Status' AS ResultDetailsName,
		ISNULL(NULlIF(ALS.ResultStatusLabel,''),'Result Status') AS ResultDetailsName,
		R.ResultStatus AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsResultStatus = 1
UNION All
SELECT Distinct
		--'Rank No' AS ResultDetailsName,
		ISNULL(NULlIF(ALS.RankNoLabel,''),'Rank No') AS ResultDetailsName,
		Convert(nvarchar,R.RankNumber) AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsRankNo = 1

UNION All
SELECT Distinct
		--'Percentile' AS ResultDetailsName,
		ISNULL(NULLIF(ALS.PercentileLabel,''),'Percentile') AS ResultDetailsName,
		Convert(nvarchar,R.Percentile) AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsPercentile = 1


		--Select * from #tmp
		Select (Select COUNT(Id)FROM #tmp) As TotalCount,ResultDetailsName,ResultDetailsValue from #tmp
		--GROUP BY Id
		DROP TABLE #tmp
 
End
GO
PRINT N'Altering Procedure [sAssessment].[pStudentwiseOptionalSubjectListGet]...';


GO

ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectListGet]
                  
    @rDivisionId bigint,
    @rClassId bigint,
    @rSubjectId bigint ,
    @rBatchId int,
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rClassStatusId int=0,
	@rStatusId int=1,
    @rViewMode smallint = 0,  -- 0 for Vertical and 1 for Horizontal
	@rSubjects nvarchar(max)=''
AS
SET NOCOUNT ON

BEGIN

	IF(@rViewMode = 1)
	BEGIN
		SELECT
			SA.AcademicId,
			CS.Id as ClassSubjectId,
			SA.Name as StudentName,
			CS.SubjectId, 
			SA.Code,
			SA.RollNo,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName
			INTO #TempTable 
			FROM
			(
					SELECT * FROM sStudent.vStudentAcademic 
					where (DivisionId = @rDivisionId OR @rDivisionId = 0)  AND BatchId = @rBatchId
					AND (ClassStatusId = @rClassStatusId OR @rClassStatusId = 0) 
					AND (StatusId = @rStatusId OR @rStatusId = 0)) SA  
					CROSS JOIN
					(select * FROM sSetup.tClassSubject B   
					WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  
					AND  (B.Id = @rSubjectId OR @rSubjectId = 0) 
			) AS CS

		SELECT DISTINCT
			SS.AcademicId,
			Stuff ((select ',' + Convert(nvarchar(20),OS.ClassSubjectId) FROM sAssessment.tOptionalSubject OS WHERE AcademicId = SS.AcademicId FOR XML PATH('') ),1,1,'') AS ClassSubjectId,
			SS.StudentName,
			SS.Code,
			SS.RollNo,
			@rBuilder1 AS ClassName,
			@rBuilder2 AS DivisionName,
			SS.DivisionId,
			SS.ClassName AS ClsName,
			SS.DivisionName AS DivName,
			@rSubjects
			FROM
			#TempTable AS SS
			INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
			LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId
			ORDER BY SS.RollNo
			DROP TABLE #TempTable
	END
	ELSE
	BEGIN
		SELECT 
		SS.AcademicId,
		SS.ClassSubjectId,
		SS.StudentName,
		SS.SubjectId,
		SM.Code as SubjectName,
		SS.Code,
		SS.RollNo,
		@rBuilder1 AS ClassName,
		@rBuilder2 AS DivisionName,
		SS.DivisionId,
		SS.ClassName AS ClsName,
		SS.DivisionName AS DivName,
		CASE WHEN isnull(OS.ClassSubjectId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
		FROM
		(SELECT
		SA.AcademicId,
		CS.Id as ClassSubjectId,
		SA.Name as StudentName,
		CS.SubjectId, 
		SA.Code,
		SA.RollNo,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName
		FROM
		 (select * FROM sStudent.vStudentAcademic where (DivisionId=@rDivisionId OR @rDivisionId = 0)  AND BatchId=@rBatchId AND (ClassStatusId=@rClassStatusId OR @rClassStatusId=0) AND (StatusId=@rStatusId OR @rStatusId=0))SA  
		 CROSS JOIN    (select * FROM sSetup.tClassSubject B   WHERE  B.IsOptional = 1 AND (B.ClassId = @rClassId OR @rClassId = 0)  AND  (B.Id= @rSubjectID OR @rSubjectId= 0) AND B.IsObsolete = 0 --add IsObsolete for mantisid - 0028508
		) AS CS 
		 ) AS SS
		 INNER JOIN sSetup.tSubjectMaster SM ON SS.SubjectId = SM.Id 
		 LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SS.AcademicId AND OS.ClassSubjectId = SS.ClassSubjectId

		ORDER BY SS.RollNo,SM.OrderIndex
	   END
END
GO
PRINT N'Altering Procedure [sAttendance].[pAttendanceFollowupListGet]...';


GO
ALTER PROCEDURE [sAttendance].[pAttendanceFollowupListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFromDate date,
		 @rToDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent,
	--(Select ISNULL(AF.Remark,'') FROM sAttendance.tAttendanceFollowup AF WHERE SA.AcademicId = AF.AcademicId AND AF.AttendanceTypeId=1 AND (AF.FollowupDate=@rFollowupDate))AS Remark
	--AF.Remark
	(isnull(SC.PresentStreetOne,'')+' '+isnull(SC.PresentStreetTwo,'')+' '+isnull(SC.PresentStreetThree,'')+' '+isnull(SC.PresentCity,'')+' '+isnull(SC.PresentState,'')+' '+isnull(SC.PresentCountry,'')) as PresentAdress

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END
GO
PRINT N'Altering Procedure [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''
Declare @lAttendanceGridTotal nvarchar(max)=''
CREATE TABLE #AttedanceGridTable (AttendanceCount int,PresentCount int,AbsentCount int,AvreragePresence Decimal(10,2));

IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
BEGIN

--Current Month Details Add
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @CurrentMonthDays DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		SET @CurrentMonthDays = (SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0))))
		DECLARE @YearNumber INT
		DECLARE @AbsentDays nvarchar(max)

		SET @YearNumber =Year(GETDATE())



		SET @PresentCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where IsPresent=1 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		SET @AbsentCount = (select count(AttendanceDate) AS AbsentCount from sAttendance.tStudentRegister 
		where IsPresent=0 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		


		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		IF(@AttendanceCount = 0) BEGIN SET @AveragePresence = 0 END ELSE BEGIN
		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100
		END

		SET @AbsentDays=(SELECT SUBSTRING(
		(SELECT ',' + CONVERT(varchar(10), Day(AttendanceDate))
		FROM  sAttendance.tStudentRegister s
		where AcademicId=@rAcademicId and IsPresent=0 and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate())	AND (AttendanceTypeId=@rAttendanceTypeId)		

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
END


SET 
	@lCuurentMonthAttedanceGrid = @lCuurentMonthAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( @YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@PresentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@AbsentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AbsentDays,0)) + '</td>
	</tr>'


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar,isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentDays,0),103) + '</td>
	</tr>'

		From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;


INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount,
								 AvreragePresence)
				SELECT @AttendanceCount,@PresentCount,@AbsentCount,@AveragePresence;

INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount,
								 AvreragePresence)
				SELECT MR.AttendanceCount, MR.PresentCount, MR.AbsentCount,MR.AveragePresence

	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;
 	
	--add for 28718 mantis, change the attendance formula for percentage
	select 
	@lAttendanceGridTotal = @lAttendanceGridTotal + '<tr>
	<td align="left" scope="col"></td>
	<td align="left" scope="col"></td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull( AGT.AttendanceCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.PresentCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.AbsentCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, CAST((CAST((Sum(isnull(AGT.PresentCount,0))*100) AS decimal(10,2))/CAST((Sum(isnull( AGT.AttendanceCount,0))) AS decimal(10,2))) AS decimal(10,2))) + '</td>
	<td align="left" scope="col"></td>
	</tr>'
		 From #AttedanceGridTable AGT;
	 
	SELECT  isnull(@lAttedanceGrid ,'') + isnull(@lCuurentMonthAttedanceGrid ,'') + isnull(@lAttendanceGridTotal ,'') AS AttedanceGrid		
	
	SELECT * FROM #AttedanceGridTable
	DROP TABLE #AttedanceGridTable;	
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptAttendanceSubjectwiseStatusGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseStatusGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int,
		 @rDepartmentId int,
		 @rSubject nvarchar(MAX)='',
		 @rStatusID int=0,
		 @rFromPercentage decimal(10,2)=0,
		 @rToPercentage decimal(10,2)=100
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rToDate = DATEADD (d,1,@rToDate)
 
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.RollNo,		
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.SubjectId,
		R.Code AS SubjectCode,
		R.Title AS SubjectName,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		
		@rFromPercentage as FromPercentage,
		@rToPercentage as ToPercentage

		FROM sStudent.vStudentAcademic SA INNER JOIN
	(
	SELECT DISTINCT SR.SubjectId,SM.Code,SM.Title,SA.AcademicId FROM
		sAttendance.tStudentRegister SR INNER JOIN 
		sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
	WHERE
		((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		AND (ISNULL(SR.SubjectId,0) IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnSplit(@rSubject,',')) OR (@rSubject=''))
		)
			 R
		ON SA.AcademicId = R.AcademicId
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.StatusId  =@rStatusID) OR (@rStatusID=0))
	 
		




	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	SA.AcademicId,
	--	SA.Name,
	--	SA.Code,
	--	SA.RollNo,
		
	--	--SA.TotalCount,
	--	--SA.PresentCount,
	--	--SA.AbsentDays,
	--	--SA.AbsentCount,
	--	ISNULL(SM.Id,0) AS SubjectId,
	--	ISNULL(SM.Code,'') AS SubjectCode,
	--	ISNULL(SM.Title,'') AS SubjectName	
	--From 
	--sStudent.vStudentAcademic SA INNER JOIN 
	--(SELECT DISTINCT SR.SubjectId,SR.AcademicId FROM
	--sAttendance.tStudentRegister SR ) R ON R.AcademicId = SA.AcademicId
	
	-- ON SA.AcademicId=SR.AcademicId
	--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
	--WHERE
	--	((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	--	AND (SA.OrgId=@rOrgId)
	--	AND	(SA.BatchId = @rBatchId) 
	--	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--	----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	--	AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--	AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--	AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	--	AND (SR.IsPresent = 1)
	--	AND SR.AttendanceTypeId = 5
	--	--AND (SA.StatusId != 3)
	
	
	
END
GO
PRINT N'Altering Procedure [sBiometric].[pTimeSheetListGet]...';


GO


ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 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)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans 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)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans 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)

	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),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans 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)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans 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)
	END
	--Mantis Id:28837 Start to check from amd to date month contain 31 days
	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),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	IF Month(@rToDate) 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),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND  ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	--Mantis Id:28837 End


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans 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)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans 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)  
  
 --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(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans 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)  
 --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(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans 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)  
 --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(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans 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)  
 --END  

 --SELECT * FROM #TempMonthTrans
 --SELECT TM.*,
 
       
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 CASE When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy,TM.ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(EJD.DateOfJoining,'1900/01/01'))
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date


 


END
GO
PRINT N'Altering Procedure [sBiometric].[pUHFReaderStatusUpdate]...';


GO
ALTER PROCEDURE [sBiometric].[pUHFReaderStatusUpdate]
	@rUpdatedDateTime datetime,
	@rDeviceIP nvarchar(20),
	@rDevicePort nvarchar(10),
	@rStatusId int
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	declare @lDeviceName as nvarchar(50)='',@lOrgId int,@lOrgGroupId int,@lStatus nvarchar(15)

	if(@rStatusId=1)
	BEGIN 
		set @lStatus='Connected'
	END
	else if (@rStatusId=2)
	BEGIN 
	set @lStatus='Disconnected'
	END
	  
	if exists(select 1 from [sBiometric].[tDeviceMasterCloud] where DeviceIP=@rDeviceIP AND DevicePort=@rDevicePort)
	BEGIN
		select top 1 @lDeviceName=DeviceName,@lOrgId=OrgId from [sBiometric].[tDeviceMasterCloud] where DeviceIP=@rDeviceIP AND DevicePort=@rDevicePort
	END

	if(@lDeviceName='')
	BEGIN
		select -101
		return
	END
	
	select @lOrgGroupId=OrgGroupId from [sSetup].[tOrganizationMaster] where id=@lOrgId

	IF EXISTS(SELECT 1 FROM sBiometric.tBiometricDeviceSyncDetail WHERE SUBSTRING(DeviceName,0,CHARINDEX('-',DeviceName,0))=@lDeviceName)
	BEGIN 
		
		UPDATE sBiometric.tBiometricDeviceSyncDetail 
		SET 
			SyncTime=@rUpdatedDateTime,
			DeviceName = @lDeviceName + '- ' + @lStatus

		Where  
			SUBSTRING(DeviceName,0,CHARINDEX('-',DeviceName,0))=@lDeviceName
		SELECT @lDeviceName AS DeviceName,@lOrgId as OrgId,@lOrgGroupId AS OrgGroupId
	END
	ELSE
	BEGIN 
	
		INSERT INTO sBiometric.tBiometricDeviceSyncDetail 
		VALUES ( @lDeviceName + '-' + @lStatus, @rUpdatedDateTime)
		SELECT @lDeviceName AS DeviceName,@lOrgId as OrgId,@lOrgGroupId AS OrgGroupId
	END
END
GO
PRINT N'Altering Procedure [sCommunication].[pMyQueryListGet]...';


GO

 
ALTER PROCEDURE [sCommunication].[pMyQueryListGet]	 
	 @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rId bigint = 0 ,  -- Add Initially 0 mantis : 0028594	
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
		
		IF @rUserSourceTypeId   = 95 -- For Employee Login
		BEGIN
			 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


			SELECT 
					QM.Id AS QueryId,
					QCM.Id AS QueryCategoryId,
					ISNULL(QCM.Title,'') AS QueryCategoryMaster,
					QM.Title,
					QM.Remark,
					QM.CreatedDateTime,
					QM.StatusId,
					ISNULL(sm.Title,'') AS StatusMaster,
					QM.IsAssigneeView,
					QM.IsUserView,
					QM.CreatedUserId AS QueryCreatedUserId,
					ISNULL(QM.SubjectId,0) AS SubjectId,
					ISNULL(SubM.Title,'') AS SubjectName,
					ISNULL(QM.Number,0) AS Number,
					ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
					ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
					ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
					ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
					--ISNULL(QM.FromSourceId,0) AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			DM.Title
																	   FROM 
																			[sStudent].[vStudentAcademic] A 
																			 INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
																			 INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
																	   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			DM.Title
																	   FROM 
																			sHrm.tEmployeeJobDetail EJD
																			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
																	   WHERE EmployeeId=QM.FromSourceId
																	   )			                                                   
			  
					   ELSE ''
					END AS Code,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
																	   FROM 
																			sStudent.tStudentMaster SM			                                                       
																	   WHERE Id=QM.FromSourceId 
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
																	   FROM 
																			sHrm.tEmployeeMaster EM
																	   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
																	   )			                                                   
			  
					   ELSE ''
					END AS Name,
					ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
					(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
		  FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
				LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
				INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
		  WHERE 
					((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
				AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((QM.Id=@rId) OR (@rId=0))
				AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
				AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
				AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
				AND ((QM.Number=@rNumber) OR (@rNumber=0))
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0
				--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
				AND QCM.AssignedToId IN (1,3) 
        
			  UNION 
		SELECT 
					QM.Id AS QueryId,
					QCM.Id AS QueryCategoryId,
					ISNULL(QCM.Title,'') AS QueryCategoryMaster,
					QM.Title,
					QM.Remark,
					QM.CreatedDateTime,
					QM.StatusId,
					ISNULL(sm.Title,'') AS StatusMaster,
					QM.IsAssigneeView,
					QM.IsUserView,
					QM.CreatedUserId AS QueryCreatedUserId,
					ISNULL(QM.SubjectId,0) AS SubjectId,
					ISNULL(SubM.Title,'') AS SubjectName,
					ISNULL(QM.Number,0) AS Number,
					ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
					ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
					ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
					ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
					--ISNULL(QM.FromSourceId,0) AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			DM.Title
																	   FROM 
																			[sStudent].[vStudentAcademic] A 
																			 INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
																			 INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
																	   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			DM.Title
																	   FROM 
																			sHrm.tEmployeeJobDetail EJD
																			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
																	   WHERE EmployeeId=QM.FromSourceId
																	   )			                                                   
			  
					   ELSE ''
					END AS Code  ,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
																	   FROM 
																			sStudent.tStudentMaster SM			                                                       
																	   WHERE Id=QM.FromSourceId 
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
																	   FROM 
																			sHrm.tEmployeeMaster EM
																	   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
																	   )			                                                   
			  
					   ELSE ''
					END AS Name,
					ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
					(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
		  FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			   -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
				LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
				INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
		  WHERE 
					((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
				AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((QM.Id=@rId) OR (@rId=0))
				--AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				--AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
				AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
				AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
				AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
				AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
				AND ((QM.Number=@rNumber) OR (@rNumber=0))
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0
				--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
				AND QCM.AssignedToId IN (1,3) 
				ORDER BY QM.CreatedDateTime DESC



		END

		ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
		BEGIN
			SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
			FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        
      UNION 
SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code  ,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC
		END
		
		 ELSE --For Other Users
		 BEGIN
			
			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        
      UNION 
SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code  ,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        ORDER BY QM.CreatedDateTime DESC
		 END
		 

--	SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ISNULL(EM.IsOtherUser,0) = 0
--		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        
--      UNION 
--SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code  ,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
--        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ISNULL(EM.IsOtherUser,0) = 0
--		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
--        ORDER BY QM.CreatedDateTime DESC
        
END

GO
ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
	@rSourceId bigint,
	@rSourceTypeId int=0,
	@rReceiptBookId int=0,
	@rReceiptId bigint=0,
	@rBatchId int,
	@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
	
	Select @lOrgGorupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @lOrgId
				
	DECLARE @lConfigValue nvarchar(50)
	--,@lOrgGroupBatchId int
	--SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM [sSetup].[tBatchMaster] WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
			,ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				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,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode, -- added for mantis 0026962 by Foram
				RBM.OrderIndex AS ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
			FROM 
				sFee.tFeeMaster FM
				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,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
					WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=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,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)
				AND CGM.IsObsolete = 0
			) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook,ReceiptBookOrderIndex
		ORDER BY CG.StartDate,CG.OrderIndex
	END
	ELSE
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
			,ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				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,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode, -- added for mantis 0026962 by Foram
				RBM.OrderIndex AS ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
			FROM 
				sFee.tFeeMaster FM
				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,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
						WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=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,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) 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 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 ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
		
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA
					ON FA.FeeSetupId=FS.Id AND 
					(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=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(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CGM.IsObsolete = 0
		  ) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook,ReceiptBookOrderIndex
		ORDER BY CG.StartDate,CG.OrderIndex
	END
END
GO
PRINT N'Altering Procedure [sFee].[pRptDepositAddReceiptGet]...';


GO
ALTER PROCEDURE [sFee].[pRptDepositAddReceiptGet] 
	 @rId BIGINT
	,@rOrgId INT
	,@rDepositHeadId INT
	,@rBatchId INT
	,@rOrgGroupId INT
	,@rOrgGroupBatchId INT = 0
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupId INT = 0
	DECLARE @lCurrencyCode NVARCHAR(20) = ''
	DECLARE @lIDConfigValue NVARCHAR(50) = ''

	SELECT @lIDConfigValue = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 308
		AND SourceId = @rOrgGroupId

	IF (@rOrgGroupId = 0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId
		FROM sFee.tDepositHeadMaster R
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id
		WHERE R.Id = @rDepositHeadId

		SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId)
	END
	ELSE
	BEGIN
		SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId)
	END

	SELECT DHM.Title AS DepositHeadName
		,DA.Id
		,DA.DepositHeadId
		,
		--DA.StudentId AS StudentId,  
		vSA.AcademicId AS AcademicId
		,DA.Amount
		,DA.DepositDate
		,DA.PayTypeId
		,PTM.Title AS PayType
		,DA.ChequeNo
		,DA.BankName
		,DA.Remark
		,DA.CreatedDateTime
		,vSA.RollNo
		,vSA.Code
		,vSA.Name AS StudentName
		,vSA.ClassName + ' - ' + vSA.DivisionName AS ClassDivisionName
		,OM.Id AS OrgId
		,OM.DisplayTitle AS OrganizationName
		,sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount, 0.00), 1, 2, OM.OrgGroupId) AS ReceiptAmountInWords
		,vSA.BatchName
		,@lCurrencyCode AS CurrencyCode
		,DA.DepositNumber AS DepositNumber
		,OI.CertificateHeaderA4 AS DepositHeaderA4
		,@lIDConfigValue AS DepositConfigValue
		,U.DisplayTitle As CreatedUserName
	FROM sStudent.vStudentAcademic vSA
	INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
	INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = DA.PayTypeId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	LEFT JOIN sSecurity.tUser U ON U.Id = DA.CreatedUserId
	WHERE
		--vSA.BatchId = @rBatchId   
		(
			vSA.OrgId = @rOrgId
			OR @rOrgId = 0
			)
		AND (
			DA.DepositHeadId = @rDepositHeadId
			OR @rDepositHeadId = 0
			)
		--AND ((DHM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
		AND (DA.Id = @rId)
		--AND DA.OrgGRoupBatchId=@rOrgGroupBatchId  
		AND vSA.OrgGRoupBatchId = @rOrgGroupBatchId
	ORDER BY DA.DepositDate
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pEmployeeGatePassGet]...';


GO
 
ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassGet]
      
   @rId int,
   @rOrgId int=0,
   @rFromGatePassDate datetime='',
   @rToGatePassDate datetime='',
   @rEntryModeStatusId smallint=0,
   @rCode nvarchar(20)='',
   @rOrgGroupId int=0,
   @rReportId int=0,
   @rStatusId int=0,
   @rUserSourceId bigint = 0
       
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			EG.GatePassTime,
			ISNULL(EG.ReturnGatePassTime,'') AS ReturnGatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			EI.EmployeePhoto,
			Remark,
			@GatePassConfig AS ConfigValue,
			ISNULL(EG.StatusId,0) as StatusId,
			SM1.Title as Status,
			ISNULL(EG.AssignEmployeeId,0) as AssignEmployeeId,
			CASE WHEN ISNULL(EG.AssignEmployeeId,0) = 0 THEN '' ELSE (SELECT FirstName+' '+MiddleName+' '+LastName FROM sHrm.tEmployeeMaster WHERE Id = EG.AssignEmployeeId) END AS AssignEmployeeName,
			ISNULL(EDM.Title,'') AS Designation,
			CASE WHEN EG.EntryModeStatusId = 582 THEN EG.GatePassTime
				 WHEN EG.EntryModeStatusId = 581 THEN EG.ReturnGatePassTime
				 ELSE '' END AS InTime,
			CASE WHEN EG.EntryModeStatusId = 582 THEN EG.ReturnGatePassTime
				 WHEN EG.EntryModeStatusId = 581 THEN EG.GatePassTime
				 ELSE '' END AS OutTime

		FROM 
		    sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sSecurity.tUser U	ON U.Id=EG.CreatedUserId
			--INNER JOIN sSecurity.tUserOrganization UO ON U.Id = @rUserId
		    LEFT JOIN  sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
			LEFT JOIN sCommon.tStatusMaster SM1 ON SM1.Id = EG.StatusId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId -- #Start Mantis : 0028596
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM	ON EDM.Id  = EJD.EmployeeDesignationId -- #Start Mantis : 0028596
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
		    AND ((EG.Id=@rId) OR (@rId=0))
			AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((EG.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((EG.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((EG.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((EM.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((ISNULL(EG.StatusId,0) = @rStatusId) OR (ISNULL(@rStatusId,-1) = -1 AND ISNULL(EG.StatusId,0) != 0))
			AND ((EG.EmployeeId = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
		ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END
GO
PRINT N'Altering Procedure [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0,
		   @rDepartmentId int=0,
		   @rClassId int=0,
		   @rDivisionId int=0
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,0)AS GatePassNo,
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo
		FROM
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SI.StudentId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeGenerateReport]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '',
	@rDOBToDate Date = '',
	@rDOJFromDate Date = '',
	@rDOJToDate Date = '',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rIsCommonForOrg bit,
	@rLeftFromDate Date = '',
	@rLeftToDate Date = '',
	@rNumber int,
	@rProbationUptoDate Date = '',
	@rAhdocUptoDate Date = '',
	@rPermanentDate Date = '',
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate=''
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate=''
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate=''
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate=''
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate=''
	IF(@rLeftToDate ='9999-12-31 00:00:00')
		SET @rLeftToDate=''

	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	
		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tEmployeeCustomSearch
			(
				Id,Title,ColumnName,OrgId,Code,FirstName,LastName,EmployeeTypeId,StatusId,OrganizationDepartmentId,ReligionId,
				MaritalStatusId,Qualification,GenderId,EmployeeDesignationId,BloodGroupId,DOBFromDate,DOBToDate,DOJFromDate,
				DOJToDate,IsCommon,CreatedUserId,CreatedDateTime,IsCommonForOrg,CustomTag,DropDownStatusId,OrderBy)
		VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrgId,@rCode,@rFirstName,@rLastName,@rEmployeeTypeId,@rStatusId,@rOrganizationDepartmentId,@rReligionId,
				@rMaritalStatusId,@rQualification,@rGenderId,@rEmployeeDesignationId,@rBloodGroupId,@rDOBFromDate,@rDOBToDate,@rDOJFromDate,
				@rDOJToDate,@rIsCommon,@rCreatedUserId,sCommon.fGetDate(),@rIsCommonForOrg,@rCustomTagId,@rDropDownStatusId,@rOrderBy)
			--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN

		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,					 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate,
				@rCustomTagId=CustomTag,
				@rDropDownStatusId=ISNULL(DropDownStatusId,0),
				@rOrderBy=ISNULL(OrderBy,'Code')
				
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee')
	 BEGIN		
		DROP Table sHrm.tTempEmployee
	 END
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee13')
		 BEGIN
			DROP Table sHrm.tTempEmployee13
		 END
	 IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEmployee
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id  AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		WHERE EM.OrgId = @rOrgId AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEmployee
	END

	--select * from sHrm.tTempEmployee
	
	 DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
			DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
			SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sHrm.tEmployeeCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--print @lAvailableEmployeeColumns
	        IF(@lAvailableEmployeeColumns IS NOT NULL)
	        BEGIN														
				set @query = 'SELECT  EmployeeId AS EmployeeId13 ,' + @lAvailableEmployeeColumns + ' into sHrm.tTempEmployee13 from 
					 (
						select PPE.FieldTitle,PP.EmployeeId,FieldData
						FROM
						sHrm.tEmployeeCustomFieldData PP 
							INNER JOIN sHrm.tEmployeeCustomFieldMaster PPE ON PPE.Id = PP.EmployeeCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = PP.EmployeeId										
							WHERE EM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableEmployeeColumns  + ')
					) p'
                execute(@query)

				SELECT  T13.*, ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress,ECS.PermanentDate
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				INNER JOIN sSetup.tOrganizationMaster OM ON ECS.OrgId = OM.Id			
				LEFT JOIN  sHrm.tTempEmployee13 T13 ON ECS.EmployeeId= T13.EmployeeId13
		
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (ISNULL(@rFirstName,'') = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(ISNULL(@rLastName,'') = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				--SELECT @sql

				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
				DROP Table sHrm.tTempEmployee13
		END
		ELSE
		BEGIN
				SELECT  ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress,ECS.PermanentDate
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				INNER JOIN sSetup.tOrganizationMaster OM ON ECS.OrgId = OM.Id	
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				
				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_Message()
	END CATCH	
		
END

GO
ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormSubmittedStudentListGet]...';


GO
ALTER PROCEDURE [sStudent].[pDigitalFormSubmittedStudentListGet]
	  
	 @rOrgGroupBatchId int,
	 @rDigitalFormId int,
	 @rPageIndex int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lPageSize int = 20	

	IF OBJECT_ID('tempdb..#tDigitalFormTable') IS NOT NULL DROP TABLE #tDigitalFormTable
	CREATE TABLE #tDigitalFormTable  
	(
		Id bigint identity,	
		SourceId Bigint,
		Code nvarchar(20),
		ClassDivision nvarchar(200),
		StudentName nvarchar(300),
		IsSubmitted bit, 
		SubmittedDate datetime,
		DivisionOrder smallint
	)

	Insert into #tDigitalFormTable
	SELECT
		DISTINCT A.AcademicId as SourceId, 
		A.Code as Code,
		A.ClassName+'-'+A.DivisionName as ClassDivision,
		A.Name as StudentName,
		convert(bit,(SELECT CASE WHEN DFS.AcademicId IS NOT NULL THEN 1 ELSE 0 END as IsSubmitted)) as IsSubmitted,
		ISNULL(CONVERT(NVARCHAR,DFS.CreatedDateTime,103),'') as SubmittedDate,
		A.DivisionOrder
	FROM
		sStudent.tDigitalForm DF		
		INNER JOIN (SELECT 
					   SD.Code,
					   DFS.DigitalFormId,
					   SD.AcademicId,
					   SD.ClassName,
					   SD.DivisionName,
					   SD.Name,
					   SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2003
					UNION ALL	
																			 			  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS 
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId
					WHERE 
						SD.StatusId = 1 AND  DFS.SourceTypeId = 2017

					UNION ALL		
															 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2016

					UNION ALL	
																 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS 
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2005

					UNION ALL		
															 			 				  
					SELECT 
						SD.Code,
						DFS.DigitalFormId,
						SD.AcademicId,
						SD.ClassName,
						SD.DivisionName,
						SD.Name,
						SD.DivisionOrder
					FROM 
						sStudent.tDigitalFormScope DFS  
						INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = DFS.SourceId AND SD.OrgGroupBatchId = @rOrgGroupBatchId 
					WHERE 
						SD.StatusId = 1 AND DFS.SourceTypeId = 2021)A ON DF.Id = A.DigitalFormId 
				LEFT JOIN sStudent.tDigitalFormStudent DFS ON DFS.DigitalFormId = DF.Id AND DFS.AcademicId = A.AcademicId
		WHERE
			DF.Id = @rDigitalFormId  
		ORDER BY
		A.DivisionOrder Asc

	Declare @lCount int = (Select Count(Id) from #tDigitalFormTable)
	
	select Id, SourceId, Code, ClassDivision , StudentName, IsSubmitted, SubmittedDate, DivisionOrder,@lCount As TotalRecords
	from #tDigitalFormTable 
	where Id between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)

	drop table #tDigitalFormTable
END
GO
PRINT N'Altering Procedure [sStudent].[pImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pImportStudent] @rOrgGroupId SMALLINT
	,@rOrgId SMALLINT
	,@rXmldoc [nvarchar] (max)
	,@rUserId BIGINT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rOperation INT = 0 --1 For Insert,2 For Update
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		DECLARE @lCount INT
		DECLARE @lInterrorCode INT
			,@intDoc INT
			,@lCode NVARCHAR(20)
			,@lNumber BIGINT
			,@lRegistrationNumber NVARCHAR(20)
			,@lFirstName NVARCHAR(100)
			,@lMiddleName NVARCHAR(100)
			,@lLastName NVARCHAR(100)
			,@lClassId INT
			,@lClass NVARCHAR(100)
			,@lDivisionId INT
			,@lDivision NVARCHAR(100)
			,@lRollNo INT
			,@lAdmissionStandardId INT
			,@lAdmissionStandard NVARCHAR(100)
			,@lAdmissionDate DATE
			,@lPreviousSchool NVARCHAR(200)
			,@lDOB DATE
			,@lGenderId INT = 0
			,@lGender NVARCHAR(10)
			,@lBloodGroupId INT = 0
			,@lBloodGroup NVARCHAR(10)
			,@lAdmissionCategoryId INT
			,--@lAdmissionCategory nvarchar(100),
			@lReligionId INT
			,@lReligion NVARCHAR(100)
			,@lFamilyCast NVARCHAR(100)
			,@lFamilySubCast NVARCHAR(100)
			,@lCastCategoryId INT = 0
			,@lCastCategory NVARCHAR(100)
			,@lParentContactNo NVARCHAR(20)
			,@lParentEmail NVARCHAR(50)
			,@lStudentContactNo NVARCHAR(20)
			,@lStudentEmail NVARCHAR(50)
			,@lPresentStreetOne NVARCHAR(150)
			,@lPresentStreetTwo NVARCHAR(150)
			,@lPresentStreetThree NVARCHAR(150)
			,@lPresentCity NVARCHAR(50)
			,@lPresentZipCode NVARCHAR(20)
			,@lPresentState NVARCHAR(50)
			,@lPresentCountry NVARCHAR(50)
			,@lPresentContactNo NVARCHAR(20)
			,
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo NVARCHAR(20)
			,@lBirthPlace NVARCHAR(150)
			,@lBirthTaluka NVARCHAR(150)
			,@lBirthDistrict NVARCHAR(150)
			,@lBirthDateInWord NVARCHAR(150)
			,@lHouseId INT
			,@lHouse NVARCHAR(100)
			,
			--@lMotherTongueId int,
			@lMotherTongue NVARCHAR(100)
			,@lAdhaarNumber NVARCHAR(20)
			,@lUIDNumber NVARCHAR(50)
			,@lQuotaId INT
			,@lQuota NVARCHAR(100)
			,
			-- New Add
			@lSUId NVARCHAR(50)
			,@lLeftStandardId INT
			,@lLeftStandard NVARCHAR(100)
			,@lLeftDate DATE
			,@lLCNumber NVARCHAR(20)
			,@lLCDate DATE
			,@lLCReason NVARCHAR(200)
			,@lLCProgress NVARCHAR(200)
			,@lLCConduct NVARCHAR(200)
			,@lLCRemark NVARCHAR(200)
			,@lStatusId SMALLINT
			,@lBirthState NVARCHAR(100)
			,@lBirthCountry NVARCHAR(100)
			,@lAcademicId BIGINT
			,@lPreviousStandard NVARCHAR(100)
			,@lWhatsAppContactNo NVARCHAR(20)
			,@lTribeId INT = 0
			,@lTribe NVARCHAR(100)
			,@lPreviousLeftDate DATE
		DECLARE @EmployeeId BIGINT
		--DECLARE @OutClassId int
		--DECLARE @OutDivisionId int
		DECLARE @OutStudentId BIGINT

		--DECLARE @OutAdmissionStandardId int
		--DECLARE @OutReligionId int
		--DECLARE @OutAdmissionCategoryId int		
		SET @lAdmissionCategoryId = sCommon.fGetIntIdForOrg(1, @rOrgGroupId)

		DECLARE @1StudentId BIGINT = 0

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT
			,@rXmlDoc

		CREATE TABLE #tTable (
			Id BIGINT identity
			,Code NVARCHAR(20)
			,Number BIGINT
			,RegistrationNumber NVARCHAR(20)
			,FirstName NVARCHAR(100)
			,MiddleName NVARCHAR(100)
			,LastName NVARCHAR(100)
			,ClassId INT NULL
			,Class NVARCHAR(100)
			,DivisionId INT NULL
			,Division NVARCHAR(100)
			,RollNo INT
			,AdmissionStandardId INT
			,AdmissionStandard NVARCHAR(100)
			,AdmissionDate DATE
			,PreviousSchool NVARCHAR(200)
			,DOB DATE
			,GenderId INT NULL
			,Gender NVARCHAR(10)
			,BloodGroupId INT NULL
			,BloodGroup NVARCHAR(10)
			,ReligionId INT
			,Religion NVARCHAR(100)
			,
			--AdmissionCategoryId int,
			--AdmissionCategory nvarchar(100),
			FamilyCast NVARCHAR(100)
			,FamilySubCast NVARCHAR(100)
			,CastCategoryId INT
			,CastCategory NVARCHAR(100)
			,ParentContactNo NVARCHAR(20)
			,ParentEmail NVARCHAR(50)
			,StudentContactNo NVARCHAR(20)
			,StudentEmail NVARCHAR(50)
			,PresentStreetOne NVARCHAR(150)
			,PresentStreetTwo NVARCHAR(150)
			,PresentStreetThree NVARCHAR(150)
			,PresentCity NVARCHAR(50)
			,PresentZipCode NVARCHAR(20)
			,PresentState NVARCHAR(50)
			,PresentCountry NVARCHAR(50)
			,PresentContactNo NVARCHAR(20)
			,
			--EmergencyStreetOne nvarchar(50),
			--EmergencyStreetTwo nvarchar(50),
			--EmergencyStreetThree nvarchar(50),
			--EmergencyCountry nvarchar(50),
			--EmergencyState nvarchar(50),
			--EmergencyCity nvarchar(50),
			--EmergencyZipCode nvarchar(20),
			EmergencyContactNo NVARCHAR(20)
			,BirthPlace NVARCHAR(150)
			,BirthTaluka NVARCHAR(150)
			,BirthDistrict NVARCHAR(150)
			,BirthDateInWord NVARCHAR(150)
			,CreatedUserId BIGINT
			,HouseId INT
			,House NVARCHAR(100)
			,MotherTongueId INT
			,MotherTongue NVARCHAR(100)
			,AdhaarNumber NVARCHAR(20)
			,UIDNumber NVARCHAR(50)
			,QuotaId INT
			,Quota NVARCHAR(100)
			,SUId NVARCHAR(50)
			,LeftStandardId INT
			,LeftStandard NVARCHAR(100)
			,LeftDate DATE
			,LCNumber NVARCHAR(20)
			,LCDate DATE
			,LCReason NVARCHAR(200)
			,LCProgress NVARCHAR(200)
			,LCConduct NVARCHAR(200)
			,LCRemark NVARCHAR(200)
			,StatusId SMALLINT
			,BirthState NVARCHAR(100)
			,BirthCountry NVARCHAR(100)
			,PreviousStandard NVARCHAR(100)
			,WhatsAppContactNo NVARCHAR(20)
			,TribeId INT NULL
			,Tribe NVARCHAR(100)
			,PreviousLeftDate DATE
			)

		INSERT INTO #tTable (
			Code
			,Number
			,RegistrationNumber
			,FirstName
			,MiddleName
			,LastName
			,ClassId
			,Class
			,DivisionId
			,Division
			,RollNo
			,AdmissionStandardId
			,AdmissionStandard
			,AdmissionDate
			,PreviousSchool
			,DOB
			,GenderId
			,Gender
			,BloodGroupId
			,BloodGroup
			,ReligionId
			,Religion
			,
			--AdmissionCategoryId,
			--AdmissionCategory,
			FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,PresentStreetOne
			,PresentStreetTwo
			,PresentStreetThree
			,PresentCity
			,PresentZipCode
			,PresentState
			,PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,BirthPlace
			,BirthTaluka
			,BirthDistrict
			,BirthDateInWord
			,CreatedUserId
			,HouseId
			,House
			,MotherTongueId
			,MotherTongue
			,AdhaarNumber
			,UIDNumber
			,QuotaId
			,Quota
			,SUId
			,LeftStandardId
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,LCReason
			,LCProgress
			,LCConduct
			,LCRemark
			,StatusId
			,BirthState
			,BirthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,TribeId
			,Tribe
			,PreviousLeftDate
			)
		SELECT Code
			,Number
			,RegistrationNumber
			,sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName
			,sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName
			,sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division
			,RollNo
			,0
			,AdmissionStandard
			,AdmissionDate
			,sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool
			,DOB
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender
			,0
			,BloodGroup
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion
			,
			--0,
			--AdmissionCategory,
			sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast
			,sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity
			,PresentZipCode
			,sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace
			,sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord
			,CreatedUserId
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(House) AS House
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue
			,sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber
			,UIDNumber
			,0
			,Quota
			,SUId
			,0
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason
			,LCProgress
			,LCConduct
			,sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark
			,StatusId
			,sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState
			,sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,0
			,Tribe
			,PreviousLeftDate
		FROM OPENXML(@intDoc, '/Table/ImportStudent', 1) WITH (
				Code NVARCHAR(20) '@Code'
				,Number BIGINT '@Number'
				,RegistrationNumber NVARCHAR(20) '@RegistrationNumber'
				,FirstName NVARCHAR(100) '@FirstName'
				,MiddleName NVARCHAR(100) '@MiddleName'
				,LastName NVARCHAR(100) '@LastName'
				,Class NVARCHAR(100) '@Class'
				,Division NVARCHAR(100) '@Division'
				,RollNo INT '@RollNo'
				,AdmissionStandard NVARCHAR(100) '@AdmissionStandard'
				,AdmissionDate DATE '@AdmissionDate'
				,PreviousSchool NVARCHAR(200) '@PreviousSchool'
				,DOB DATE '@DOB'
				,Gender NVARCHAR(10) '@Gender'
				,BloodGroup NVARCHAR(10) '@BloodGroup'
				,Religion NVARCHAR(100) '@Religion'
				,
				--AdmissionCategory nvarchar(100) '@AdmissionCategory',
				FamilyCast NVARCHAR(100) '@FamilyCast'
				,FamilySubCast NVARCHAR(100) '@FamilySubCast'
				,CastCategory NVARCHAR(100) '@CastCategory'
				,ParentContactNo NVARCHAR(20) '@ParentContactNo'
				,ParentEmail NVARCHAR(50) '@ParentEmail'
				,StudentContactNo NVARCHAR(20) '@StudentContactNo'
				,StudentEmail NVARCHAR(50) '@StudentEmail'
				,PresentStreetOne NVARCHAR(150) '@PresentStreetOne'
				,PresentStreetTwo NVARCHAR(150) '@PresentStreetTwo'
				,PresentStreetThree NVARCHAR(150) '@PresentStreetThree'
				,PresentCity NVARCHAR(50) '@PresentCity'
				,PresentZipCode NVARCHAR(20) '@PresentZipCode'
				,PresentState NVARCHAR(50) '@PresentState'
				,PresentCountry NVARCHAR(50) '@PresentCountry'
				,PresentContactNo NVARCHAR(20) '@PresentContactNo'
				,
				--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
				--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
				--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
				--EmergencyCountry nvarchar(50) '@EmergencyCountry',
				--EmergencyState nvarchar(50) '@EmergencyState',
				--EmergencyCity nvarchar(50) '@EmergencyCity',
				--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
				EmergencyContactNo NVARCHAR(20) '@EmergencyContactNo'
				,BirthPlace NVARCHAR(150) '@BirthPlace'
				,BirthTaluka NVARCHAR(150) '@BirthTaluka'
				,BirthDistrict NVARCHAR(150) '@BirthDistrict'
				,BirthDateInWord NVARCHAR(150) '@BirthDateInWord'
				,CreatedUserId BIGINT '@CreatedUserId'
				,House NVARCHAR(100) '@House'
				,MotherTongue NVARCHAR(100) '@MotherTongue'
				,AdhaarNumber NVARCHAR(20) '@AdhaarNumber'
				,UIDNumber NVARCHAR(50) '@UIDNumber'
				,Quota NVARCHAR(20) '@Quota'
				,SUId NVARCHAR(50) '@SUId'
				,LeftStandard NVARCHAR(100) '@LeftStandard'
				,LeftDate DATE '@LeftDate'
				,LCNumber NVARCHAR(20) '@LCNumber'
				,LCDate DATE '@LCDate'
				,LCReason NVARCHAR(200) '@LCReason'
				,LCProgress NVARCHAR(200) '@LCProgress'
				,LCConduct NVARCHAR(200) '@LCConduct'
				,LCRemark NVARCHAR(200) '@LCRemark'
				,StatusId SMALLINT '@StatusId'
				,BirthState NVARCHAR(100) '@BirthState'
				,BirthCountry NVARCHAR(100) '@BirthCountry'
				,PreviousStandard NVARCHAR(100) '@PreviousStandard'
				,WhatsAppContactNo NVARCHAR(20) '@WhatsAppContactNo'
				,Tribe NVARCHAR(100) '@Tribe'
				,PreviousLeftDate DATE '@PreviousLeftDate'
				)

		EXEC sp_xml_removedocument @intDoc

		SELECT @lCount = COUNT(Id)
		FROM #tTable

		WHILE @lCount > 0
		BEGIN
			SET @lCode = ''
			SET @lNumber = NULL
			SET @lRegistrationNumber = NULL
			SET @lFirstName = ''
			SET @lMiddleName = ''
			SET @lLastName = ''
			SET @lClassId = NULL
			SET @lClass = ''
			SET @lDivisionId = NULL
			SET @lDivision = ''
			SET @lRollNo = NULL
			SET @lAdmissionStandardId = NULL
			SET @lAdmissionStandard = ''
			SET @lAdmissionDate = ''
			SET @lPreviousSchool = ''
			SET @lDOB = ''
			SET @lGenderId = NULL
			SET @lGender = ''
			SET @lBloodGroupId = NULL
			SET @lBloodGroup = ''
			SET @lReligionId = NULL
			SET @lReligion = ''
			--SET @lAdmissionCategoryId  = null
			--SET @lAdmissionCategory = ''
			SET @lFamilyCast = ''
			SET @lFamilySubCast = ''
			SET @lCastCategoryId = NULL
			SET @lCastCategory = ''
			SET @lParentContactNo = ''
			SET @lParentEmail = ''
			SET @lStudentContactNo = ''
			SET @lStudentEmail = ''
			SET @lPresentStreetOne = ''
			SET @lPresentStreetTwo = ''
			SET @lPresentStreetThree = ''
			SET @lPresentCity = ''
			SET @lPresentZipCode = ''
			SET @lPresentState = ''
			SET @lPresentCountry = ''
			SET @lPresentContactNo = ''
			--SET @lEmergencyStreetOne = ''
			--SET @lEmergencyStreetTwo = ''
			--SET @lEmergencyStreetThree = ''
			--SET @lEmergencyCountry = ''
			--SET @lEmergencyState = ''
			--SET @lEmergencyCity = ''
			--SET @lEmergencyZipCode = ''
			SET @lEmergencyContactNo = ''
			SET @lBirthPlace = ''
			SET @lBirthTaluka = ''
			SET @lBirthDistrict = ''
			SET @lBirthDateInWord = ''
			--SET @OutClassId = null
			--SET @OutDivisionId = null
			SET @OutStudentId = NULL
			--SET @OutAdmissionStandardId = null
			--SET @OutReligionId = null,
			SET @lHouseId = NULL
			SET @lHouse = ''
			--SET @lMotherTongueId=NULL
			SET @lMotherTongue = ''
			SET @lAdhaarNumber = ''
			SET @lUIDNumber = ''
			SET @lQuotaId = NULL
			SET @lQuota = ''
			SET @lSUId = ''
			SET @lLeftStandardId = NULL
			SET @lLeftStandard = ''
			SET @lLeftDate = ''
			SET @lLCNumber = ''
			SET @lLCDate = ''
			SET @lLCReason = ''
			SET @lLCProgress = ''
			SET @lLCConduct = ''
			SET @lLCRemark = ''
			SET @lStatusId = NULL
			SET @lBirthState = ''
			SET @lBirthCountry = ''
			SET @lPreviousStandard = ''
			SET @lWhatsAppContactNo = ''
			SET @lTribeId = NULL
			SET @lTribe = ''
			SET @lPreviousLeftDate = ''

			SELECT @lCode = Code
				,@lNumber = Number
				,@lRegistrationNumber = RegistrationNumber
				,@lFirstName = FirstName
				,@lMiddleName = MiddleName
				,@lLastName = LastName
				,@lClass = Class
				,@lDivision = Division
				,@lRollNo = RollNo
				,@lAdmissionStandard = AdmissionStandard
				,@lAdmissionDate = CASE 
					WHEN AdmissionDate = ''
						THEN NULL
					ELSE AdmissionDate
					END
				,@lPreviousSchool = PreviousSchool
				,@lReligion = Religion
				,
				--@lAdmissionCategory = AdmissionCategory,
				@lFamilyCast = FamilyCast
				,@lFamilySubCast = FamilySubCast
				,@lCastCategory = CastCategory
				,@lDOB = CASE 
					WHEN DOB = ''
						THEN NULL
					ELSE DOB
					END
				,@lGender = Gender
				,@lBloodGroup = BloodGroup
				,@lParentContactNo = ParentContactNo
				,@lParentEmail = ParentEmail
				,@lStudentContactNo = StudentContactNo
				,@lStudentEmail = StudentEmail
				,@lPresentStreetOne = PresentStreetOne
				,@lPresentStreetTwo = PresentStreetTwo
				,@lPresentStreetThree = PresentStreetThree
				,@lPresentCountry = PresentCountry
				,@lPresentState = PresentState
				,@lPresentCity = PresentCity
				,@lPresentZipCode = PresentZipCode
				,@lPresentContactNo = PresentContactNo
				,
				--@lEmergencyStreetOne = EmergencyStreetOne,
				--@lEmergencyStreetTwo = EmergencyStreetTwo,
				--@lEmergencyStreetThree = EmergencyStreetThree,
				--@lEmergencyCountry = EmergencyCountry,
				--@lEmergencyState = EmergencyState,
				--@lEmergencyCity = EmergencyCity,
				--@lEmergencyZipCode = EmergencyZipCode,
				@lEmergencyContactNo = EmergencyContactNo
				,@lBirthPlace = BirthPlace
				,@lBirthTaluka = BirthTaluka
				,@lBirthDistrict = BirthDistrict
				,@lBirthDateInWord = BirthDateInWord
				,@lHouse = House
				,@lMotherTongue = MotherTongue
				,@lAdhaarNumber = AdhaarNumber
				,@lUIDNumber = UIDNumber
				,@lSUId = SUId
				,@lLeftStandard = LeftStandard
				,@lLeftDate = CASE 
					WHEN LeftDate = ''
						THEN NULL
					ELSE LeftDate
					END
				,@lLCNumber = LCNumber
				,@lLCDate = CASE 
					WHEN LCDate = ''
						THEN NULL
					ELSE LCDate
					END
				,@lLCReason = LCReason
				,@lLCProgress = LCProgress
				,@lLCConduct = LCConduct
				,@lLCRemark = LCRemark
				,@lStatusId = StatusId
				,@lBirthState = BirthState
				,@lBirthCountry = BirthCountry
				,@lPreviousStandard = PreviousStandard
				,@lWhatsAppContactNo = WhatsAppContactNo
				,@lTribe = Tribe
				,@lPreviousLeftDate = CASE 
					WHEN PreviousLeftDate = ''
						THEN NULL
					ELSE PreviousLeftDate
					END
			FROM #tTable
			WHERE Id = @lCount

			SELECT @lGenderId = ID
			FROM sCommon.tGenderMaster
			WHERE Title = @lGender

			SELECT @lLeftStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lLeftStandard
				AND OrgId = @rOrgId

			SELECT @lClassId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lClass
				AND OrgId = @rOrgId

			SELECT @lDivisionId = ID
			FROM sSetup.tDivisionMaster
			WHERE Title = @lDivision
				AND ClassId = @lClassId
				AND OrgId = @rOrgId

			SELECT @lBloodGroupId = ID
			FROM sCommon.tBloodGroupMaster
			WHERE Title = @lBloodGroup

			SELECT @lAdmissionStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lAdmissionStandard
				AND OrgId = @rOrgId

			SELECT @lReligionId = ID
			FROM sCommon.tReligionMaster
			WHERE Title = @lReligion
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
			SELECT @lCastCategoryId = ID
			FROM sCommon.tCastCategoryMaster
			WHERE Title = @lCastCategory
				AND OrgGroupId = @rOrgGroupId

			SELECT @lHouseId = ID
			FROM sActivity.tHouseMaster
			WHERE Title = @lHouse
				AND OrgId = @rOrgId

			SELECT @lQuotaId = ID
			FROM sCommon.tQuotaMaster
			WHERE Title = @lQuota
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
			SELECT @lTribeId = ID
			FROM sCommon.tTribeMaster
			WHERE Title = @lTribe

			PRINT (@lTribeId)

			IF (@lGenderId IS NULL)
				SET @lGenderId = 0

			IF (@lBloodGroupId IS NULL)
				SET @lBloodGroupId = 0

			IF (@lCastCategoryId IS NULL)
				SET @lCastCategoryId = 0

			IF (@lHouseId IS NULL)
				SET @lHouseId = 0

			IF (@lQuotaId IS NULL)
				SET @lQuotaId = 0

			IF (@lTribeId IS NULL)
				SET @lTribeId = 0

			--IF(@lMotherTongueId IS NULL)
			--	SET	@lMotherTongueId = 0		
			--IF 	@lClassId IS NULL  AND @lClass != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutClassId = @lClassId
			--END
			--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionStandardId = @lAdmissionStandardId
			--END
			--IF 	@lDivisionId IS NULL  AND @lDivision != ''
			--BEGIN
			--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
			--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutDivisionId = @lDivisionId
			--END
			--IF 	@lReligionId IS NULL  AND @lReligion != ''
			--BEGIN
			--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutReligionId = @lReligionId
			--END
			--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
			--BEGIN
			--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
			--END
			BEGIN TRANSACTION

			DECLARE @lStudCap INT
				,@lOrgStudentCap INT

			SELECT @lStudCap = ISNULL(NoOfStudent, 0) + ISNULL(StudentExtraCap, 0)
			FROM sSetup.tOrgGroupSetting
			WHERE OrgGroupId = @rOrgGroupId

			SELECT @lOrgStudentCap = [sSetup].[fStudentCapGet](@rOrgGroupBatchId)

			IF (@lOrgStudentCap >= @lStudCap)
			BEGIN
				SELECT - 111 AS RESULT

				COMMIT TRANSACTION

				RETURN
			END

			IF (
					@rOperation = 1
					OR @rOperation = 0
					)
			BEGIN
				IF (@lStatusId = 1)
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,1
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
				ELSE
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,3
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId

				EXEC sStudent.pAcademicAdd 0
					,@OutStudentId
					,@lClassId
					,@lDivisionId
					,@lRollNo
					,@rOrgId
					,@rBatchId
					,@rUserId
					,@rUserId
					,@lAdmissionCategoryId
					,1

				EXEC sStudent.pStudentCommunicationAdd @OutStudentId
					,@lPresentStreetOne
					,@lPresentStreetTwo
					,@lPresentStreetThree
					,@lPresentCountry
					,@lPresentState
					,@lPresentCity
					,@lPresentZipCode
					,@lPresentContactNo
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lEmergencyContactNo
					,@lParentContactNo
					,@lParentEmail
					,@lStudentContactNo
					,@lStudentEmail
					,@rUserId
					,@rUserId
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lWhatsAppContactNo

				EXEC sStudent.pStudentOtherAdd @OutStudentId
					,@lUIDNumber
					,@lDOB
					,@lGenderId
					,@lReligionId
					,@lBloodGroupId
					,@lBirthPlace
					,@lBirthTaluka
					,@lBirthDistrict
					,@lBirthDateInWord
					,@lFamilyCast
					,@lFamilySubCast
					,@lCastCategoryId
					,NULL
					,@lHouseId
					,NULL
					,NULL
					,''
					,@rUserId
					,@rUserId
					,''
					,@lAdhaarNumber
					,@lMotherTongue
					,@lQuotaId
					,@lBirthState
					,@lBirthCountry
					,@rBatchId
					,@lTribeId

				IF (@lStatusId = 1)
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,1
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
				ELSE
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,@lLeftStandardId
						,@lLeftDate
						,NULL
						,NULL
						,NULL
						,@lLCReason
						,@lLCProgress
						,@lLCConduct
						,NULL
						,@lLCNumber
						,@lLCDate
						,@lLCRemark
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,0
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
			END
			ELSE
			BEGIN
				SET @1StudentId = (
						SELECT Id
						FROM sStudent.tStudentMaster
						WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT
							AND OrgId = @rOrgId
						)

				UPDATE sStudent.tStudentMaster
				SET RegistrationNumber = @lRegistrationNumber
					,FirstName = @lFirstName
					,MiddleName = @lMiddleName
					,LastName = @lLastName
					,SUId = @lSUId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE Id = @1StudentId

				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @lAdmissionStandardId
					,AdmissionDate = @lAdmissionDate
					,PreviousSchool = @lPreviousSchool
					,LeftStandardId = @lLeftStandardId
					,LeftDate = @lLeftDate
					,LCNumber = @lLCNumber
					,LCDate = @lLCDate
					,LCRemark = @lLCRemark
					,LCConduct = @lLCConduct
					,LCProgress = @lLCProgress
					,LeftReason = @lLCReason
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,PreviousStandard = @lPreviousStandard
					,PreviousLeftDate = @lPreviousLeftDate
				WHERE StudentId = @1StudentId

				UPDATE sStudent.tStudentOther
				SET DateOfBirth = @lDOB
					,GenderId = @lGenderId
					,BloodGroupId = @lBloodGroupId
					,ReligionId = @lReligionId
					,FamilyCast = @lFamilyCast
					,FamilySubCast = @lFamilySubCast
					,CastCategoryId = @lCastCategoryId
					,BirthPlace = @lBirthPlace
					,BirthTaluka = @lBirthTaluka
					,BirthDistrict = @lBirthDistrict
					,BirthState = @lBirthState
					,BirthCountry = @lBirthCountry
					,AdhaarNumber = @lAdhaarNumber
					,MotherTongue = @lMotherTongue
					,QuotaId = @lQuotaId
					,UIDNumber = @lUIDNumber
					,HouseId = @lHouseId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,TribeId = @lTribeId
				WHERE StudentId = @1StudentId

				IF (@lDivisionId IS NOT NULL)
				BEGIN
					UPDATE sStudent.tAcademic
					SET DivisionId = @lDivisionId
						,RollNo = @lRollNo
						,UpdatedUserId = @rUserId
						,UpdatedDateTime = getdate()
					WHERE StudentId = @1StudentId
						AND BatchId = @rBatchId
						AND OrgId = @rOrgId
				END

				UPDATE sStudent.tStudentCommunication
				SET PresentStreetOne = @lPresentStreetOne
					,PresentStreetTwo = @lPresentStreetTwo
					,PresentStreetThree = @lPresentStreetThree
					,PresentCountry = @lPresentCountry
					,PresentState = @lPresentState
					,PresentCity = @lPresentCity
					,PresentZipCode = @lPresentZipCode
					,PresentContactNo = @lPresentContactNo
					,EmergencyContactNo = @lEmergencyContactNo
					,ParentContactNo = @lParentContactNo
					,ParentEmail = @lParentEmail
					,StudentContactNo = @lStudentContactNo
					,StudentEmail = @lStudentEmail
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE StudentId = @1StudentId
			END

			SET @lCount = @lCount - 1

			COMMIT TRANSACTION
		END

		SELECT 1
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT ERROR_MESSAGE()
			,ERROR_LINE()
	END CATCH
END
GO
PRINT N'Altering Procedure [sTimetable].[pRptDivisionTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date='',
	  @rOrgId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN 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) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN 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) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject,
	'' AS EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak ,
	'' AS SubjectEmployeeSN			--add for 27992 mantis

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT	
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND TT.EmployeeId <> 0
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak,
	0 AS IsBreakBefore,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject ,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
  BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge,
	A.EmployeeSubject,
	'' as ClassSubject,
	'' AS SubjectEmployeeSN		--add for 27992 mantis
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN 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) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN 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) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	'' AS EmployeeSubject,
	ClassSubject,
	'' AS SubjectEmployeeSN		--add for 27992 mantis
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(EM.FirstName,'') , ISNULL(EM.MiddleName,''), ISNULL(EM.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'<br><b>'+SM1.Title+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN 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) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN 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) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak,
	A.SubjectEmployeeSN			--add for 27992 mantis
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)) ,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName+'<br><b>' +SM1.Code+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, '')) ClassSubject,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.ShortName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSNSubject,

	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Title+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectEmployeeSN			--add for 27992 mantis

	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering Procedure [sTransport].[pSendAlertDropPointGet]...';


GO

ALTER PROCEDURE [sTransport].[pSendAlertDropPointGet]
	 	 
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int,
		 @rTransportId int,
		 @rOrgGroupId int,
		 @rTemplate nvarchar(max),
		 @rCode nvarchar(max),
		 @rDropDestinationId int = 0,
		 @rDropDestinationIds nvarchar(max)='' --add for mantis:28792
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	Select 
			OM.Title As OrganizationName,
			SC.AcademicId,			
			SC.Code,
			SC.RollNo,
			SC.Name AS StudentName,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM1.Title,'')),
			'[PickupTime]',isnull(BRDM1.PickupTime,'')),
			'[DropTime]',isnull(BRDM1.DropTime,''))
			 AS Template,
			 SC.OrgId,
			 SC.OrgGroupId,
			 SC.StudentId AS SourceId,
			 2003 AS SourceTypeId,	 
			 SC.StudentId AS ReceiverSourceId,
			 2003 AS ReceiverSourceTypeId,
			 replace (
			 replace (
			 replace (
			 replace (
			 replace (
			 replace (
			 replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			 '[Class]',isnull(SC.ClassName,'')),
			 '[Division]',isnull(SC.DivisionName,'')),
			 '[BusRoute]',isnull(BRM.Title,'')),
			 '[PickupPoint]',isnull(BRDM1.Title,'')),
			 '[PickupTime]',isnull(BRDM1.PickupTime,'')),
			 '[DropTime]',isnull(BRDM1.DropTime,''))
			 AS MsgText,
			 'Bus Route' AS Subject			
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=BRM.OrgGroupId AND OM.Id=SC.OrgId
		INNER JOIN sTransport.tTransportMaster TM ON TM.Id=BRM.TransportId
		LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.PickupDestinationId
	WHERE		
		(SC.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.BusRouteId=@rBusRouteId OR (ISNULL(@rBusRouteId,0)=0))
		AND (BRDM.OrgGroupId=@rOrgGroupId)
		AND (SC.Code IN(SELECT Item FROM sCommon.fnSplit(@rCode, ','))OR (ISNULL(@rCode,'')=''))
		AND (AR.DropDestinationId = @rDropDestinationId OR @rDropDestinationId = 0)
		AND (AR.DropDestinationId IN(SELECT Item FROM sCommon.fnSplit(@rDropDestinationIds, ','))OR (ISNULL(@rDropDestinationIds,'')=''))
	ORDER BY SC.OrgId ASC
END
GO
PRINT N'Altering Procedure [sTransport].[pSendAlertPickUpPointGet]...';


GO
ALTER PROCEDURE [sTransport].[pSendAlertPickUpPointGet]
	 	 
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int,
		 @rTransportId int,
		 @rOrgGroupId int,
		 @rTemplate nvarchar(max),
		 @rCode nvarchar(max),
		 @rPickUpDestinationId int = 0,
		 @rPickUpDestinationIds nvarchar(max)='' --add for mantis:28792
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	Select 
			OM.Title As OrganizationName,
			SC.AcademicId,			
			SC.Code,
			SC.RollNo,
			SC.Name AS StudentName,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template,
			 SC.OrgId,
			 SC.OrgGroupId,
			 SC.StudentId AS SourceId,
			 2003 AS SourceTypeId,	 
			 SC.StudentId AS ReceiverSourceId,
			 2003 AS ReceiverSourceTypeId,
			 replace (
			 replace (
			 replace (
			 replace (
			 replace (
			 replace (
			 replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			 '[Class]',isnull(SC.ClassName,'')),
			 '[Division]',isnull(SC.DivisionName,'')),
			 '[BusRoute]',isnull(BRM.Title,'')),
			 '[PickupPoint]',isnull(BRDM.Title,'')),
			 '[PickupTime]',isnull(BRDM.PickupTime,'')),
			 '[DropTime]',isnull(BRDM.DropTime,''))
			 AS MsgText,
			 'Bus Route' AS Subject			
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId	AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=BRM.OrgGroupId AND OM.Id=SC.OrgId
		INNER JOIN sTransport.tTransportMaster TM ON TM.Id=BRM.TransportId
	WHERE		
		(SC.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.BusRouteId=@rBusRouteId OR (ISNULL(@rBusRouteId,0)=0))
		AND (BRDM.OrgGroupId=@rOrgGroupId)
		--AND ((SC.Code IN(@rCode)) OR (ISNULL(@rCode,'')=''))
		AND (SC.Code IN(SELECT Item FROM sCommon.fnSplit(@rCode, ','))OR (ISNULL(@rCode,'')=''))
		AND (AR.PickupDestinationId = @rPickUpDestinationId OR @rPickUpDestinationId = 0)
		AND (AR.PickupDestinationId IN(SELECT Item FROM sCommon.fnSplit(@rPickUpDestinationIds, ','))OR (ISNULL(@rPickUpDestinationIds,'')=''))
	order by SC.OrgId ASC
END
GO
PRINT N'Altering Procedure [sTransport].[pTransportStudentList]...';


GO
ALTER PROCEDURE [sTransport].[pTransportStudentList]
           
	 @rOrgId int,	 
	 @rTransportId int,
	 @rBusRouteId int,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rBusRouteDestination nvarchar(100) = '',	 
	 @rPickUpId int	 

WITH EXECUTE AS CALLER	 
AS
SET NOCOUNT ON

IF(@rPickUpId!=0 AND @rBusRouteDestination='')
BEGIN
SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,							
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo			
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
	
		
			END
			ELSE IF(@rPickUpId=0 AND @rBusRouteDestination!='')
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,									
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Title LIKE '%'+@rBusRouteDestination+'%') OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
			END
			
			ELSE IF(@rPickUpId!=0 AND @rBusRouteDestination!='')
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,					
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)))					
				AND BMM.IsInContext = 1				
				--order by SD.ClassId,SD.Suid,SD.Code
				UNION
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,				
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,	
				ISNULL(SC.ParentEmail,'') AS EMail,	
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId	
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Title LIKE '%'+@rBusRouteDestination+'%') OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				--order by SD.ClassId,SD.Suid,SD.Code
			END
			
			ELSE
			BEGIN
			SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,					
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,	
				ISNULL(SC.ParentEmail,'') AS EMail,	
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)) 
				AND ((BDM.Title=@rBusRouteDestination) OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
			END
GO
PRINT N'Altering Procedure [sWorkflow].[pWorkflowQueuesGet]...';


GO

ALTER  PROCEDURE [sWorkflow].[pWorkflowQueuesGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(20) ='',
			 @rDepartmentId int=0,
			 @rUserId bigint ,
			 @rApprovalRequestId int = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
Declare @lRoleId int
Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId
--Select @lRoleId
SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
	ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId AND AR.WorkflowFunctionalityId = FAA.WorkflowFunctionalityId
INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE R.Id = @lRoleId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode = '')))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

UNION

SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status,
	ISNULL(AA.ActionRemark, '') AS ActionRemark
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId AND AR.WorkflowFunctionalityId = FAA.WorkflowFunctionalityId
INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE U.Id = @rUserId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ISNULL(ASM.Id,3) = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode ='')))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

END
GO
PRINT N'Creating Procedure [sChatbot].[pChatbotAuditLogAdd]...';


GO


CREATE PROCEDURE [sChatbot].[pChatbotAuditLogAdd]
	   @rChannelId bigint,	
	   @rUserId bigint,
       @rQuestion nvarchar(max),
	   @rAnswer nvarchar(max)
	   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION
	 DECLARE @lChannelId bigint, @lChatId bigint
	 IF(@rChannelId = 0)
	 BEGIN
		
		INSERT INTO sChatbot.tChatbotAuditLog
           (
		    UserId
           ,CreatedDateTime
           )
		VALUES
			(
			 @rUserId,
			 sCommon.fGetDate()
			 )

		SET @lChannelId = @@Identity

		INSERT INTO sChatbot.tChatbotAuditLogDetail
           (
		    ChannelId
           ,Question
           ,Answer
           ,CreatedDateTime
           )
     VALUES
           (
		    @lChannelId
           ,@rQuestion
           ,@rAnswer
           ,sCommon.fGetDate()
           )
		SET @lChatId = @@Identity

		SELECT @lChannelId AS ChannelId, @lChatId AS ChatId
	 END
	 
	 ELSE
	 BEGIN
		INSERT INTO sChatbot.tChatbotAuditLogDetail
           (
		    ChannelId
           ,Question
           ,Answer
           ,CreatedDateTime
           )
       VALUES
           (
		    @rChannelId
           ,@rQuestion
           ,@rAnswer
           ,sCommon.fGetDate()
           )
		SET @lChatId = @@Identity
		SELECT @rChannelId AS ChannelId, @lChatId AS ChatId
	 END	
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sChatbot].[pChatbotFeedbackUpdate]...';


GO


CREATE PROCEDURE [sChatbot].[pChatbotFeedbackUpdate]
	   @rChannelId bigint,
       @rChatId bigint,
	   @rFeedback bit,
	   @rAnsFeedback bit,
	   @rDescription nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rChannelId > 0 AND @rChatId = 0)
BEGIN
	UPDATE sChatbot.tChatbotAuditLog SET Feedback = @rFeedback , Description = @rDescription , UpdatedDateTime = sCommon.fGetDate()
	WHERE ChannelId = @rChannelId

END
ELSE
BEGIN
	UPDATE sChatbot.tChatbotAuditLogDetail SET Feedback = @rAnsFeedback, UpdatedDateTime = sCommon.fGetDate()
	WHERE ChatId = @rChatId
END

END
GO
PRINT N'Creating Procedure [sAcademic].[pRptDailyStatusDetailGet]...';


GO
CREATE PROCEDURE [sAcademic].[pRptDailyStatusDetailGet]
	 @rBuilder1 nvarchar(max)='',
     @rSearchDate datetime,
     @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
     @rDate smallint,
	 @rAttendanceTypeId int=1,
	 @rAttendanceStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	 
 

	SELECT 		
			@rBuilder1 AS Builder1,
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](@rYear,@rMonth,@rDate,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime,
			[sCommon].[fGetUserNameforDailyStatus](A.DivisionId,@rSearchDate,@rAttendanceTypeId)AS UserName
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=@rSearchDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
					
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId
			Having (@rAttendanceStatusId=1 AND (COUNT(SR.AcademicId)=0 And (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0) )
				OR (@rAttendanceStatusId=2 and (COUNT(SR.AcademicId)<>0 OR (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0))<>0) )
				 OR ( @rAttendanceStatusId=0)	
            ORDER BY vCD.OrderIndex
END
GO
PRINT N'Creating Procedure [sAcademic].[pRptDailyStatusMonthlyDetailGet]...';


GO
CREATE PROCEDURE [sAcademic].[pRptDailyStatusMonthlyDetailGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rOrgId SMALLINT
	,@rBatchId BIGINT
	,@rYear SMALLINT
	,@rMonth SMALLINT
	--,@rDayOfMonth SMALLINT
	,@rAttendanceTypeId INT = 1
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF OBJECT_ID('tempdb..#TempDaysTempTable') IS NOT NULL
		DROP TABLE #TempDaysTempTable

	IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
		DROP TABLE #Temp

	DECLARE @Days INT
		,@lFromDate DATE
		,@lToDate DATE

	SELECT @Days = sCommon.fGetDaysInMonth(@rMonth, @rYear)

	SET @lFromDate = CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '-' + CONVERT(NVARCHAR(2), @rMonth) + '-01'))
	SET @lToDate = CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '-' + CONVERT(NVARCHAR(2), @rMonth) + '-' + CAST(@Days AS NVARCHAR(2))))

	CREATE TABLE #Temp (
		id INT NOT NULL IDENTITY PRIMARY KEY
		,AllDate DATE
		);

	WITH AllDays
	AS (
		SELECT @lFromDate AS MyDate
			,1 AS [level]
		
		UNION ALL
		
		SELECT DATEADD(DAY, 1, MyDate)
			,[level] + 1
		FROM AllDays
		WHERE MyDate < @lToDate
		)
	INSERT INTO #Temp (AllDate)
	SELECT MyDate
	FROM AllDays
	OPTION (MAXRECURSION 0)

	SELECT A.ClassId
		,A.DivisionId
		,vCD.ClassDivisionName
		,ISNULL(EM.FirstName + ' ' + EM.LastName, '') AS ClassTeacherName
		,T.id AS DayPart
		,CASE 
			WHEN ([sAttendance].[fWeekHOffGet](@rYear, @rMonth, T.id, @rBatchId, A.ClassId, A.DivisionId, '', @rOrgId)) != ''
				THEN ([sAttendance].[fWeekHOffGet](@rYear, @rMonth, T.id, @rBatchId, A.ClassId, A.DivisionId, '', @rOrgId))
			ELSE CASE 
					WHEN COUNT(SR.AcademicId) = 0
						THEN CASE 
								WHEN (
										SELECT [sCommon].[fCountAbsentStudent](A.DivisionId, @rBatchId, T.AllDate, @rAttendanceTypeId, 0)
										) = 0
									THEN 'P'
								ELSE 'C'
								END
					ELSE 'C'
					END
			END AS AttendanceStatus
	INTO #TempDaysTempTable
	FROM #Temp T
	INNER JOIN sStudent.tAcademic A ON 1 = 1
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		AND SM.StatusId = 1
	INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId = A.ClassId
		AND vCD.OrgId = @rOrgId
		AND vCD.DivisionId = A.DivisionId
		AND A.OrgId = vCD.OrgId
		AND A.OrgId = @rOrgId
		AND A.BatchId = @rBatchId
		AND vCD.IsObsolete = 0
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId
		AND DM.OrgId = @rOrgId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
		AND ISNULL(EM.IsOtherUser, 0) = 0
	LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.IsPresent = 1
		AND T.AllDate = SR.AttendanceDate
	GROUP BY A.DivisionId
		,A.BatchId
		,vCD.ClassDivisionName
		,vCD.OrderIndex
		,EM.FirstName
		,EM.LastName
		,SM.StatusId
		,A.ClassId
		,T.id
		,T.AllDate

	SELECT @rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,ClassId
		,DivisionId
		,ClassDivisionName
		,ClassTeacherName
		,[1] AS D1
		,[2] AS D2
		,[3] AS D3
		,[4] AS D4
		,[5] AS D5
		,[6] AS D6
		,[7] AS D7
		,[8] AS D8
		,[9] AS D9
		,[10] AS D10
		,[11] AS D11
		,[12] AS D12
		,[13] AS D13
		,[14] AS D14
		,[15] AS D15
		,[16] AS D16
		,[17] AS D17
		,[18] AS D18
		,[19] AS D19
		,[20] AS D20
		,[21] AS D21
		,[22] AS D22
		,[23] AS D23
		,[24] AS D24
		,[25] AS D25
		,[26] AS D26
		,[27] AS D27
		,[28] AS D28
		,(CASE WHEN @Days >= 29 THEN [29] ELSE '' END)AS D29 
		,(CASE WHEN @Days >= 30 THEN [30] ELSE '' END) AS D30
		,(CASE WHEN @Days >= 31 THEN [31] ELSE '' END) AS D31
		,TotalPending
		,TotalComplete
		,TotalHoliday
		,TotalWeekOff
	FROM (
		SELECT *
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'P'
				) AS TotalPending
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'C'
				) AS TotalComplete
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'H'
				) AS TotalHoliday
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'W'
				) AS TotalWeekOff
		FROM #TempDaysTempTable T
		) d
	pivot(min(AttendanceStatus) FOR DayPart IN (
				[1]
				,[2]
				,[3]
				,[4]
				,[5]
				,[6]
				,[7]
				,[8]
				,[9]
				,[10]
				,[11]
				,[12]
				,[13]
				,[14]
				,[15]
				,[16]
				,[17]
				,[18]
				,[19]
				,[20]
				,[21]
				,[22]
				,[23]
				,[24]
				,[25]
				,[26]
				,[27]
				,[28]
				,[29]
				,[30]
				,[31]
				)) piv;


	-- For Drag n Drop DataSet for Report
	--SELECT '' AS Builder1
	--	,'' AS Builder2
	--	,0 AS ClassId
	--	,0 AS DivisionId
	--	,'' AS ClassDivisionName
	--	,'' AS ClassTeacherName
	--	,'' AS D1
	--	,'' AS D2
	--	,'' AS D3
	--	,'' AS D4
	--	,'' AS D5
	--	,'' AS D6
	--	,'' AS D7
	--	,'' AS D8
	--	,'' AS D9
	--	,'' AS D10
	--	,'' AS D11
	--	,'' AS D12
	--	,'' AS D13
	--	,'' AS D14
	--	,'' AS D15
	--	,'' AS D16
	--	,'' AS D17
	--	,'' AS D18
	--	,'' AS D19
	--	,'' AS D20
	--	,'' AS D21
	--	,'' AS D22
	--	,'' AS D23
	--	,'' AS D24
	--	,'' AS D25
	--	,'' AS D26
	--	,'' AS D27
	--	,'' AS D28
	--	,'' AS D29
	--	,'' AS D30
	--	,'' AS D31
	--	,0 AS TotalPending
	--	,0 AS TotalComplete
	--	,0 AS TotalHoliday
	--	,0 AS TotalWeekOff
END
GO
PRINT N'Creating Procedure [sAcademic].[pRptDailyStatusYearlyDetailGet]...';


GO
CREATE PROCEDURE [sAcademic].[pRptDailyStatusYearlyDetailGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rOrgId SMALLINT
	,@rBatchId BIGINT
	,@rClassId INT=0
	,@rDivisionId INT=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,DM.ClassId
		,DM.Id AS DivisionId
		,DM.Code AS ClassDivisionName
		,ISNULL(EM.FirstName + ' ' + EM.LastName, '') AS ClassTeacherName
		,ISNULL((MM.Code + '-' + CONVERT(NVARCHAR, MY.YearNumber)),'') AS MonthDetail
		,CONVERT(DATE, MR.UpdatedDateTime) AS Date
		,MY.MonthNumber
		,MY.YearNumber
	FROM sSetup.tDivisionMaster DM
	LEFT JOIN sStudent.vStudentName SN ON SN.DivisionId = DM.Id
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId = SN.BatchId
	INNER JOIN sCommon.tMonthMaster MM ON MY.MonthNumber = MM.Id
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId = SN.AcademicId AND MR.ForMonth = MY.MonthNumber AND MR.ForYear = MY.YearNumber
	WHERE DM.IsObsolete = 0	AND DM.OrgId = @rOrgId
	AND (DM.ClassId	= @rClassId	OR @rClassId = 0)
	AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
	AND 
	((ISNULL(MY.YearNumber,0) < YEAR(GETDATE())) OR
	(ISNULL(MY.MonthNumber, 0) <= MONTH(GETDATE()) AND ISNULL(MY.YearNumber,0) = YEAR(GETDATE())))
	GROUP BY DM.ClassId,DM.Id,DM.Code,MM.Code,MY.YearNumber,DM.OrderIndex,MY.MonthNumber,CONVERT(DATE, MR.UpdatedDateTime),EM.FirstName,EM.LastName
	ORDER BY DM.OrderIndex, MY.YearNumber, MY.MonthNumber, CONVERT(DATE, MR.UpdatedDateTime) DESC

END
GO
PRINT N'Creating Procedure [sAlert].[pMonthlySubjectwiseAttendanceGet]...';


GO

--declare @rBatchId int =991100105,@rForMonth int =10,@rForYear int=2023,@rSubjectId int=991100004,
--@rClassId int=991100001,@rDivisionId int =991100001,
--@rTemplate nvarchar(max)='[Name] [Class] [Division] [ForYear] [ForMonth] [TotalCount] [PresentCount] [AbsentCount] [AveragePresence] [AbsentDates]', @rMailSubject nvarchar(500)=''

CREATE PROCEDURE [sAlert].[pMonthlySubjectwiseAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rForYear smallint,
	 	 @rForMonth tinyint,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	select 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		replace(
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[Name]',SC.Name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[ForYear]',MY.YearNumber),
		'[ForMonth]',MM.Title),
		'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
		'[PresentCount]',convert(decimal(5,2),isnull(TCount,0.00))),
		'[AbsentCount]',convert(decimal(5,2),isnull(ACount,0.00))),
		'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 
							0.00 end),
		'[AbsentDates]',[sAttendance].[fAbsentDaysGet](MY.MonthNumber,MY.YearNumber, 5,@rSubjectId,SC.AcademicId)),
		'[SubjectName]',CS.SubjectName)
			AS MsgText,
			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			MY.YearNumber as ForYear,
			MM.Title AS ForMonth,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(5,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(5,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 
							0.00 end as AveragePresence,
			[sAttendance].[fAbsentDaysGet](MY.MonthNumber,MY.YearNumber, 5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	 from 
	sStudent.vStudentCommunication SC 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SC.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	--LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SC.ClassId
	--	AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber AND MS.BatchId=@rBatchID
	--LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SC.AcademicId
	--	AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId)
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId) 
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	INNER JOIN sCommon.tMonthMaster MM ON MY.MonthNumber = MM.Id
	Inner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId AND CS.SubjectId=@rSubjectId
	WHERE
	(MY.BatchId=@rBatchId) 
	 AND SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
End
GO
PRINT N'Creating Procedure [sAttendance].[pDateWiseAttendanceStrengthGet]...';


GO
CREATE PROCEDURE sAttendance.pDateWiseAttendanceStrengthGet
	@rUserId bigint,
	@rMonth smallint,
	@rYear int,
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempAttendanceData') IS NOT NULL
		DROP TABLE #TempAttendanceData

	IF OBJECT_ID('tempdb..#TempDaysTempTable') IS NOT NULL
		DROP TABLE #TempDaysTempTable

	IF OBJECT_ID('tempdb..#TempData') IS NOT NULL
		DROP TABLE #TempData

	SELECT DISTINCT DM.Id AS DivisionId
		,CM.Id AS ClassId
		,OM.DisplayTitle + ' - ' + CM.Title + ' - ' + DM.Title AS ClassDivision
	INTO #TempData
	FROM sSetup.tClassMaster CM
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id
	WHERE U.SourceTypeId = 2005
		AND U.UserId = @rUserId

	DECLARE @li INT, @Days INT, @lOrgGroupBatchId int
	SELECT @lOrgGroupBatchId = (SELECT OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId)
	SET @li = 1
	SELECT @Days = sCommon.fGetDaysInMonth(@rMonth, @rYear)

	CREATE TABLE #TempDaysTempTable (
		DayPart INT
		,WHDate DATE
		,Value NVARCHAR(20)
		,ClassId INT
		,DivisionId INT
		,ClassDivision NVARCHAR(200)
	)

	WHILE @li <= @Days
	BEGIN
		INSERT INTO #TempDaysTempTable (
			DayPart
			,WHDate
			,Value
			,ClassId
			,DivisionId
			,ClassDivision
		)
		SELECT @li AS DayPart
			,CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '/' + CONVERT(NVARCHAR(2), @rMonth) + '/' + CONVERT(NVARCHAR(2), @li)))
			,[sAttendance].[fWeekHOffGet](@rYear, @rMonth, @li, @rBatchId, ClassId, DivisionId, '', @rOrgId) AS STATUS
			,ClassId
			,DivisionId
			,ClassDivision
		FROM #TempData

		SET @li = @li + 1
	END

	CREATE TABLE #TempAttendanceData (
		AttendanceDate DATE
		,StudentCount INT
		,AttendanceType SMALLINT
		,DivisionId INT
	)

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Present
		,1 -- For Present
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 1
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Absent
		,2 -- For Absent
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 0
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	-- Class Division List
	SELECT *
	FROM #TempData

	-- Attendance and WeekOff/Holiday Data
	
	SELECT AttendanceDate, SUM(Present) AS Present, SUM(Absent) AS Absent, SUM(Present) + SUM(Absent) AS Total,  DivisionId, ClassDivision, MIN(STATUS) AS STATUS FROM 
	(SELECT AttendanceDate
		,SUM(Present) AS Present
		,SUM(Absent) AS Absent
		--,SUM(Present) + SUM(Absent) AS Total
		,T.DivisionId
		,T.ClassDivision
		,T.Value AS STATUS
	FROM (
		SELECT AttendanceDate
			,CASE 
				WHEN AttendanceType = 1
					THEN SUM(StudentCount)
				ELSE 0
				END AS Present
			,CASE 
				WHEN AttendanceType = 2
					THEN SUM(StudentCount)
				ELSE 0
				END AS Absent
			,DivisionId
		FROM #TempAttendanceData
		GROUP BY AttendanceDate
			,AttendanceType
			,StudentCount
			,DivisionId
		) AS A
	LEFT JOIN #TempDaysTempTable T ON T.WHDate = A.AttendanceDate
		AND T.DivisionId = A.DivisionId
	GROUP BY A.AttendanceDate
		,T.DivisionId
		,T.ClassDivision
		,T.Value

	UNION

	SELECT WHDate AS AttendanceDate
		,0 AS Present
		,0 AS Absent
		--,0 AS Total
		,DivisionId
		,ClassDivision
		,Value AS STATUS
	FROM #TempDaysTempTable
	WHERE ISNULL(Value, '') <> '' ) A 
	GROUP BY AttendanceDate, DivisionId, ClassDivision
END
GO
PRINT N'Creating Procedure [sAttendance].[pRptAttendanceFollowupListGet]...';


GO
CREATE PROCEDURE [sAttendance].[pRptAttendanceFollowupListGet]

		@rBuilder1 nvarchar(max),
	 	@rClassId int,
	 	@rDivisionId int,
	 	@rAttendanceTypeId tinyint,
		@rFromDate date,
		@rToDate date,
	 	@rBatchId int,
	 	@rOrgId int,
		@rPresentStatus int,
		@rCode nvarchar(20)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT
	@rBuilder1 AS Builder1,
	SA.AcademicId,
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent,
	(isnull(SC.PresentStreetOne,'')+' '+isnull(SC.PresentStreetTwo,'')+' '+isnull(SC.PresentStreetThree,'')+' '+isnull(SC.PresentCity,'')+' '+isnull(SC.PresentState,'')+' '+isnull(SC.PresentCountry,'')) as PresentAdress

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId

	WHERE
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END
GO
PRINT N'Creating Procedure [sBiometric].[pRptTimesheetSummaryListGet]...';


GO


CREATE PROCEDURE [sBiometric].[pRptTimesheetSummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 )  
  INSERT INTO #TempMonthTrans  
   
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 --WHEN  AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'  
			 --WHEN D01 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 When ((D01='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D01_IN ='00:00'))  then 'A'
			 ELSE D01 END ,	
	D01_L,D01_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 --WHEN D02 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'  
			 --WHEN D02 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			  When ((D02='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D02_IN ='00:00'))  then 'A'
			 ELSE D02 END ,	
	D02_L,D02_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 --WHEN D03 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'  
			 --WHEN D03 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 When ((D03='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D03_IN ='00:00'))  then 'A'
			 ELSE D03 END ,	
	D03_L,D03_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 --WHEN D04 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'  
			 --WHEN D04 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 When ((D04='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D04 END ,	
	D04_L,D04_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 --WHEN D05 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'  
			 --WHEN D05 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			  When ((D05='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D05_IN ='00:00'))  then 'A'
			 ELSE D05 END ,	
	D05_L,D05_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 --WHEN D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'  
			 --WHEN D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			  When ((D06='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D06 END ,	
	D06_L,D06_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 --WHEN D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'  
			 --WHEN D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			  When ((D07='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D07_IN ='00:00'))  then 'A'
			 ELSE D07 END ,	
	D07_L,D07_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 --WHEN D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'  
			 --WHEN D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			  When ((D08='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D08_IN ='00:00'))  then 'A'
			 ELSE D08 END ,	
	D08_L,D08_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 --WHEN D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'  
			 --WHEN D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			  When ((D09='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D09_IN ='00:00'))  then 'A'
			 ELSE D09 END ,	
	D09_L,D09_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 --WHEN D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'  
			 --WHEN D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			  When ((D10='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D10_IN ='00:00'))  then 'A'
			 ELSE D10 END ,	
	D10_L,D10_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 --WHEN D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'  
			 --WHEN D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			  When ((D11='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D11_IN ='00:00'))  then 'A'
			 ELSE D11 END ,
	D11_L,D11_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 --WHEN D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'  
			 --WHEN D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			  When ((D12='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D12_IN ='00:00'))  then 'A'
			 ELSE D12 END ,	
	D12_L,D12_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 --WHEN D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'  
			 --WHEN D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			  When ((D13='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D13_IN ='00:00'))  then 'A'
			 ELSE D13 END ,	
	D13_L,D13_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 --WHEN D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'  
			 --WHEN D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			  When ((D14='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D14_IN ='00:00'))  then 'A'
			 ELSE D14 END ,	
	D14_L,D14_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 --WHEN D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'  
			 --WHEN D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			  When ((D15='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D15_IN ='00:00'))  then 'A'
			 ELSE D15 END ,	
	D15_L,D15_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 --WHEN D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'  
			 --WHEN D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			  When ((D16='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D16_IN ='00:00'))  then 'A'
			 ELSE D16 END ,	
	D16_L,D16_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 --WHEN D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'  
			 --WHEN D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			  When ((D17='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D17_IN ='00:00'))  then 'A'
			 ELSE D17 END ,	
	D17_L,D17_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 --WHEN D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'  
			 --WHEN D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			  When ((D18='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D18_IN ='00:00'))  then 'A'
			 ELSE D18 END ,	
	D18_L,D18_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 --WHEN D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'  
			 --WHEN D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			  When ((D19='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D19_IN ='00:00'))  then 'A'
			 ELSE D19 END ,	
	D19_L,D19_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 --WHEN D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'  
			 --WHEN D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			  When ((D20='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D20_IN ='00:00'))  then 'A'
			 ELSE D20 END ,		
	D20_L,D20_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 --WHEN D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'  
			 --WHEN D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			  When ((D21='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D21_IN ='00:00'))  then 'A'
			 ELSE D21 END ,	
	D21_L,D21_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 --WHEN D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'  
			 --WHEN D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			  When ((D22='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D22_IN ='00:00'))  then 'A'
			 ELSE D22 END ,		
	D22_L,D22_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 --WHEN D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'  
			 --WHEN D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			  When ((D23='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D23_IN ='00:00'))  then 'A'
			 ELSE D23 END ,	
	D23_L,D23_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 --WHEN D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'  
			 --WHEN D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			  When ((D24='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D24_IN ='00:00'))  then 'A'
			 ELSE D24 END ,	
	D24_L,D24_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 --WHEN D25 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'  
			 --WHEN D25 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			  When ((D25='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D25_IN ='00:00'))  then 'A'
			 ELSE D25 END ,	
	D25_L,D25_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 --WHEN D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'  
			 --WHEN D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			  When ((D26='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D26_IN ='00:00'))  then 'A'
			 ELSE D26 END ,	
	D26_L,D26_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 --WHEN D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'  
			 --WHEN D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			  When ((D27='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D27_IN ='00:00'))  then 'A'
			 ELSE D27 END ,	
	D27_L,D27_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 --WHEN D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'  
			 --WHEN D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			  When ((D28='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D28_IN ='00:00'))  then 'A'
			ELSE D28 END ,	D28_L,D28_E
			FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
			AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	IF  @rForMonth <> 2 or ((@rForYear % 4 = 0 AND @rForYear % 100 <> 0) OR @rForYear % 400 = 0 And @rForMonth  =2)
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 --WHEN D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'  
			 --WHEN D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			  When ((D29='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D29_IN ='00:00'))  then 'A'
			 ELSE D29 END ,	
	D29_L,D29_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 --WHEN D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'  
			 --WHEN D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			  When ((D30='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D30_IN ='00:00'))  then 'A'
			 ELSE D30 END ,	
	D30_L,D30_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,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 , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 --WHEN D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'  
			 --WHEN D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			  When ((D31='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D31_IN ='00:00'))  then 'A'
			 ELSE D31 END ,	
	D31_L,D31_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	--select * from #TempMonthTrans

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		EM.Code as EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS WeekOffsWiseTotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS WeekOffsWiseTotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS WeekOffsWiseTotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS WeekOffsWiseTotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS WeekOffsWiseTotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS WeekOffsWiseTotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS WeekOffsWiseTotalErrorCase

	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

	DROP Table #TempMonthTrans

	--SELECT
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	cast(0 as bigint) as EmployeeId,
	--	'' as EmpCode,
	--	'' AS EmployeeName,  
	--	cast(0 as float)  AS TotalPresentDays,
	--	cast(0 as float) AS TotalAbsentDays,
	--	cast(0 as int) AS TotalWeekOffs,
	--	cast(0 as int) AS TotalHolidays,
	--	cast(0 as smallint) AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	cast(0 as int) AS OrganizationOrderIndex,
	--	cast(0 as bigint) AS EmployeeNumber,
	--	cast(0 as int) AS TotalDays,
	--	cast(0 as int) AS Count_Late,
	--	cast(0 as int) AS WeekOffsWiseTotalAbsentDays,
	--	cast(0 as int) AS WeekOffsWiseTotalWeekOffs,
	--	cast(0 as int) AS WeekOffsWiseTotalHolidays,
	--	cast(0 as int) AS WeekOffsWiseTotalPresentDays,
	--	cast(0 as int) AS WeekOffsWiseTotalHalfDays,
	--	cast(0 as int) AS WeekOffsWiseTotalLessHours,
	--	cast(0 as int) AS WeekOffsWiseTotalErrorCase
END
GO
PRINT N'Creating Procedure [sBiometric].[pShiftMasterDelete]...';


GO
 
CREATE PROCEDURE [sBiometric].[pShiftMasterDelete]
	@rShiftcode int,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	 
  		IF EXISTS( SELECT 1 FROM sHrm.tEmployeeMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT 101 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM sStudent.tStudentMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT -102 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM  sBiometric.tShiftAllocationCloud WHERE ShiftCode = @rShiftcode)	
		BEGIN
			SELECT -103 AS RESULT
		END 
		ELSE
		BEGIN
			DELETE FROM sBiometric.tShiftMasterCloud WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END


	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sBiometric].[pTimeSheetListStudentGet]...';


GO

CREATE PROCEDURE [sBiometric].[pTimeSheetListStudentGet]
	@rOrgId int,
	@rFromDate DateTime,  
    @rToDate DateTime, 
	@rStudentId bigint,
	@rClassId int=0,
	@rDivisionId int=0,
	@rStatusId int=0,
	@rBatchId  int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
    ShiftName nvarchar(25) 
	
	)

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId = 2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)

	--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),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)
	--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),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 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 ( SourceTypeId =2003)
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 --When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(AD.AdmissionDate as date)<= Cast(TM.Attn_Date as date) OR ISNULL(AD.AdmissionDate,'')='')AND (AD.LeftDate>= Cast(TM.Attn_Date as date) OR ISNULL(AD.LeftDate,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 
		--INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId

--select * from #TempMonthTrans 
	Select 
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		TM.Attn_Date AS  Attn_Date,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		TM.PresentStatus as PresentStatus,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		 From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2003 
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.EmployeeId AND MT.SourceTypeId=2003 
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	
	WHERE 
			SA.OrgId=@rOrgId 
			AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			AND SA.BatchId = @rBatchId
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	
END
GO
PRINT N'Creating Procedure [sCommunication].[pCircularConsentResultAdd]...';


GO


CREATE PROCEDURE [sCommunication].[pCircularConsentResultAdd]
	 
		@rSourceId bigint,
        @rCircularConsentId bigint,
		@rCircularConsentAns nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsentResult]
		(
			SourceId,
			CircularConsentId,
			CircularConsentAns
		)
	VALUES
		(
			@rSourceId,
			@rCircularConsentId,
			@rCircularConsentAns
		)

	 
	 SELECT 1 AS Result

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sCommunication].[pCircularConsentResultGet]...';


GO


CREATE PROCEDURE [sCommunication].[pCircularConsentResultGet]
	 	 
		 @rCircularId bigint,
	 	 @rOrgId int
	 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			A.Code,
			A.Name,
			A.CircularConsentAns,
			A.ClassDept
	From 
			sCommunication.tCircular CR
			
			INNER JOIN (
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2001
			
			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 95
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2
				

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2017 AND CS.AssigneeToId = 3 

			UNION ALL	
		
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2016 AND CS.AssigneeToId = 2 
				

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2005 AND CS.AssigneeToId = 2 
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.OrgId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 2 

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 3 
			
		) as A ON A.CircularId = CR.Id 
	WHERE
			A.OrgId = @rOrgId AND A.CircularId = @rCircularId
END
GO
PRINT N'Creating Procedure [sCommunication].[pDailyThoughtAssignSearchGet]...';


GO
CREATE PROCEDURE [sCommunication].[pDailyThoughtAssignSearchGet]
	 @rOrgId int,
	 @rDay smallint,
	 @rMonth smallint,
	 @rDivisionId int = 0,
	 @rClassId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT
		DTA.DailyThoughtId AS Id,
		STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
		STUFF ((SELECT ', '+ Title
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
		STUFF ((SELECT ', '+ Remark
		FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
		FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
	FROM 
		sCommunication.tDailyThoughtAssign DTA 
	WHERE DTA.OrgId = @rOrgId 
		AND DTA.Day = @rDay AND DTA.Month = @rMonth 
		AND (((DTA.SourceTypeId = 2021 AND DTA.SourceId = @rOrgId) OR (DTA.SourceTypeId IS NULL AND DTA.SourceId IS NULL)) OR
			   ((DTA.SourceTypeId = 2005 AND DTA.SourceId = @rDivisionId)) 
			OR ((DTA.SourceTypeId = 2016 AND DTA.SourceId = @rClassId)))
	ORDER BY DTA.AutoId DESC
END
GO


CREATE PROCEDURE [sHrm].[pEmployeeGet] 
	 @rFirstName NVARCHAR(50) = ''
	,@rLastName NVARCHAR(50) = ''
	,@rID NVARCHAR(50) = ''
	,@rOrgGroupId INT = 0
	,@rMiddleName NVARCHAR(50) = ''
	,@rContactNo NVARCHAR(50) = ''
	,@rCommonSearch NVARCHAR(500) = ''
	,@rUserId BIGINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		CREATE TABLE #EmpAutoSearchTemp
		(
			EmployeeId Bigint,
			EmployeeData nvarchar(max),
		)
		INSERT INTO #EmpAutoSearchTemp
		SELECT
			EM.Id AS EmployeeId,
			EM.FirstName +' '+EM.MiddleName +' '+EM.LastName+' '+DM.DisplayTitle+' '+EM.Code AS EmployeeData
		FROM 
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId

	SELECT [sHrm].[fEmployeeNameGet](VEM.FirstName, VEM.MiddleName, VEM.LastName, OM.StudentNameFormatId) AS Name
		,SM.Title AS StatusName
		,VEM.Id AS EmployeeId
		,VEM.Code
		,OM.DisplayTitle AS Organization
		,VEM.DepartmentName
		,VEM.DepartmentId
		,CASE 
			WHEN RIGHT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.Id)), ' ', ''), 1) = ','
				THEN reverse(stuff(reverse(([sHrm].[fEmployeeContactsGet](VEM.Id))), 1, 1, ''))
			WHEN LEFT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.Id)), ' ', ''), 1) = ','
				THEN STUFF(([sHrm].[fEmployeeContactsGet](VEM.Id)), 1, 1, '')
			ELSE ([sHrm].[fEmployeeContactsGet](VEM.Id)) END AS ContactNo
		,EAS.EmployeeData
		,VEM.OrgId
		,ISNULL(EC.MobileNumber, '') AS MobileNumber
		,ISNULL(EC.CompanyEmail, '') AS Email
		,ISNULL(EI.EmployeePhoto, 0x) AS EmployeePhoto
		,ISNULL(U.Id, 0) AS UserId
		,EC.WhatsAppContactNo
	FROM [sCommon].[vEmployeeMaster] VEM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = VEM.OrgId
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = VEM.ID
	LEFT JOIN [sHrm].[tEmployeeFamilyDetails] EF ON EF.EmployeeId = VEM.Id
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VEM.StatusId
	INNER JOIN #EmpAutoSearchTemp EAS ON EAS.EmployeeId = VEM.Id
	LEFT JOIN [sHrm].[tEmployeeImages] EI ON EI.EmployeeId = VEM.ID
	LEFT JOIN sSecurity.tUser U ON U.OrgId = OM.Id AND U.SourceId = VEM.ID AND U.SourceTypeId = 95
	WHERE ((VEM.FirstName LIKE @rFirstName + '%') OR (@rFirstName = ''))
		AND ((VEM.LastName LIKE @rLastName + '%') OR (@rLastName = ''))
		AND ((VEM.MiddleName LIKE @rMiddleName + '%') OR (@rMiddleName = ''))
		AND ((VEM.Code = @rID) OR (@rID = ''))
		AND ((EC.MobileNumber = @rContactNo) OR (EC.PermanentContactNo = @rContactNo) OR (EC.EmergencyContactNo = @rContactNo) 
			OR (EC.PhoneNoCompany = @rContactNo) OR (EC.PresentContactNo = @rContactNo) OR (EC.WhatsAppContactNo = @rContactNo) OR (@rContactNo = ''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((EAS.EmployeeData LIKE '%' + @rCommonSearch + '%') OR (@rCommonSearch = ''))
END
GO
PRINT N'Creating Procedure [sHrm].[pStaffBiometricDashboardGet]...';


GO
CREATE PROCEDURE [sHrm].[pStaffBiometricDashboardGet]
	@rTypeId smallint,
	@rDate date,
	@rOrgGroupId int,
	@rCommonOrgGroupBatchId int,
	@rOrgId int=0,
	@rDepartmentId int=0,
	@rStatusId smallint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	Declare @lQuery nvarchar(Max)
	DECLARE @lDay as nvarchar(3)
	DECLARE @lMonth as nvarchar(3)
	DECLARE @lYear as nvarchar(4)



 
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rDate) AS varchar(4)), 4)


	if(@rTypeId=1)
	BEGIN
		set @lQuery ='SELECT     
						OGM.Id AS OrgGroupId,
						OGM.Title As OrgGroupTitle,
						0 As DepartmentId,
						'''' As DepartmentCode,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' then 1 else 0 end) as INCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' then 1 else 0 end) as OUTCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00''  then 1 else 0 end) as BothCount,
						Count(EM.Id) as TotalCount	 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId ='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 Group by OGM.Id,OGM.Title'


		--print @lQuery
		EXECUTE(@lQuery)
	END
	Else if(@rTypeId=2)
	BEGIN
		set @lQuery ='SELECT     
						OGM.Id AS OrgGroupId,
						OGM.Title As OrgGroupTitle,
						(DME.Id) As DepartmentId,
						DME.Code As DepartmentCode,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' then 1 else 0 end) as INCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' then 1 else 0 end) as OUTCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00''  then 1 else 0 end) as BothCount,
						Count(EM.Id) as TotalCount	 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId ='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 Group by OGM.Id,OGM.Title,(DME.Id),DME.Code'
		--print @lQuery
		EXECUTE(@lQuery)
	End
	

	Else if(@rTypeId=3)
	BEGIN
		set @lQuery ='SELECT   
						(EM.Id)EmployeeID,
						EM.Code EmployeeCode,
						(EM.FirstName+'' ''+EM.LastName) AS EmployeeName,  
						Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') as  IN_Time,
						Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'') as OUT_Time
						 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0 
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 
				AND  (DME.Id='+convert(nvarchar(20),@rDepartmentId)+'  OR 0='+convert(nvarchar(20),@rDepartmentId)+' )
				AND (( '+convert(nvarchar(20),@rStatusId)+'=1 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'') OR
					(  '+convert(nvarchar(20),@rStatusId)+'=2 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'') OR
					( '+convert(nvarchar(20),@rStatusId)+'=3 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' ) OR
					( '+convert(nvarchar(20),@rStatusId)+'=0 ))'
		--print @lQuery
		EXECUTE(@lQuery)
	End
END

GO


CREATE PROCEDURE [sTimetable].[pDeleteTimeTable]

	  @rSelectScreen nvarchar(100),
	  @rTimeTableSchemaId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSelectScreen='Proxy Setting')
	BEGIN
		DELETE FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Assign Time Table Time')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 101 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Time Table')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 102 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Teacher Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 103 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Division Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 104 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Time Setup')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 105 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END
END
GO
PRINT N'Creating Procedure [sTimetable].[pTimeTableTimeListGet]...';


GO
CREATE PROCEDURE [sTimetable].[pTimeTableTimeListGet]

		@rBatchId int,
		@rDayIds nvarchar(100)='',
		@rLectureNo smallint,
		@rTimeTableSchemaId int,
		@rOrgId int=0,
		@rDivisionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		TTT.TimeTableSchemaId AS TimeTableSchemaId,
		TTT.AutoId AS AutoId,
		DV.Title AS DivisionName,
		TTT.DivisionId,
		ISNULL(DM.Title,'') AS DayName,
		ISNULL(TTT.DayId,0) AS DayId,
		ISNULL(TTT.LectureNumber,'') AS LactureNumber,
		ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TTT.LectureNumber),'') AS DayLacture,
		ISNULL(DV.Code,'') AS ClassDivisionName
		,ISNULL(TTT.FromTime,'') AS FromTime
		,ISNULL(TTT.ToTime,'') AS ToTime

	FROM
		sTimetable.tTimeTableTime TTT
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TTT.DayId
		INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TTT.DivisionId

	WHERE
		TTT.TimeTableSchemaId=@rTimeTableSchemaId
		AND (TTT.DayId IN (SELECT CAST(item AS int) FROM  sCommon.fnsplit(@rDayIds,',')) OR (@rDayIds = ''))
		AND ((TTT.LectureNumber = @rLectureNo) OR (@rLectureNo = 0))
		AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ISNULL(TTT.IsBreak,0)=0
		AND ISNULL(TTT.IsBreakBefore,0)=0
		AND ((ISNULL(TTT.DivisionId,0)=@rDivisionId) OR (@rDivisionId=0))
	ORDER BY TTT.LectureNumber
END
GO

PRINT N'Refreshing Function [sBiometric].[fBiometricTempMonthTransGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[fBiometricTempMonthTransGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pOrganizationSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOrganizationSetupRemove]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pLeavingBulkGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingBulkGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pRptStudentLCVerificationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pRptStudentLCVerificationGet]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pRptOtherCertificateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pRptOtherCertificateGet]';


GO
PRINT N'Refreshing Procedure [sErp].[pOrgGroupModuleSummaryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sErp].[pOrgGroupModuleSummaryGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pForceStudentDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pForceStudentDelete]';


GO
PRINT N'Refreshing Procedure [sAlert].[pStudentLeavingCertificateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pStudentLeavingCertificateGet]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pLeavingBulkAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pLeavingBulkAdd]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pOverallCertificateCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pOverallCertificateCountGet]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pSummaryCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pSummaryCountGet]';


GO
PRINT N'Refreshing Procedure [sCertificate].[pTemplateFunctionalFieldsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCertificate].[pTemplateFunctionalFieldsGet]';


GO
PRINT N'Refreshing Procedure [sSetup].[pOrganizationWiseStudentDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSetup].[pOrganizationWiseStudentDelete]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularConsentAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularConsentAdd]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pCircularConsentGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pCircularConsentGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pDailyThoughtAssignGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pDailyThoughtAssignGet]';


GO
PRINT N'Refreshing Procedure [sCommunication].[pDailyThoughtGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommunication].[pDailyThoughtGet]';


GO
PRINT N'Refreshing Procedure [sOp].[pGatewayProductReceiptBookMappingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOp].[pGatewayProductReceiptBookMappingGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pOrgGroupSetupRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOrgGroupSetupRemove]';


GO
PRINT N'Refreshing Procedure [sOp].[pGatewayProductReceiptBookMappingAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOp].[pGatewayProductReceiptBookMappingAdd]';


GO
PRINT N'Refreshing Procedure [sOp].[pPaymentTransactionDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sOp].[pPaymentTransactionDetailGet]';


GO
PRINT N'Refreshing Procedure [sPayroll].[pRemoveProfessionalTaxRange]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPayroll].[pRemoveProfessionalTaxRange]';


GO
PRINT N'Refreshing Procedure [sPayroll].[pRptMonthlyProfessoionTaxSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPayroll].[pRptMonthlyProfessoionTaxSummary]';


GO
PRINT N'Refreshing Procedure [sPayroll].[pPayProcessEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPayroll].[pPayProcessEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [sPayroll].[pPayProcessAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPayroll].[pPayProcessAdd]';



GO
PRINT N'Refreshing Procedure [sAcademic].[pDailyStatusGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pDailyStatusGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pMonthlyStatus]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pMonthlyStatus]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pMonthlyAttenanceRegisterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pMonthlyAttenanceRegisterGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pStudentTimeSheetListGe]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pStudentTimeSheetListGe]';


GO
PRINT N'Refreshing Procedure [sAcademic].[pMonthlyStatusGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAcademic].[pMonthlyStatusGet]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pAttenanceRegisterGetNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGetNew]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pRptDailyStatusGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptDailyStatusGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptMonthlySummaryListDateWiseGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptMonthlySummaryListDateWiseGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptStudentMonthlySummaryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptStudentMonthlySummaryListGet]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pAttenanceRegisterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pAttenanceRegisterGet]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pHoliDayCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pHoliDayCountGet]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pRptStudentRegisterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptStudentRegisterGet]';


GO
PRINT N'Refreshing Procedure [sAttendance].[pRptYearlyAttendanceGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAttendance].[pRptYearlyAttendanceGet]';


GO
PRINT N'Refreshing Procedure [sHostel].[pRptHostelAttendanceSheetGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHostel].[pRptHostelAttendanceSheetGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeAttenanceviewGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeAttenanceviewGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pRptEmployeeAttendanceRegisterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pRptEmployeeAttendanceRegisterGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pRptEmployeeAttendanceRegisterGet_old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pRptEmployeeAttendanceRegisterGet_old]';


GO
PRINT N'Refreshing Procedure [sHrm].[pRptAttendanceSheet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pRptAttendanceSheet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeAttendanceRegisterReportProcess]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeAttendanceRegisterReportProcess]';


GO
PRINT N'Refreshing Procedure [sHrm].[pHoliDayCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pHoliDayCountGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeRegisterAttendanceGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeRegisterAttendanceGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeMonthWiseSandwichDaysCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeMonthWiseSandwichDaysCountGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeRuleApply]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeRuleApply]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeMonthWiseLeaveGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeMonthWiseLeaveGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pBiometricReportData]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pBiometricReportData]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptMonthlySummaryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptMonthlySummaryListGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pBiometricReportDataDateWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pBiometricReportDataDateWise]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptDateWiseTimeSheetSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptDateWiseTimeSheetSummary]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptEmployeeWiseStatusSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptEmployeeWiseStatusSummary]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptTimeSheetListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptTimeSheetListGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptEmployeeWiseMonthlySummaryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptEmployeeWiseMonthlySummaryGet]';


GO
PRINT N'Refreshing Procedure [sBiometric].[pRptMonthlyLateInSummaryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sBiometric].[pRptMonthlyLateInSummaryGet]';


GO
PRINT N'Refreshing Procedure [sStudent].[pStudentDetailFormGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sStudent].[pStudentDetailFormGet]';


GO
PRINT N'Update complete.';

go
ALTER PROCEDURE [sTimetable].[pDeleteTimeTable]

	  @rSelectScreen nvarchar(100),
	  @rTimeTableSchemaId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSelectScreen='Proxy Setting')
	BEGIN
		DELETE FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Assign Time Table Time')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tProxySetting WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 101 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF(@rSelectScreen='Time Table')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 102 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Teacher Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTimeTable WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 103 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Division Work Load')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tTeacherWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 104 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END

	ELSE IF (@rSelectScreen='Time Setup')
	BEGIN
		IF EXISTS(SELECT * FROM sTimetable.tDivisionWorkLoad WHERE TimeTableSchemaId=@rTimeTableSchemaId)
		BEGIN
			SELECT 105 AS Result
			RETURN;
		END
		DELETE FROM sTimetable.tTimeSetup WHERE TimeTableSchemaId=@rTimeTableSchemaId
		SELECT 1 AS Result
	END
END

GO
ALTER PROCEDURE [sTimetable].[pTimeTableTimeListGet]

		@rBatchId int,
		@rDayIds nvarchar(100)='',
		@rLectureNo smallint,
		@rTimeTableSchemaId int,
		@rOrgId int=0,
		@rDivisionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		TTT.TimeTableSchemaId AS TimeTableSchemaId,
		TTT.AutoId AS AutoId,
		DV.Title AS DivisionName,
		TTT.DivisionId,
		ISNULL(DM.Title,'') AS DayName,
		ISNULL(TTT.DayId,0) AS DayId,
		ISNULL(TTT.LectureNumber,'') AS LactureNumber,
		ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TTT.LectureNumber),'') AS DayLacture,
		ISNULL(DV.Code,'') AS ClassDivisionName
		,ISNULL(TTT.FromTime,'') AS FromTime
		,ISNULL(TTT.ToTime,'') AS ToTime

	FROM
		sTimetable.tTimeTableTime TTT
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TTT.DayId
		INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TTT.DivisionId

	WHERE
		TTT.TimeTableSchemaId=@rTimeTableSchemaId
		AND (TTT.DayId IN (SELECT CAST(item AS int) FROM  sCommon.fnsplit(@rDayIds,',')) OR (@rDayIds = ''))
		AND ((TTT.LectureNumber = @rLectureNo) OR (@rLectureNo = 0))
		AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ISNULL(TTT.IsBreak,0)=0
		AND ISNULL(TTT.IsBreakBefore,0)=0
		AND ((ISNULL(TTT.DivisionId,0)=@rDivisionId) OR (@rDivisionId=0))
	ORDER BY TTT.LectureNumber
END


GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('23.11.30',231130,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO

